'use client';

import { useFormState, useFormStatus } from 'react-dom';
import { requestPasswordReset, type ForgotPasswordFormState } from '@/app/forgot-password/actions';

const initialState: ForgotPasswordFormState = undefined;

function SubmitButton() {
  const { pending } = useFormStatus();
  return (
    <button type="submit" disabled={pending} className="btn-primary w-full disabled:opacity-60">
      {pending ? 'Sending…' : 'Send Reset Link'}
    </button>
  );
}

export function ForgotPasswordForm() {
  const [state, formAction] = useFormState(requestPasswordReset, initialState);
  const errors = state?.errors ?? {};

  if (state?.success) {
    return (
      <div className="mt-6 rounded-md border border-green-200 bg-green-50 px-4 py-3 text-sm text-green-700">
        {state.message}
      </div>
    );
  }

  return (
    <form action={formAction} className="mt-6 space-y-4">
      {Object.keys(errors).length > 0 && (
        <div className="rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
          <ul className="list-inside list-disc">
            {Object.values(errors).flat().map((error) => (
              <li key={error}>{error}</li>
            ))}
          </ul>
        </div>
      )}
      <div>
        <label className="block text-sm font-semibold text-navy-800">Email Address</label>
        <input
          type="email"
          name="email"
          required
          className="mt-1.5 w-full rounded-md border-navy-100 text-sm focus:border-gold-500 focus:ring-gold-500"
        />
      </div>
      <SubmitButton />
    </form>
  );
}
