"use client";

import { useEffect, useState } from "react";
import { resendVerification, verifyEmail, type User } from "@/lib/api/auth";
import { CodeField, FormAlert, Submit, readError, type FieldErrors } from "./Form";

const COOLDOWN = 60;

/** Enter the 6-digit code sent to `email`. Resend is locked for a minute after each send. */
export default function VerifyEmail({ email, onVerified }: { email: string; onVerified: (token: string, user: User) => void }) {
  const [code, setCode] = useState("");
  const [busy, setBusy] = useState(false);
  const [errors, setErrors] = useState<FieldErrors>({});
  const [message, setMessage] = useState<string | null>(null);
  const [sent, setSent] = useState<string | null>(null);
  const [wait, setWait] = useState(COOLDOWN);

  useEffect(() => {
    if (wait <= 0) return;
    const t = window.setTimeout(() => setWait((w) => w - 1), 1000);
    return () => window.clearTimeout(t);
  }, [wait]);

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    setBusy(true);
    setErrors({});
    setMessage(null);
    try {
      const s = await verifyEmail(email, code);
      onVerified(s.token, s.user);
    } catch (err) {
      const r = readError(err);
      setErrors(r.fields);
      setMessage(r.message);
      setBusy(false);
    }
  };

  const resend = async () => {
    setMessage(null);
    setSent(null);
    try {
      await resendVerification(email);
      setSent("A new code is on its way.");
      setWait(COOLDOWN);
    } catch (err) {
      setMessage(readError(err).message);
    }
  };

  return (
    <form className="acct-form" onSubmit={submit} noValidate>
      <p className="acct-lead">
        We sent a 6-digit code to <strong>{email}</strong>. Enter it to finish.
      </p>
      <CodeField label="Verification code" value={code} onChange={setCode} error={errors.code} required autoFocus />
      {message && <FormAlert>{message}</FormAlert>}
      {sent && <FormAlert tone="ok">{sent}</FormAlert>}
      <Submit busy={busy}>Verify email</Submit>
      <p className="acct-alt">
        Did not get it?{" "}
        <button type="button" className="acct-link" onClick={resend} disabled={wait > 0}>
          {wait > 0 ? `Resend in ${wait}s` : "Resend code"}
        </button>
      </p>
    </form>
  );
}
