'use client';
import { useState } from 'react';
import { api } from '@/lib/api';
import { AuthShell, AuthBack } from '../shell';
import { Spinner } from '@/components/ui';
import { FloatInput } from '@/components/float';
import { useDialog } from '@/components/dialog';
import { v } from '@/lib/validation';

export default function ForgotPage() {
  const { notify } = useDialog();
  const [email, setEmail] = useState('');
  const [busy, setBusy] = useState(false);
  const [fieldErr, setFieldErr] = useState('');
  return (
    <AuthShell title="Forgot password" subtitle="We'll email you a reset link">
      <form className="space-y-4" noValidate onSubmit={async (e) => {
        e.preventDefault();
        const emailErr = v.email(email);
        setFieldErr(emailErr ?? '');
        if (emailErr) return;
        setBusy(true);
        try {
          await api.post('/api/v1/auth/forgot-password', { email });
          notify('If the email exists, a reset link has been sent.', { tone: 'success' });
        } catch (ex: any) { notify(ex.message, { tone: 'error' }); }
        finally { setBusy(false); }
      }}>
        <FloatInput label="Email" id="fp-email" type="email" autoComplete="email" required error={fieldErr} value={email} onChange={(e) => setEmail(e.target.value)} />
        <button className="btn-primary btn-tall w-full" disabled={busy}>{busy ? <Spinner label="Sending…" /> : 'Send reset link'}</button>
        <p className="text-center"><AuthBack /></p>
      </form>
    </AuthShell>
  );
}
