'use client';

import { ArrowRight } from 'lucide-react';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import { useEffect, useState } from 'react';
import { AnimatePresence, motion, useReducedMotion } from 'framer-motion';

import { ResendButton } from '@/components/auth/resend-button';
import { AuthCard, AuthLink } from '@/components/forms/auth-card';
import { FormAlert } from '@/components/forms/form-field';
import { ErrorIllustration, MailSentIllustration } from '@/components/illustrations';
import { SuccessBurst } from '@/components/illustrations/success-burst';
import { Button, buttonVariants } from '@/components/ui/button';
import { api, ApiError } from '@/lib/api-client';
import { useAuth } from '@/lib/auth';
import { cn } from '@/lib/utils';

type VerifyState = 'verifying' | 'success' | 'invalid';

export function VerifyEmailPanel() {
  const params = useSearchParams();
  const token = params.get('token');
  const { status } = useAuth();
  const reduce = useReducedMotion();
  const [state, setState] = useState<VerifyState>(token === null ? 'invalid' : 'verifying');
  const [message, setMessage] = useState<string | null>(null);
  const [sending, setSending] = useState(false);

  useEffect(() => {
    if (token === null || token.length === 0) return;
    let active = true;
    void api('/auth/verify-email', { json: { token } })
      .then(() => {
        if (active) setState('success');
      })
      .catch(() => {
        if (active) setState('invalid');
      });
    return () => {
      active = false;
    };
  }, [token]);

  const resend = async () => {
    setMessage(null);
    setSending(true);
    try {
      await api('/auth/resend-verification', { method: 'POST' });
      setMessage('Verification email sent.');
    } catch (error) {
      setMessage(error instanceof ApiError ? error.message : 'The email could not be sent.');
    } finally {
      setSending(false);
    }
  };

  return (
    <AnimatePresence mode="wait" initial={false}>
      <motion.div
        key={state}
        initial={reduce ? { opacity: 0 } : { opacity: 0, y: 8, scale: 0.98 }}
        animate={{ opacity: 1, y: 0, scale: 1 }}
        exit={reduce ? { opacity: 0 } : { opacity: 0, y: -8, scale: 0.98 }}
        transition={{ duration: 0.22, ease: [0.2, 0.8, 0.2, 1] }}
      >
        {state === 'verifying' ? (
          <AuthCard
            align="center"
            title="Verifying your email"
            description="This only takes a moment."
            top={
              <div className="relative grid h-24 w-24 place-items-center" role="status" aria-label="Verifying your email">
                <span className="absolute inset-0 rounded-full border-4 border-primary-soft" aria-hidden="true" />
                <span className="absolute inset-0 animate-spin rounded-full border-4 border-transparent border-t-primary" aria-hidden="true" />
              </div>
            }
          />
        ) : null}
        {state === 'success' ? (
          <AuthCard align="center" title="Email verified" description="You are all set. Your workspace is fully unlocked." top={<SuccessBurst size={120} />}>
            <Link href="/dashboard" className={cn(buttonVariants({ size: 'lg' }), 'group w-full')}>
              Go to dashboard
              <ArrowRight className="h-4 w-4 transition-transform duration-180 group-hover:translate-x-[3px]" aria-hidden="true" />
            </Link>
          </AuthCard>
        ) : null}
        {state === 'invalid' ? (
          <AuthCard
            align="center"
            title="This link has expired"
            description="Verification links work once and expire after a while. Request a fresh one below."
            top={<ErrorIllustration size={120} />}
          >
            <div className="grid gap-4 text-left">
              {message === null ? null : (
                <FormAlert tone={message === 'Verification email sent.' ? 'success' : 'error'}>{message}</FormAlert>
              )}
              {status === 'authenticated' ? (
                <Button type="button" size="lg" className="w-full" loading={sending} onClick={() => void resend()}>
                  Resend verification
                </Button>
              ) : (
                <Link href="/login" className={cn(buttonVariants({ size: 'lg' }), 'w-full')}>
                  Sign in
                </Link>
              )}
            </div>
          </AuthCard>
        ) : null}
      </motion.div>
    </AnimatePresence>
  );
}

export function VerifyEmailPending() {
  const { user } = useAuth();
  const [cooldown, setCooldown] = useState(0);
  const [message, setMessage] = useState<string | null>(null);
  const [sending, setSending] = useState(false);

  const resend = async () => {
    setMessage(null);
    setSending(true);
    try {
      await api('/auth/resend-verification', { method: 'POST' });
      setMessage('Verification email sent.');
      setCooldown(60);
      const timer = window.setInterval(() => {
        setCooldown((current) => {
          if (current <= 1) {
            window.clearInterval(timer);
            return 0;
          }
          return current - 1;
        });
      }, 1000);
    } catch (error) {
      setMessage(error instanceof ApiError && error.code === 'TOO_MANY_ATTEMPTS' ? 'You have reached the resend limit. Try again later.' : 'The email could not be sent.');
    } finally {
      setSending(false);
    }
  };

  return (
    <AuthCard
      align="center"
      title="Check your inbox"
      top={<MailSentIllustration size={160} className="animate-float [animation-duration:5s]" />}
      description={
        <p>
          Verification email sent to
          {user?.email === undefined ? null : (
            <>
              <br />
              <span className="mt-2 inline-flex max-w-full truncate rounded-pill bg-surface-muted px-3 py-1 text-small font-semibold text-foreground">{user.email}</span>
            </>
          )}
        </p>
      }
      footer={<p className="text-caption text-subtle-foreground">Some actions stay locked until you verify.</p>}
    >
      <div className="grid gap-4 text-left">
        {message === null ? null : <FormAlert tone={message === 'Verification email sent.' ? 'success' : 'error'}>{message}</FormAlert>}
        <ResendButton cooldown={cooldown} loading={sending} onClick={() => void resend()} />
        <p className="text-center text-small">
          <AuthLink href="/dashboard">Continue to dashboard</AuthLink>
        </p>
      </div>
    </AuthCard>
  );
}
