"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, Users } from "lucide-react";

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

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

const ROLE_OPTIONS = [
  "Kläger",
  "Beklagter",
  "Nebenintervenient",
  "Patentinhaber",
  "Streithelfer",
];

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

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 hinzugefügt");
      setShowForm(false);
      setForm({ name: "", role: "", representative: "" });
    },
    onError: () => toast.error("Fehler beim Hinzufügen"),
  });

  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"),
  });

  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 transition-colors hover:text-neutral-700"
          >
            <Plus className="h-3.5 w-3.5" />
            Hinzufügen
          </button>
        )}
      </div>

      {parties.length === 0 && !showForm && (
        <div className="mt-4 flex flex-col items-center py-6 text-center">
          <div className="rounded-xl bg-neutral-100 p-3">
            <Users className="h-5 w-5 text-neutral-400" />
          </div>
          <p className="mt-2 text-sm text-neutral-500">
            Keine Parteien vorhanden.
          </p>
          <button
            onClick={() => setShowForm(true)}
            className="mt-3 inline-flex items-center gap-1 text-sm text-neutral-500 transition-colors hover:text-neutral-700"
          >
            <Plus className="h-3.5 w-3.5" />
            Erste Partei hinzufügen
          </button>
        </div>
      )}

      <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 transition-colors hover:bg-neutral-50"
          >
            <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 transition-colors 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 transition-colors hover:text-neutral-600"
            >
              <X className="h-4 w-4" />
            </button>
          </div>
          <form
            onSubmit={(e) => {
              e.preventDefault();
              if (!form.name.trim()) {
                toast.error("Bitte Namen eingeben");
                return;
              }
              addMutation.mutate(form);
            }}
            className="mt-3 space-y-3"
          >
            <input
              type="text"
              placeholder="Name der Partei"
              value={form.name}
              onChange={(e) => setForm({ ...form, name: e.target.value })}
              className={inputClass}
            />
            <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
              <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 transition-colors hover:bg-neutral-800 disabled:opacity-50"
              >
                {addMutation.isPending ? "Speichern..." : "Hinzufügen"}
              </button>
            </div>
          </form>
        </div>
      )}
    </div>
  );
}
