
const LOGO_URL = "https://lh3.googleusercontent.com/d/1TeKL1F2_xwTSq2tN0ssfqu-EL9N5tbfR";

export type EmailLang = 'en' | 'es';

const escapeHtml = (value: string): string =>
  String(value)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');

export const getEmailStyle = () => `
  @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');

  body {
    font-family: 'Inter', 'Helvetica Neue', Helvetica, Arial, sans-serif;
    line-height: 1.6;
    color: #374151;
    background-color: #f3f4f6;
    margin: 0;
    padding: 0;
    -webkit-font-smoothing: antialiased;
  }

  .wrapper {
    width: 100%;
    background-color: #f3f4f6;
    padding: 40px 0;
  }

  .container {
    max-width: 600px;
    margin: 0 auto;
    background-color: #ffffff;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  }

  .header {
    background: linear-gradient(135deg, #06b6d4 0%, #2563eb 100%);
    padding: 40px 20px;
    text-align: center;
  }

  .logo-img {
    height: 56px;
    width: auto;
    background-color: white;
    padding: 10px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }

  .content {
    padding: 40px 40px 20px 40px;
  }

  h1 {
    font-size: 24px;
    font-weight: 700;
    color: #111827;
    margin-top: 0;
    margin-bottom: 16px;
    text-align: center;
  }

  p {
    font-size: 16px;
    color: #4b5563;
    margin-bottom: 24px;
  }

  .box-container {
    background-color: #f9fafb;
    border: 1px solid #e5e7eb;
    border-radius: 12px;
    padding: 24px;
    text-align: center;
    margin: 32px 0;
  }

  .label {
    font-size: 12px;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    color: #6b7280;
    font-weight: 600;
    margin-bottom: 8px;
  }

  .value {
    font-family: monospace;
    font-size: 24px;
    font-weight: 700;
    color: #2563eb;
    letter-spacing: 0.05em;
  }

  .button {
    display: inline-block;
    padding: 14px 32px;
    background: linear-gradient(135deg, #06b6d4 0%, #2563eb 100%);
    color: #ffffff;
    text-decoration: none;
    border-radius: 8px;
    font-weight: 600;
    font-size: 16px;
    text-align: center;
    transition: opacity 0.2s;
    box-shadow: 0 4px 6px -1px rgba(37, 99, 235, 0.2);
  }

  .button:hover {
    opacity: 0.9;
  }

  .divider {
    height: 1px;
    background-color: #e5e7eb;
    margin: 32px 0;
  }

  .footer {
    padding: 24px;
    background-color: #f9fafb;
    text-align: center;
    border-top: 1px solid #f3f4f6;
  }

  .footer p {
    font-size: 12px;
    color: #9ca3af;
    margin: 4px 0;
  }

  .footer-links {
    margin-top: 12px;
  }

  .footer-link {
    color: #6b7280;
    font-size: 12px;
    text-decoration: none;
    margin: 0 8px;
  }
`;

const footerText = {
  en: { rights: 'All rights reserved.', privacy: 'Privacy Policy', terms: 'Terms of Service', support: 'Contact Support' },
  es: { rights: 'Todos los derechos reservados.', privacy: 'Política de Privacidad', terms: 'Términos de Servicio', support: 'Contactar Soporte' },
};

const getBaseLayout = (content: string, lang: EmailLang = 'en') => {
  const f = footerText[lang];
  return `
<!DOCTYPE html>
<html lang="${lang}">
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>${getEmailStyle()}</style>
</head>
<body>
  <div class="wrapper">
    <div class="container">
      <div class="header">
        <img src="${LOGO_URL}" alt="Medklinix" class="logo-img" />
      </div>
      <div class="content">
        ${content}
      </div>
      <div class="footer">
        <p>&copy; ${new Date().getFullYear()} Medklinix. ${f.rights}</p>
        <div class="footer-links">
          <a href="#" class="footer-link">${f.privacy}</a>
          <a href="#" class="footer-link">${f.terms}</a>
          <a href="#" class="footer-link">${f.support}</a>
        </div>
      </div>
    </div>
  </div>
</body>
</html>
`;
};

export const appointmentReminderTemplate = (name: string, date: string, doctorName: string, lang: EmailLang = 'en') => {
  const t = {
    en: {
      title: 'Appointment Reminder ⏰',
      greeting: `Hello ${name}, this is a reminder for your upcoming appointment.`,
      doctor: 'Doctor',
      time: 'Time',
      note: 'Please arrive 10 minutes early.',
    },
    es: {
      title: 'Recordatorio de Cita ⏰',
      greeting: `Hola ${name}, este es un recordatorio de tu próxima cita.`,
      doctor: 'Doctor',
      time: 'Hora',
      note: 'Por favor llega 10 minutos antes.',
    },
  }[lang];

  const content = `
    <h1>${t.title}</h1>
    <p style="text-align: center;">${t.greeting}</p>

    <div class="box-container">
      <div class="label">${t.doctor}</div>
      <div class="value">${doctorName}</div>
      <div class="label" style="margin-top: 16px;">${t.time}</div>
      <div class="value" style="font-size: 18px; color: #4b5563;">${date}</div>
    </div>

    <p style="text-align: center;">${t.note}</p>

  `;
  return getBaseLayout(content, lang);
};

export const appointmentConfirmationTemplate = (name: string, date: string, doctorName: string, lang: EmailLang = 'en') => {
  const t = {
    en: {
      title: 'Appointment Confirmed ✅',
      greeting: `Hello ${name}, your appointment has been successfully scheduled!`,
      doctor: 'Doctor',
      datetime: 'Date & Time',
      note: 'You will receive reminder notifications before your appointment.',
    },
    es: {
      title: 'Cita Confirmada ✅',
      greeting: `Hola ${name}, ¡tu cita ha sido programada exitosamente!`,
      doctor: 'Doctor',
      datetime: 'Fecha y Hora',
      note: 'Recibirás recordatorios antes de tu cita.',
    },
  }[lang];

  const content = `
    <h1>${t.title}</h1>
    <p style="text-align: center;">${t.greeting}</p>

    <div class="box-container">
      <div class="label">${t.doctor}</div>
      <div class="value">${doctorName}</div>
      <div class="label" style="margin-top: 16px;">${t.datetime}</div>
      <div class="value" style="font-size: 18px; color: #4b5563;">${date}</div>
    </div>

    <p style="text-align: center;">${t.note}</p>

  `;
  return getBaseLayout(content, lang);
};

export const appointmentCancellationTemplate = (name: string, date: string, doctorName: string, lang: EmailLang = 'en') => {
  const t = {
    en: {
      title: 'Appointment Cancelled ❌',
      greeting: `Hello ${name}, we want to inform you that your appointment has been cancelled.`,
      doctor: 'Doctor',
      originalDateTime: 'Original Date & Time',
      note: "If you didn't request this cancellation, please contact us immediately.",
    },
    es: {
      title: 'Cita Cancelada ❌',
      greeting: `Hola ${name}, queremos informarte que tu cita ha sido cancelada.`,
      doctor: 'Doctor',
      originalDateTime: 'Fecha y Hora Original',
      note: 'Si no solicitaste esta cancelación, contáctanos de inmediato.',
    },
  }[lang];

  const content = `
    <h1>${t.title}</h1>
    <p style="text-align: center;">${t.greeting}</p>

    <div class="box-container">
      <div class="label">${t.doctor}</div>
      <div class="value">${doctorName}</div>
      <div class="label" style="margin-top: 16px;">${t.originalDateTime}</div>
      <div class="value" style="font-size: 18px; color: #ef4444;">${date}</div>
    </div>

    <p style="text-align: center;">${t.note}</p>

  `;
  return getBaseLayout(content, lang);
};

export const appointmentCompletedTemplate = (name: string, date: string, doctorName: string, lang: EmailLang = 'en') => {
  const t = {
    en: {
      title: 'Appointment Completed ✅',
      greeting: `Hello ${name}, your appointment has been marked as completed.`,
      doctor: 'Doctor',
      completedAt: 'Completed Appointment Time',
      note: 'Thank you for visiting us. We wish you good health.',
    },
    es: {
      title: 'Cita Completada ✅',
      greeting: `Hola ${name}, tu cita ha sido marcada como completada.`,
      doctor: 'Doctor',
      completedAt: 'Hora de la Cita Completada',
      note: 'Gracias por visitarnos. Te deseamos buena salud.',
    },
  }[lang];

  const content = `
    <h1>${t.title}</h1>
    <p style="text-align: center;">${t.greeting}</p>

    <div class="box-container">
      <div class="label">${t.doctor}</div>
      <div class="value">${doctorName}</div>
      <div class="label" style="margin-top: 16px;">${t.completedAt}</div>
      <div class="value" style="font-size: 18px; color: #16a34a;">${date}</div>
    </div>

    <p style="text-align: center;">${t.note}</p>

  `;
  return getBaseLayout(content, lang);
};

export const appointmentRescheduledTemplate = (
  name: string,
  oldDate: string,
  newDate: string,
  doctorName: string,
  lang: EmailLang = 'en'
) => {
  const t = {
    en: {
      title: 'Appointment Rescheduled 🔄',
      greeting: `Hello ${name}, your appointment schedule has been updated.`,
      doctor: 'Doctor',
      oldDateTime: 'Previous Date & Time',
      newDateTime: 'New Date & Time',
      note: 'Please use the new date and time for your visit.',
    },
    es: {
      title: 'Cita Reprogramada 🔄',
      greeting: `Hola ${name}, el horario de tu cita ha sido actualizado.`,
      doctor: 'Doctor',
      oldDateTime: 'Fecha y Hora Anterior',
      newDateTime: 'Nueva Fecha y Hora',
      note: 'Por favor usa la nueva fecha y hora para tu visita.',
    },
  }[lang];

  const content = `
    <h1>${t.title}</h1>
    <p style="text-align: center;">${t.greeting}</p>

    <div class="box-container">
      <div class="label">${t.doctor}</div>
      <div class="value">${doctorName}</div>
      <div class="label" style="margin-top: 16px;">${t.oldDateTime}</div>
      <div class="value" style="font-size: 18px; color: #ef4444;">${oldDate}</div>
      <div class="label" style="margin-top: 16px;">${t.newDateTime}</div>
      <div class="value" style="font-size: 18px; color: #16a34a;">${newDate}</div>
    </div>

    <p style="text-align: center;">${t.note}</p>

  `;
  return getBaseLayout(content, lang);
};

export const welcomeEmailTemplate = (name: string, lang: EmailLang = 'en') => {
  const t = {
    en: {
      title: `Welcome Aboard, ${name}!`,
      body: "We're thrilled to have you join Medklinix. Your account has been successfully created.",
      access: 'You can now access all the features of our platform to manage your healthcare needs efficiently.',
      button: 'Log In Now',
      help: "If you have any questions, feel free to reply to this email. We're here to help!",
    },
    es: {
      title: `¡Bienvenido, ${name}!`,
      body: 'Estamos muy contentos de tenerte en Medklinix. Tu cuenta ha sido creada exitosamente.',
      access: 'Ahora puedes acceder a todas las funciones de nuestra plataforma para gestionar tu salud de manera eficiente.',
      button: 'Iniciar Sesión',
      help: 'Si tienes alguna pregunta, responde a este correo. ¡Estamos aquí para ayudarte!',
    },
  }[lang];

  const content = `
    <h1>${t.title}</h1>
    <p style="text-align: center;">${t.body}</p>

    <p style="text-align: center; font-size: 16px; margin: 32px 0;">
      ${t.access}
    </p>

    <center><a href="${process.env.FRONTEND_URL}/login" class="button">${t.button}</a></center>

    <div class="divider"></div>
    <p style="font-size: 14px; text-align: center; color: #6b7280;">
      ${t.help}
    </p>
  `;
  return getBaseLayout(content, lang);
};

export const patientAddedTemplate = (name: string, lang: EmailLang = 'en') => {
  const t = {
    en: {
      title: `You Have Been Added as a Patient, ${name}`,
      body: 'A doctor has created your patient profile in Medklinix.',
      access: 'Your details are now available in the clinic system for appointments and records.',
      button: 'Open Login Page',
      help: 'If this was not expected, please contact your clinic.',
    },
    es: {
      title: `Has Sido Añadido Como Paciente, ${name}`,
      body: 'Un doctor ha creado tu perfil de paciente en Medklinix.',
      access: 'Tus datos ahora están disponibles en el sistema de la clínica para citas y registros.',
      button: 'Abrir Inicio de Sesión',
      help: 'Si no esperabas este correo, por favor contacta a tu clínica.',
    },
  }[lang];

  const content = `
    <h1>${t.title}</h1>
    <p style="text-align: center;">${t.body}</p>

    <p style="text-align: center; font-size: 16px; margin: 32px 0;">
      ${t.access}
    </p>
    <div class="divider"></div>
    <p style="font-size: 14px; text-align: center; color: #6b7280;">
      ${t.help}
    </p>
  `;
  return getBaseLayout(content, lang);
};

export const forgotPasswordTemplate = (resetLink: string, lang: EmailLang = 'en') => {
  const t = {
    en: {
      title: 'Reset Your Password',
      body: 'We received a request to reset the password for your Medklinix account.',
      button: 'Reset Password',
      expiry: 'This link is valid for <strong>1 hour</strong>. If you didn\'t request a password reset, you can safely ignore this email.',
      fallback: 'Button not working? Paste this link in your browser:',
    },
    es: {
      title: 'Restablecer Tu Contraseña',
      body: 'Recibimos una solicitud para restablecer la contraseña de tu cuenta en Medklinix.',
      button: 'Restablecer Contraseña',
      expiry: 'Este enlace es válido por <strong>1 hora</strong>. Si no solicitaste este restablecimiento, puedes ignorar este correo.',
      fallback: '¿El botón no funciona? Pega este enlace en tu navegador:',
    },
  }[lang];

  const content = `
    <h1>${t.title}</h1>
    <p style="text-align: center;">${t.body}</p>

    <center style="margin: 32px 0;">
      <a href="${resetLink}" class="button">${t.button}</a>
    </center>

    <p style="text-align: center; font-size: 14px; color: #6b7280;">
      ${t.expiry}
    </p>

    <div class="divider"></div>

    <p style="font-size: 12px; color: #9ca3af; text-align: center; word-break: break-all;">
      ${t.fallback}<br/>
      <a href="${resetLink}" style="color: #2563eb;">${resetLink}</a>
    </p>
  `;
  return getBaseLayout(content, lang);
};

export const subscriptionConfirmationTemplate = (name: string, planName: string, lang: EmailLang = 'en') => {
  const t = {
    en: {
      title: 'Subscription Activated! 🎉',
      greeting: `Hello ${name}, great news! Your subscription has been successfully processed.`,
      plan: 'Current Plan',
      access: `You now have full access to all the features included in the <strong>${planName}</strong> plan.`,
      button: 'Go to Dashboard',
    },
    es: {
      title: '¡Suscripción Activada! 🎉',
      greeting: `Hola ${name}, ¡buenas noticias! Tu suscripción ha sido procesada exitosamente.`,
      plan: 'Plan Actual',
      access: `Ahora tienes acceso completo a todas las funciones incluidas en el plan <strong>${planName}</strong>.`,
      button: 'Ir al Panel',
    },
  }[lang];

  const content = `
    <h1>${t.title}</h1>
    <p style="text-align: center;">${t.greeting}</p>

    <div class="box-container">
      <div class="label">${t.plan}</div>
      <div class="value" style="color: #059669;">${planName}</div>
    </div>

    <p style="text-align: center;">${t.access}</p>

    <center><a href="${process.env.FRONTEND_URL}/dashboard" class="button">${t.button}</a></center>
  `;
  return getBaseLayout(content, lang);
};

export const clinicalRecordTemplate = (name: string, date: string, type: string, lang: EmailLang = 'en') => {
  const t = {
    en: {
      title: 'New Clinical Record Added 📋',
      greeting: `Hello ${name}, a new clinical record has been added to your file.`,
      recordType: 'Record Type',
      date: 'Date',
      note: 'You can view the details of this record by logging into your patient portal.',
    },
    es: {
      title: 'Nuevo Registro Clínico Añadido 📋',
      greeting: `Hola ${name}, se ha añadido un nuevo registro clínico a tu expediente.`,
      recordType: 'Tipo de Registro',
      date: 'Fecha',
      note: 'Puedes ver los detalles de este registro iniciando sesión en tu portal de paciente.',
    },
  }[lang];

  const content = `
    <h1>${t.title}</h1>
    <p style="text-align: center;">${t.greeting}</p>

    <div class="box-container">
      <div class="label">${t.recordType}</div>
      <div class="value">${type}</div>
      <div class="label" style="margin-top: 16px;">${t.date}</div>
      <div class="value" style="font-size: 18px; color: #4b5563;">${date}</div>
    </div>

    <p style="text-align: center;">${t.note}</p>

  `;
  return getBaseLayout(content, lang);
};

export const dentalRecordTemplate = (name: string, date: string, treatment: string, lang: EmailLang = 'en') => {
  const t = {
    en: {
      title: 'New Dental Record Added 🦷',
      greeting: `Hello ${name}, a new dental record has been added to your file.`,
      treatment: 'Treatment',
      date: 'Date',
      note: 'You can view the details of this record by logging into your patient portal.',
    },
    es: {
      title: 'Nuevo Registro Dental Añadido 🦷',
      greeting: `Hola ${name}, se ha añadido un nuevo registro dental a tu expediente.`,
      treatment: 'Tratamiento',
      date: 'Fecha',
      note: 'Puedes ver los detalles de este registro iniciando sesión en tu portal de paciente.',
    },
  }[lang];

  const content = `
    <h1>${t.title}</h1>
    <p style="text-align: center;">${t.greeting}</p>

    <div class="box-container">
      <div class="label">${t.treatment}</div>
      <div class="value">${treatment}</div>
      <div class="label" style="margin-top: 16px;">${t.date}</div>
      <div class="value" style="font-size: 18px; color: #4b5563;">${date}</div>
    </div>

    <p style="text-align: center;">${t.note}</p>

  `;
  return getBaseLayout(content, lang);
};

export const newDoctorCredentialsTemplate = (name: string, email: string, password: string, ownerName: string, lang: EmailLang = 'en') => {
  const safeName = escapeHtml(name);
  const safeOwnerName = escapeHtml(ownerName);
  const safeEmail = escapeHtml(email);
  const safePassword = escapeHtml(password);

  const t = {
    en: {
      title: `Welcome to the Team, ${safeName}! 👋`,
      addedBy: `You have been added to the team by <strong>${safeOwnerName}</strong>.`,
      credentials: 'Here are your login credentials to access the Medklinix system:',
      emailLabel: 'Email',
      passwordLabel: 'Temporary Password',
      note: 'Please log in and update your password immediately.',
      button: 'Log In Now',
    },
    es: {
      title: `¡Bienvenido al Equipo, ${safeName}! 👋`,
      addedBy: `Has sido añadido al equipo por <strong>${safeOwnerName}</strong>.`,
      credentials: 'Aquí están tus credenciales de acceso al sistema de Medklinix:',
      emailLabel: 'Correo Electrónico',
      passwordLabel: 'Contraseña Temporal',
      note: 'Por favor inicia sesión y actualiza tu contraseña de inmediato.',
      button: 'Iniciar Sesión',
    },
  }[lang];

  const content = `
    <h1>${t.title}</h1>
    <p style="text-align: center;">${t.addedBy}</p>

    <p style="text-align: center;">${t.credentials}</p>

    <div class="box-container">
      <div class="label">${t.emailLabel}</div>
      <div class="value" style="font-size: 18px; color: #4b5563; margin-bottom: 24px; white-space: nowrap; letter-spacing: 0;">${safeEmail}</div>
      <div class="label">${t.passwordLabel}</div>
      <div class="value" style="white-space: nowrap; letter-spacing: 0.08em;">${safePassword}</div>
    </div>

    <p style="text-align: center;">${t.note}</p>

    <center><a href="${process.env.FRONTEND_URL}/login" class="button">${t.button}</a></center>
  `;
  return getBaseLayout(content, lang);
};
