"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";

export default function ClaimConfirm({
  trahId,
  personId,
  displayName,
}: {
  trahId: string;
  personId: string;
  displayName: string;
}) {
  const router = useRouter();
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const [success, setSuccess] = useState(false);

  async function handleConfirm() {
    setError(null);
    setBusy(true);
    try {
      const res = await fetch(
        `/api/trahs/${trahId}/persons/${personId}/claim`,
        { method: "POST" },
      );

      if (res.ok) {
        setSuccess(true);
        router.refresh();
        setTimeout(() => router.push(`/trahs/${trahId}`), 1000);
        return;
      }

      const data = (await res.json().catch(() => null)) as
        | { error?: string }
        | null;

      if (data?.error === "ALREADY_CLAIMED") {
        setError("This person has already been claimed by another member.");
      } else if (data?.error === "PERSON_NOT_FOUND") {
        setError("This person could not be found.");
      } else {
        setError("Something went wrong. Please try again.");
      }
    } catch {
      setError("Something went wrong. Please try again.");
    } finally {
      setBusy(false);
    }
  }

  if (success) {
    return <p>You have claimed {displayName}. Redirecting…</p>;
  }

  return (
    <div>
      <p>Are you {displayName}?</p>
      {error && (
        <p role="alert" style={{ color: "crimson" }}>
          {error}
        </p>
      )}
      <button type="button" disabled={busy} onClick={handleConfirm}>
        {busy ? "Confirming…" : `Yes, I am ${displayName}`}
      </button>
    </div>
  );
}
