import {
  Body,
  Button,
  Container,
  Head,
  Heading,
  Hr,
  Html,
  Img,
  Link,
  Preview,
  Section,
  Tailwind,
  Text,
} from '@react-email/components';

/**
 * Bienvenida al crear un laboratorio en Labento (registro público trial).
 *
 * Props de producción (PHP rellena el HTML espejo en app/Views/emails/).
 * Preview: npm run email → http://localhost:3000
 *
 * Assets:
 * - Dev (React Email): /static/labento_logo.png
 * - Prod (PHP/Brevo): base_url('labento_logo.png') vía prop assetBaseUrl
 */
export interface BienvenidaEmailProps {
  /** Nombre del dueño / admin */
  nombreDueno: string;
  /** Nombre comercial del laboratorio */
  nombreLab: string;
  /** Username de acceso */
  username: string;
  /** URL absoluta de login */
  loginUrl: string;
  /**
   * Prefijo absoluto de assets en producción (sin slash final).
   * En preview local de React Email dejar vacío.
   * Ej. https://labsaas.test  →  logo en {assetBaseUrl}/labento_logo.png
   */
  assetBaseUrl?: string;
  /** Año del footer */
  year?: number;
  /** URL del aviso de privacidad */
  privacidadUrl?: string;
  /** URL de términos */
  terminosUrl?: string;
}

const colors = {
  primary: '#5d87ff',
  primaryEmphasis: '#4a6cd9',
  heading: '#2a3547',
  body: '#5a6a85',
  bg: '#eff4fa',
  surface: '#ffffff',
  border: '#e5e5e5',
  success: '#13deb9',
};

export default function BienvenidaEmail({
  nombreDueno,
  nombreLab,
  username,
  loginUrl,
  assetBaseUrl = '',
  year = new Date().getFullYear(),
  privacidadUrl = '',
  terminosUrl = '',
}: BienvenidaEmailProps) {
  const base = (assetBaseUrl || '').replace(/\/$/, '');
  // Dev: React Email sirve /static/* · Prod: archivos en public/ del sitio
  const logoSrc = base
    ? `${base}/labento_logo.png`
    : '/static/labento_logo.png';

  const preview = `${nombreLab} ya está listo en Labento · Usuario ${username}`;

  return (
    <Html lang="es-MX">
      <Tailwind
        config={{
          theme: {
            extend: {
              colors: {
                brand: colors.primary,
                'brand-dark': colors.primaryEmphasis,
                heading: colors.heading,
                muted: colors.body,
                canvas: colors.bg,
                surface: colors.surface,
                line: colors.border,
                ok: colors.success,
              },
            },
          },
        }}
      >
        <Head />
        <Preview>{preview}</Preview>
        <Body className="bg-canvas font-sans py-10 m-0">
          <Container className="max-w-[560px] mx-auto px-4">
            {/* Card */}
            <Section className="bg-surface rounded-[14px] border border-solid border-line px-8 py-8">
              {/* Brand */}
              <Section className="text-center mb-6">
                <Img
                  src={logoSrc}
                  alt="Labento"
                  width="56"
                  height="56"
                  className="mx-auto rounded-[12px]"
                />
                <Text className="text-heading text-[13px] font-semibold tracking-wide m-0 mt-3">
                  Labento
                </Text>
                <Text className="text-muted text-[12px] m-0 mt-1">
                  Software para laboratorios clínicos
                </Text>
              </Section>

              <Heading className="text-heading text-[22px] font-bold leading-snug m-0 mb-3 text-center">
                Tu laboratorio ya está listo
              </Heading>

              <Text className="text-muted text-[15px] leading-relaxed m-0 mb-4 text-center">
                Hola{nombreDueno ? ` ${nombreDueno}` : ''}, creamos tu espacio
                en Labento. Ya puedes operar caja, laboratorio y entrega de
                resultados en un solo sistema.
              </Text>

              {/* Fact box */}
              <Section className="bg-canvas rounded-[10px] border border-solid border-line px-5 py-4 mb-6">
                <Text className="text-muted text-[12px] uppercase tracking-wide m-0 mb-1">
                  Laboratorio
                </Text>
                <Text className="text-heading text-[16px] font-semibold m-0 mb-3">
                  {nombreLab}
                </Text>
                <Text className="text-muted text-[12px] uppercase tracking-wide m-0 mb-1">
                  Usuario de acceso
                </Text>
                <Text className="text-heading text-[16px] font-semibold m-0 font-mono">
                  {username}
                </Text>
                <Text className="text-muted text-[13px] m-0 mt-3 leading-relaxed">
                  Acceso <strong className="text-heading">$0 en fase de desarrollo</strong>
                  . Sin tarjeta. Los precios del software se definirán más
                  adelante y se avisarán con claridad.
                </Text>
              </Section>

              <Section className="text-center mb-6">
                <Button
                  href={loginUrl}
                  className="bg-brand text-white text-[15px] font-semibold no-underline px-7 py-3 rounded-[999px] box-border inline-block"
                >
                  Entrar a Labento
                </Button>
              </Section>

              <Text className="text-muted text-[13px] leading-relaxed m-0 mb-2 text-center">
                Si el botón no funciona, copia y pega este enlace en tu
                navegador:
              </Text>
              <Text className="text-brand text-[13px] m-0 mb-6 text-center break-all">
                <Link href={loginUrl} className="text-brand no-underline">
                  {loginUrl}
                </Link>
              </Text>

              <Hr className="border-none border-t border-solid border-line my-6" />

              <Text className="text-muted text-[13px] leading-relaxed m-0 mb-2">
                <strong className="text-heading">Próximos pasos sugeridos</strong>
              </Text>
              <Text className="text-muted text-[13px] leading-relaxed m-0 mb-1">
                1. Entra con tu usuario y revisa el panel de administración.
              </Text>
              <Text className="text-muted text-[13px] leading-relaxed m-0 mb-1">
                2. Ajusta catálogo, precios y personal de tu sucursal.
              </Text>
              <Text className="text-muted text-[13px] leading-relaxed m-0 mb-4">
                3. Prueba una venta y el flujo de resultados cuando estés listo.
              </Text>

              <Text className="text-muted text-[12px] leading-relaxed m-0">
                Si no solicitaste esta cuenta, puedes ignorar este mensaje.
                ¿Dudas? Responde a este correo o escribe a soporte.
              </Text>
            </Section>

            {/* Footer */}
            <Section className="text-center px-2 pt-6">
              <Text className="text-muted text-[12px] m-0 mb-1">
                © {year} Labento · Software para laboratorios clínicos
              </Text>
              <Text className="text-muted text-[12px] m-0">
                {privacidadUrl ? (
                  <Link href={privacidadUrl} className="text-muted no-underline">
                    Aviso de Privacidad
                  </Link>
                ) : (
                  'Aviso de Privacidad'
                )}
                {' · '}
                {terminosUrl ? (
                  <Link href={terminosUrl} className="text-muted no-underline">
                    Términos
                  </Link>
                ) : (
                  'Términos'
                )}
              </Text>
            </Section>
          </Container>
        </Body>
      </Tailwind>
    </Html>
  );
}

BienvenidaEmail.PreviewProps = {
  nombreDueno: 'Ana Martínez',
  nombreLab: 'Laboratorio Norte',
  username: 'ana.admin',
  loginUrl: 'https://labsaas.test/login',
  assetBaseUrl: '',
  year: new Date().getFullYear(),
  privacidadUrl: 'https://labsaas.test/privacidad',
  terminosUrl: 'https://labsaas.test/terminos',
} satisfies BienvenidaEmailProps;

export { BienvenidaEmail };
