'use client';

import { useFormState, useFormStatus } from 'react-dom';
import { resetPassword, type ResetPasswordFormState } from '@/app/reset-password/actions';

const initialState: ResetPasswordFormState = undefined;

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

export function ResetPasswordForm({ token, email }: { token: string; email: string }) {
  const [state, formAction] = useFormState(resetPassword, initialState);
  const errors = state?.errors ?? {};

  return (
    <form action={formAction} className="mt-6 space-y-4">
      <input type="hidden" name="token" value={token} />
      <input type="hidden" name="email" value={email} />

      {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">New Password</label>
        <input
          type="password"
          name="password"
          required
          minLength={8}
          className="mt-1.5 w-full rounded-md border-navy-100 text-sm focus:border-gold-500 focus:ring-gold-500"
        />
      </div>
      <div>
        <label className="block text-sm font-semibold text-navy-800">Confirm New Password</label>
        <input
          type="password"
          name="password_confirmation"
          required
          minLength={8}
          className="mt-1.5 w-full rounded-md border-navy-100 text-sm focus:border-gold-500 focus:ring-gold-500"
        />
      </div>
      <SubmitButton />
    </form>
  );
}
