"use client";

import { useState, type FormEvent } from "react";
import { useRouter } from "next/navigation";
import type { LifeStatus } from "@prisma/client";

const CONTACT_TYPES = ["WHATSAPP", "PHONE", "EMAIL", "OTHER"] as const;
const VISIBILITIES = ["ONLY_ME", "FAMILY", "PUBLIC"] as const;

export default function AddContactForm({
  trahId,
  personId,
  lifeStatus,
}: {
  trahId: string;
  personId: string;
  lifeStatus: LifeStatus;
}) {
  const router = useRouter();
  const isAlive = lifeStatus === "ALIVE";

  const [type, setType] = useState<(typeof CONTACT_TYPES)[number]>("WHATSAPP");
  const [value, setValue] = useState("");
  // Non-ALIVE persons require an explicit visibility (addContact rejects a
  // missing one as INVALID_INPUT — see addContact.ts's header note), so
  // default the select to something explicit either way; ALIVE persons may
  // still leave it as the auto-default by not changing the selection away
  // from the server default (ONLY_ME here mirrors that default exactly).
  const [visibility, setVisibility] = useState<(typeof VISIBILITIES)[number]>("ONLY_ME");
  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}/contacts`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ type, value, visibility }),
      });

      if (res.ok) {
        setValue("");
        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 contact</h3>
      {error && (
        <p role="alert" style={{ color: "crimson" }}>
          {error}
        </p>
      )}

      <div>
        <label htmlFor="contact-type">Type</label>
        <br />
        <select
          id="contact-type"
          value={type}
          onChange={(e) => setType(e.target.value as (typeof CONTACT_TYPES)[number])}
        >
          {CONTACT_TYPES.map((t) => (
            <option key={t} value={t}>
              {t}
            </option>
          ))}
        </select>
      </div>

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

      <div>
        <label htmlFor="contact-visibility">
          Visibility{!isAlive ? " (required)" : ""}
        </label>
        <br />
        <select
          id="contact-visibility"
          value={visibility}
          onChange={(e) => setVisibility(e.target.value as (typeof VISIBILITIES)[number])}
        >
          {VISIBILITIES.map((v) => (
            <option key={v} value={v}>
              {v}
            </option>
          ))}
        </select>
      </div>

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