import { useState, type FormEvent, type ReactNode } from 'react';
import { supabase } from '../lib/supabase';
import { useInstalarPWA } from '../lib/useInstalarPWA';

const INPUT =
  'w-full rounded-xl border border-white/10 bg-superficie-2 py-3 pl-10 pr-3 text-sm text-white placeholder:text-white/40 outline-none transition focus:border-dorado focus:ring-2 focus:ring-dorado/25';

export default function Login() {
  const [email, setEmail] = useState('');
  const [pass, setPass] = useState('');
  const [verClave, setVerClave] = useState(false);
  const [err, setErr] = useState<string | null>(null);
  const [cargando, setCargando] = useState(false);
  const { instalable, instalar, instalado, esIOS } = useInstalarPWA();

  async function entrar(e: FormEvent) {
    e.preventDefault();
    setErr(null);
    setCargando(true);
    const { error } = await supabase.auth.signInWithPassword({ email, password: pass });
    setCargando(false);
    if (error) setErr('Correo o contrasena incorrectos.');
  }

  return (
    <div className="min-h-full bg-noche text-white lg:grid lg:grid-cols-2">
      {/* Panel de marca Gustito Xpress */}
      <div className="relative isolate overflow-hidden bg-gradient-to-br from-superficie to-noche">
        <div className="pointer-events-none absolute inset-0 overflow-hidden">
          <div className="absolute -top-24 right-0 h-72 w-72 rounded-full bg-dorado/15 blur-3xl" />
          <div className="absolute bottom-0 left-0 h-64 w-64 rounded-full bg-dorado/10 blur-3xl" />
        </div>
        <div className="relative px-7 py-9 lg:flex lg:min-h-full lg:flex-col lg:justify-center lg:px-14">
          <div className="max-w-md">
            <div className="flex items-center gap-2.5">
              <span className="grid h-11 w-11 place-items-center rounded-2xl bg-dorado text-noche shadow-glow">
                <Glifo className="h-6 w-6" />
              </span>
              <div className="leading-none">
                <span className="block text-2xl font-extrabold tracking-tight">
                  Gustito <span className="text-dorado">Xpress</span>
                </span>
                <span className="text-xs font-semibold uppercase tracking-[0.2em] text-niebla">Repartidor</span>
              </div>
            </div>
            <h1 className="mt-6 text-2xl font-extrabold leading-tight lg:text-4xl">Tus entregas, en una sola app.</h1>
            <p className="mt-3 text-sm text-niebla lg:text-base">
              Toma las entregas de tu restaurante, sigue el mapa dentro de la app y comparte tu ubicacion en vivo.
            </p>
            <ul className="mt-7 hidden space-y-3.5 text-sm lg:block">
              <Bullet>Ve las entregas listas al instante</Bullet>
              <Bullet>Mapa del destino sin salir de la app</Bullet>
              <Bullet>Comparte tu ubicacion con el cliente</Bullet>
              <Bullet>Tu historial de entregas por jornada</Bullet>
            </ul>
          </div>
        </div>
      </div>

      {/* Formulario */}
      <div className="px-6 py-8 lg:flex lg:items-center lg:justify-center lg:p-12">
        <form
          onSubmit={entrar}
          className="mx-auto w-full max-w-sm rounded-3xl bg-superficie p-6 shadow-2xl ring-1 ring-white/10 lg:p-8"
        >
          <h2 className="text-2xl font-extrabold text-white">Entra a tu turno</h2>
          <p className="mb-6 mt-1 text-sm text-niebla">Usa el correo y la clave que te dio tu restaurante.</p>

          <Campo label="Correo" icon={<IconMail />}>
            <input
              className={INPUT}
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="tucorreo@ejemplo.com"
              required
            />
          </Campo>
          <Campo label="Contrasena" icon={<IconLock />}>
            <input
              className={`${INPUT} pr-11`}
              type={verClave ? 'text' : 'password'}
              value={pass}
              onChange={(e) => setPass(e.target.value)}
              placeholder="Tu clave"
              required
            />
            <button
              type="button"
              onClick={() => setVerClave((v) => !v)}
              className="absolute right-2 top-1/2 grid h-8 w-8 -translate-y-1/2 place-items-center rounded-lg text-niebla hover:text-white"
              aria-label={verClave ? 'Ocultar clave' : 'Mostrar clave'}
              title={verClave ? 'Ocultar clave' : 'Mostrar clave'}
            >
              {verClave ? <IconEyeOff /> : <IconEye />}
            </button>
          </Campo>

          {err && (
            <p className="mb-3 rounded-lg bg-red-500/15 px-3 py-2 text-sm text-red-300 ring-1 ring-red-500/25">{err}</p>
          )}

          <button
            disabled={cargando}
            className="w-full rounded-2xl bg-dorado py-3 text-base font-bold text-noche shadow-glow transition active:scale-[0.99] disabled:opacity-60"
          >
            {cargando ? 'Un momento...' : 'Entrar a repartir'}
          </button>

          {!instalado && instalable && (
            <button
              type="button"
              onClick={instalar}
              className="mt-3 flex w-full items-center justify-center gap-2 rounded-2xl border border-dorado/40 py-2.5 text-sm font-semibold text-dorado transition active:scale-[0.99]"
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M12 3v12m0 0 4-4m-4 4-4-4M5 21h14" />
              </svg>
              Instalar la app
            </button>
          )}
          {!instalado && esIOS && (
            <p className="mt-3 text-center text-xs text-niebla">
              Para instalar: toca <span className="text-white">Compartir</span> y luego{' '}
              <span className="text-white">Agregar a inicio</span>.
            </p>
          )}

          <p className="mt-5 text-center text-xs text-niebla">
            Gustito <span className="font-semibold text-dorado">Xpress</span>, hecho en Venezuela
          </p>
        </form>
      </div>
    </div>
  );
}

function Glifo({ className = 'h-7 w-7' }: { className?: string }) {
  return (
    <svg viewBox="0 0 512 512" className={className} aria-hidden>
      <circle cx="256" cy="256" r="150" fill="none" stroke="currentColor" strokeWidth="34" />
      <g fill="currentColor" transform="rotate(-32 256 256)">
        <rect x="245" y="214" width="22" height="150" rx="11" />
        <rect x="236" y="152" width="8" height="66" rx="4" />
        <rect x="252" y="152" width="8" height="66" rx="4" />
        <rect x="268" y="152" width="8" height="66" rx="4" />
        <rect x="236" y="208" width="40" height="14" rx="7" />
      </g>
      <g fill="currentColor" transform="rotate(32 256 256)">
        <rect x="245" y="202" width="22" height="162" rx="11" />
        <ellipse cx="256" cy="174" rx="27" ry="38" />
      </g>
    </svg>
  );
}

function Bullet({ children }: { children: ReactNode }) {
  return (
    <li className="flex items-start gap-2.5">
      <span className="mt-0.5 grid h-5 w-5 shrink-0 place-items-center rounded-full bg-dorado/20 text-[11px] font-bold text-dorado">
        ✓
      </span>
      <span className="text-white/90">{children}</span>
    </li>
  );
}

function Campo({ label, icon, children }: { label: string; icon: ReactNode; children: ReactNode }) {
  return (
    <label className="mb-3.5 block">
      <span className="text-xs font-semibold text-niebla">{label}</span>
      <div className="relative mt-1">
        <span className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-niebla">{icon}</span>
        {children}
      </div>
    </label>
  );
}

function IconMail() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="5" width="18" height="14" rx="2" />
      <path d="m3 7 9 6 9-6" />
    </svg>
  );
}
function IconLock() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <rect x="4" y="10" width="16" height="11" rx="2" />
      <path d="M8 10V7a4 4 0 0 1 8 0v3" />
    </svg>
  );
}
function IconEye() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7Z" />
      <circle cx="12" cy="12" r="3" />
    </svg>
  );
}
function IconEyeOff() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M9.9 5.1A9.8 9.8 0 0 1 12 5c6.5 0 10 7 10 7a17 17 0 0 1-3.2 4.1M6.6 6.6A17 17 0 0 0 2 12s3.5 7 10 7a9.8 9.8 0 0 0 4.2-.9" />
      <path d="M9.9 9.9a3 3 0 0 0 4.2 4.2" />
      <path d="M2 2l20 20" />
    </svg>
  );
}
