"use client";

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

const FACT_FIELDS = [
  "FULL_NAME",
  "NICKNAME",
  "BIRTH_DATE",
  "BIRTH_PLACE",
  "DEATH_DATE",
  "DEATH_PLACE",
] as const;

const DATE_FIELDS: ReadonlySet<string> = new Set(["BIRTH_DATE", "DEATH_DATE"]);

const PRECISIONS = ["EXACT", "YEAR_ONLY", "MONTH_YEAR", "CIRCA", "BEFORE", "AFTER"] as const;

const VERIFICATION_STATUSES = ["VERIFIED", "PROBABLE", "UNCERTAIN", "DISPUTED"] as const;

export default function AddFactForm({
  trahId,
  personId,
}: {
  trahId: string;
  personId: string;
}) {
  const router = useRouter();
  const [field, setField] = useState<(typeof FACT_FIELDS)[number]>("BIRTH_DATE");
  const [value, setValue] = useState("");
  const [precisionQualifier, setPrecisionQualifier] = useState<string>("EXACT");
  const [verificationStatus, setVerificationStatus] =
    useState<(typeof VERIFICATION_STATUSES)[number]>("VERIFIED");
  const [sourceNote, setSourceNote] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  const isDateField = DATE_FIELDS.has(field);

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setError(null);
    setBusy(true);
    try {
      const res = await fetch(`/api/trahs/${trahId}/persons/${personId}/facts`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          field,
          value,
          precisionQualifier: isDateField ? precisionQualifier : undefined,
          verificationStatus,
          sourceNote: sourceNote.trim() ? sourceNote : undefined,
        }),
      });

      if (res.ok) {
        setValue("");
        setSourceNote("");
        router.refresh();
        return;
      }

      const data = (await res.json().catch(() => null)) as { error?: string } | null;
      if (data?.error === "PERSON_NOT_FOUND") {
        setError("This person could not be found.");
      } else if (data?.error === "FORBIDDEN") {
        setError("You don't have permission to edit this person.");
      } else {
        setError("Please check the values and try again.");
      }
    } catch {
      setError("Something went wrong. Please try again.");
    } finally {
      setBusy(false);
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <h3>Add a fact</h3>
      {error && (
        <p role="alert" style={{ color: "crimson" }}>
          {error}
        </p>
      )}

      <div>
        <label htmlFor="fact-field">Field</label>
        <br />
        <select
          id="fact-field"
          value={field}
          onChange={(e) => setField(e.target.value as (typeof FACT_FIELDS)[number])}
        >
          {FACT_FIELDS.map((f) => (
            <option key={f} value={f}>
              {f}
            </option>
          ))}
        </select>
      </div>

      <div>
        <label htmlFor="fact-value">Value</label>
        <br />
        <input
          id="fact-value"
          type={isDateField ? "date" : "text"}
          value={value}
          onChange={(e) => setValue(e.target.value)}
          required
        />
      </div>

      {isDateField && (
        <div>
          <label htmlFor="fact-precision">Precision</label>
          <br />
          <select
            id="fact-precision"
            value={precisionQualifier}
            onChange={(e) => setPrecisionQualifier(e.target.value)}
          >
            {PRECISIONS.map((p) => (
              <option key={p} value={p}>
                {p}
              </option>
            ))}
          </select>
        </div>
      )}

      <div>
        <label htmlFor="fact-verification">Verification status</label>
        <br />
        <select
          id="fact-verification"
          value={verificationStatus}
          onChange={(e) =>
            setVerificationStatus(e.target.value as (typeof VERIFICATION_STATUSES)[number])
          }
        >
          {VERIFICATION_STATUSES.map((v) => (
            <option key={v} value={v}>
              {v}
            </option>
          ))}
        </select>
      </div>

      <div>
        <label htmlFor="fact-source">Source note (optional)</label>
        <br />
        <input
          id="fact-source"
          type="text"
          value={sourceNote}
          onChange={(e) => setSourceNote(e.target.value)}
        />
      </div>

      <button type="submit" disabled={busy}>
        {busy ? "Saving…" : "Add fact"}
      </button>
    </form>
  );
}
