"use client";

import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { toast } from "sonner";
import { api } from "@/lib/api";
import type { Party } from "@/lib/types";
import { Plus, Trash2, X } from "lucide-react";

interface PartyListProps {
  caseId: string;
  parties: Party[];
}

interface PartyFormData {
  name: string;
  role: string;
  representative: string;
}

const ROLE_OPTIONS = [
  "Klager",
  "Beklagter",
  "Nebenintervenient",
  "Patentinhaber",
  "Streithelfer",
];

export function PartyList({ caseId, parties }: PartyListProps) {
  const queryClient = useQueryClient();
  const [showForm, setShowForm] = useState(false);
  const [form, setForm] = useState<PartyFormData>({
    name: "",
    role: "",
    representative: "",
  });

  const addMutation = useMutation({
    mutationFn: (data: PartyFormData) =>
      api.post<Party>(`/cases/${caseId}/parties`, {
        name: data.name,
        role: data.role || undefined,
        representative: data.representative || undefined,
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["case", caseId] });
      toast.success("Partei hinzugefugt");
      setShowForm(false);
      setForm({ name: "", role: "", representative: "" });
    },
    onError: () => toast.error("Fehler beim Hinzufugen"),
  });

  const deleteMutation = useMutation({
    mutationFn: (partyId: string) => api.delete(`/parties/${partyId}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["case", caseId] });
      toast.success("Partei entfernt");
    },
    onError: () => toast.error("Fehler beim Entfernen"),
  });

  const inputClass =
    "w-full rounded-md border border-neutral-200 bg-white px-3 py-1.5 text-sm outline-none focus:border-neutral-400 focus:ring-1 focus:ring-neutral-400";

  return (
    <div>
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-medium text-neutral-700">
          Parteien ({parties.length})
        </h3>
        {!showForm && (
          <button
            onClick={() => setShowForm(true)}
            className="inline-flex items-center gap-1 text-sm text-neutral-500 hover:text-neutral-700"
          >
            <Plus className="h-3.5 w-3.5" />
            Hinzufugen
          </button>
        )}
      </div>

      {parties.length === 0 && !showForm && (
        <p className="mt-4 py-4 text-center text-sm text-neutral-400">
          Keine Parteien vorhanden.
        </p>
      )}

      <div className="mt-3 space-y-2">
        {parties.map((party) => (
          <div
            key={party.id}
            className="flex items-center justify-between rounded-md border border-neutral-200 bg-white px-4 py-2.5"
          >
            <div>
              <p className="text-sm font-medium text-neutral-900">
                {party.name}
              </p>
              <div className="mt-0.5 flex gap-3 text-xs text-neutral-500">
                {party.role && <span>{party.role}</span>}
                {party.representative && (
                  <span>Vertreter: {party.representative}</span>
                )}
              </div>
            </div>
            <button
              onClick={() => deleteMutation.mutate(party.id)}
              className="rounded p-1 text-neutral-300 hover:bg-neutral-100 hover:text-red-500"
              title="Partei entfernen"
            >
              <Trash2 className="h-3.5 w-3.5" />
            </button>
          </div>
        ))}
      </div>

      {showForm && (
        <div className="mt-3 rounded-md border border-neutral-200 bg-neutral-50 p-4">
          <div className="flex items-center justify-between">
            <span className="text-sm font-medium text-neutral-700">
              Neue Partei
            </span>
            <button
              onClick={() => setShowForm(false)}
              className="text-neutral-400 hover:text-neutral-600"
            >
              <X className="h-4 w-4" />
            </button>
          </div>
          <form
            onSubmit={(e) => {
              e.preventDefault();
              addMutation.mutate(form);
            }}
            className="mt-3 space-y-3"
          >
            <input
              type="text"
              required
              placeholder="Name der Partei"
              value={form.name}
              onChange={(e) => setForm({ ...form, name: e.target.value })}
              className={inputClass}
            />
            <div className="grid grid-cols-2 gap-3">
              <select
                value={form.role}
                onChange={(e) => setForm({ ...form, role: e.target.value })}
                className={inputClass}
              >
                <option value="">-- Rolle --</option>
                {ROLE_OPTIONS.map((r) => (
                  <option key={r} value={r}>
                    {r}
                  </option>
                ))}
              </select>
              <input
                type="text"
                placeholder="Vertreter / Anwalt"
                value={form.representative}
                onChange={(e) =>
                  setForm({ ...form, representative: e.target.value })
                }
                className={inputClass}
              />
            </div>
            <div className="flex justify-end">
              <button
                type="submit"
                disabled={addMutation.isPending}
                className="rounded-md bg-neutral-900 px-3 py-1.5 text-sm font-medium text-white hover:bg-neutral-800 disabled:opacity-50"
              >
                {addMutation.isPending ? "..." : "Hinzufugen"}
              </button>
            </div>
          </form>
        </div>
      )}
    </div>
  );
}
