import { Button } from '@/components/ui/button';
import { getPendingInvite } from '@/lib/invitations';
import { Route } from '@/routes/onboard/verify-email';
import { Link } from '@tanstack/react-router';
import { useEffect, useState } from 'react';

export function VerifyEmailPage() {
  const search = Route.useSearch();
  const email = search.email || sessionStorage.getItem('pending-signup-email') || '';
  const pendingInvite = getPendingInvite();
  const [resendCooldown, setResendCooldown] = useState(0);

  useEffect(() => {
    if (resendCooldown > 0) {
      const timer = setTimeout(() => setResendCooldown((c) => c - 1), 1000);
      return () => clearTimeout(timer);
    }
  }, [resendCooldown]);

  const handleResend = async () => {
    if (!email || resendCooldown > 0) return;

    setResendCooldown(60);
  };

  return (
    <main className="flex min-h-screen w-full items-center justify-center px-6">
      <section className="w-full max-w-sm rounded-xl border bg-card p-6 text-card-foreground shadow-sm">
        <h1 className="mb-2 text-2xl font-semibold">Verificá tu email</h1>
        <p className="mb-4 text-sm text-muted-foreground">
          Te enviamos un email de verificación a <strong>{email}</strong>. Hacé click en el link
          para confirmar tu cuenta.
        </p>

        <div className="space-y-3">
          <Button
            type="button"
            className="w-full"
            onClick={handleResend}
            disabled={resendCooldown > 0}
          >
            {resendCooldown > 0 ? `Reenviar en ${resendCooldown}s` : 'Reenviar email'}
          </Button>

          <p className="text-center text-sm text-muted-foreground">
            ¿Ya verificaste tu email?{' '}
            {pendingInvite.token ? (
              <Link
                to="/invite"
                search={{
                  email: pendingInvite.email ?? email,
                  inviteToken: pendingInvite.token,
                }}
                className="text-primary hover:underline"
              >
                Continuar con la invitación
              </Link>
            ) : (
              <Link to="/onboard/create-complex" className="text-primary hover:underline">
                Continuar
              </Link>
            )}
          </p>
        </div>
      </section>
    </main>
  );
}
