'use client';

import { ArrowLeft, Mail } from 'lucide-react';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';

import { CountdownRing } from '@/components/auth/resend-button';
import { AuthCard, AuthLink } from '@/components/forms/auth-card';
import { describedBy, FormAlert, FormField } from '@/components/forms/form-field';
import { LockIllustration, MailSentIllustration } from '@/components/illustrations';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { api, ApiError } from '@/lib/api-client';
import { forgotPasswordBodySchema, type ForgotPasswordBody } from '@/shared/schemas/auth';

const backLink = (
  <span className="inline-flex items-center gap-1.5">
    <ArrowLeft className="h-3.5 w-3.5" aria-hidden="true" />
    <AuthLink href="/login">Back to sign in</AuthLink>
  </span>
);

export function ForgotPasswordForm() {
  const [sent, setSent] = useState(false);
  const [cooldown, setCooldown] = useState(0);
  const [alert, setAlert] = useState<string | null>(null);
  const form = useForm<ForgotPasswordBody>({ resolver: zodResolver(forgotPasswordBodySchema), mode: 'onBlur' });
  const emailError = form.formState.errors.email?.message;

  const onSubmit = form.handleSubmit(async (values) => {
    setAlert(null);
    try {
      await api('/auth/forgot-password', { json: values });
      setSent(true);
      setCooldown(60);
      const timer = window.setInterval(() => {
        setCooldown((current) => {
          if (current <= 1) {
            window.clearInterval(timer);
            return 0;
          }
          return current - 1;
        });
      }, 1000);
    } catch (error) {
      setAlert(error instanceof ApiError ? error.message : 'Something went wrong. Try again.');
    }
  });

  if (sent) {
    return (
      <AuthCard
        align="center"
        title="Check your email"
        description="If an account exists, we sent a reset link. It may take a minute to arrive."
        top={<MailSentIllustration size={140} className="animate-float [animation-duration:5s]" />}
        footer={backLink}
      >
        <form className="grid gap-3" onSubmit={onSubmit} noValidate>
          {alert === null ? null : <FormAlert className="text-left">{alert}</FormAlert>}
          <p className="text-small text-muted-foreground" aria-live="polite">
            Did not get it?{' '}
            {cooldown > 0 ? (
              <span className="inline-flex items-center gap-1.5 align-middle text-subtle-foreground">
                <CountdownRing remaining={cooldown} className="h-4 w-4" />
                Resend in <span className="tabular-nums">{cooldown}s</span>
              </span>
            ) : (
              <button type="submit" className="rounded-sm font-semibold text-primary underline-offset-4 hover:underline disabled:opacity-60" disabled={form.formState.isSubmitting}>
                {form.formState.isSubmitting ? 'Sending' : 'Resend link'}
              </button>
            )}
          </p>
        </form>
      </AuthCard>
    );
  }

  return (
    <AuthCard
      title="Forgot your password?"
      description="We will email you a reset link."
      top={
        <span className="grid h-16 w-16 place-items-center rounded-xl bg-primary-soft">
          <LockIllustration size={56} />
        </span>
      }
      footer={backLink}
    >
      <form className="grid gap-5" onSubmit={onSubmit} noValidate>
        {alert === null ? null : <FormAlert>{alert}</FormAlert>}
        <FormField id="email" label="Email" error={emailError}>
          <Input id="email" type="email" autoComplete="email" placeholder="you@company.com" leading={<Mail />} aria-invalid={emailError !== undefined} aria-describedby={describedBy('email', undefined, emailError)} {...form.register('email')} />
        </FormField>
        <Button type="submit" size="lg" className="w-full" loading={form.formState.isSubmitting}>
          {form.formState.isSubmitting ? 'Sending link' : 'Send reset link'}
        </Button>
      </form>
    </AuthCard>
  );
}
