"use client";

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

export default function AddResidenceForm({
  trahId,
  personId,
}: {
  trahId: string;
  personId: string;
}) {
  const router = useRouter();
  const [place, setPlace] = useState("");
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [isCurrent, setIsCurrent] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setError(null);
    setBusy(true);
    try {
      const res = await fetch(`/api/trahs/${trahId}/persons/${personId}/residences`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          place,
          startDate,
          endDate: endDate ? endDate : undefined,
          isCurrent,
        }),
      });

      if (res.ok) {
        setPlace("");
        setStartDate("");
        setEndDate("");
        setIsCurrent(false);
        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 residence</h3>
      {error && (
        <p role="alert" style={{ color: "crimson" }}>
          {error}
        </p>
      )}

      <div>
        <label htmlFor="residence-place">Place</label>
        <br />
        <input
          id="residence-place"
          type="text"
          value={place}
          onChange={(e) => setPlace(e.target.value)}
          required
        />
      </div>

      <div>
        <label htmlFor="residence-start">Start date</label>
        <br />
        <input
          id="residence-start"
          type="date"
          value={startDate}
          onChange={(e) => setStartDate(e.target.value)}
          required
        />
      </div>

      <div>
        <label htmlFor="residence-end">End date (optional)</label>
        <br />
        <input
          id="residence-end"
          type="date"
          value={endDate}
          onChange={(e) => setEndDate(e.target.value)}
        />
      </div>

      <div>
        <label htmlFor="residence-current">
          <input
            id="residence-current"
            type="checkbox"
            checked={isCurrent}
            onChange={(e) => setIsCurrent(e.target.checked)}
          />{" "}
          Current residence
        </label>
      </div>

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