'use client';

import { useState } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod/v4';
import { Mail, Loader2, ChevronLeft, CheckCircle2 } from 'lucide-react';
import api from '@/lib/api';

const emailSchema = z.object({
  email: z.email('Enter a valid email address'),
});

type EmailInput = z.infer<typeof emailSchema>;
type Mode = 'enter-email' | 'success';

export default function ForgotPasswordForm() {
  const [mode, setMode] = useState<Mode>('enter-email');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [sentEmail, setSentEmail] = useState('');

  const form = useForm<EmailInput>({ resolver: zodResolver(emailSchema) });

  const apiError = (err: unknown) =>
    ((err as { response?: { data?: { message?: string } } })?.response?.data?.message) ?? 'Something went wrong.';

  const onSubmit = async (data: EmailInput) => {
    setLoading(true); setError('');
    try {
      await api.post('/auth/forgot-password', { email: data.email });
      setSentEmail(data.email);
      setMode('success');
    } catch (err) { setError(apiError(err)); }
    finally { setLoading(false); }
  };

  return (
    <div className="w-full max-w-md">
      <div className="relative mt-16">
        <Link href="/" className="absolute left-1/2 -translate-x-1/2 -top-16 z-10">
          <Image src="/logo-circle.png" alt="Roopaya" width={130} height={130} className="rounded-full shadow-lg ring-4 ring-background w-[100px] h-[100px] sm:w-[130px] sm:h-[130px]" />
        </Link>
        <div className="bg-card border border-border rounded-2xl pt-[65px] sm:pt-20 pb-6 sm:pb-8 px-4 sm:px-8 shadow-sm">
          <div className="text-center mb-4">
            <h2 className="font-bold text-[22px] tracking-tight leading-none">Roopaya</h2>
            <p className="text-[9px] font-semibold tracking-[0.25em] uppercase text-primary mt-1">Beauty · Bridal · Couture</p>
          </div>
          <div className="w-10 h-px bg-border mx-auto mb-4" />

          {mode === 'enter-email' && (
            <>
              <Link href="/login"
                className="flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground mb-6 transition-colors">
                <ChevronLeft className="w-4 h-4" /> Back to login
              </Link>
              <h1 className="text-xl font-bold mb-1">Forgot password?</h1>
              <p className="text-sm text-muted-foreground mb-6">Enter your email and we&apos;ll send you a reset link</p>
              <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                <div>
                  <label className="block text-sm font-medium mb-1.5">Email Address</label>
                  <div className="relative">
                    <Mail className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                    <input {...form.register('email')} type="email" placeholder="you@example.com"
                      className="w-full pl-10 pr-4 py-3 border border-input rounded-xl text-sm bg-background focus:outline-none focus:ring-2 focus:ring-ring" />
                  </div>
                  {form.formState.errors.email && <p className="text-destructive text-xs mt-1">{form.formState.errors.email.message}</p>}
                </div>
                {error && <p className="text-destructive text-sm bg-destructive/10 px-3 py-2 rounded-lg">{error}</p>}
                <button type="submit" disabled={loading}
                  className="w-full flex items-center justify-center gap-2 py-3 bg-primary text-primary-foreground rounded-xl font-semibold hover:opacity-90 disabled:opacity-60 transition-opacity">
                  {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <span>Send Reset Link</span>}
                </button>
              </form>
            </>
          )}

          {mode === 'success' && (
            <div className="text-center py-4">
              <div className="w-14 h-14 rounded-full bg-green-100 dark:bg-green-900/30 flex items-center justify-center mx-auto mb-4">
                <CheckCircle2 className="w-7 h-7 text-green-600 dark:text-green-400" />
              </div>
              <h1 className="text-xl font-bold mb-2">Check your email</h1>
              <p className="text-sm text-muted-foreground mb-1">
                We sent a password reset link to
              </p>
              <p className="text-sm font-medium mb-6">{sentEmail}</p>
              <p className="text-xs text-muted-foreground mb-6">
                Didn&apos;t receive the email? Check your spam folder or{' '}
                <button onClick={() => { setMode('enter-email'); form.reset(); setError(''); }}
                  className="text-primary hover:underline font-medium">try again</button>
              </p>
              <Link href="/login"
                className="inline-flex items-center justify-center gap-2 w-full py-3 bg-primary text-primary-foreground rounded-xl font-semibold hover:opacity-90 transition-opacity">
                Back to Login
              </Link>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
