"use client";

// Simple "end this partnership" action for an existing PARTNER relationship
// (REQ-REL-003) — sets endDate + status via updateRelationship(). Deliberately
// minimal (a status pick + optional end date, not a full editor), per the
// ticket's guidance to prioritize the create flow.
import { useState, type FormEvent } from "react";
import { useRouter } from "next/navigation";

const END_STATUSES = ["DIVORCED", "WIDOWED", "ENDED"] as const;

export default function EndPartnershipForm({
  trahId,
  relationshipId,
}: {
  trahId: string;
  relationshipId: string;
}) {
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [status, setStatus] = useState<(typeof END_STATUSES)[number]>("DIVORCED");
  const [endDate, setEndDate] = useState("");
  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}/relationships/${relationshipId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          status,
          endDate: endDate ? endDate : undefined,
        }),
      });

      if (res.ok) {
        setOpen(false);
        router.refresh();
        return;
      }

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

  if (!open) {
    return (
      <>
        {" "}
        <button type="button" onClick={() => setOpen(true)}>
          End this partnership
        </button>
      </>
    );
  }

  return (
    <form onSubmit={handleSubmit} style={{ marginTop: "0.5rem" }}>
      {error && (
        <p role="alert" style={{ color: "crimson" }}>
          {error}
        </p>
      )}

      <div>
        <label htmlFor={`end-status-${relationshipId}`}>Status</label>
        <br />
        <select
          id={`end-status-${relationshipId}`}
          value={status}
          onChange={(e) => setStatus(e.target.value as (typeof END_STATUSES)[number])}
        >
          {END_STATUSES.map((s) => (
            <option key={s} value={s}>
              {s}
            </option>
          ))}
        </select>
      </div>

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

      <button type="submit" disabled={busy}>
        {busy ? "Saving…" : "Confirm"}
      </button>{" "}
      <button type="button" onClick={() => setOpen(false)} disabled={busy}>
        Cancel
      </button>
    </form>
  );
}
