"use client";

import { useState } from "react";
import { Edit, Plus, Trash2 } from "lucide-react";

import ConfirmDialog from "@/components/common/ConfirmDialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useToast } from "@/components/common/ToastProvider";
import { api } from "@/lib/api";
import type { InventoryCategory, InventoryLocation, InventorySupplier } from "@/types/inventory";
import { getErrorMessage } from "./inventory-utils";

type MasterKind = "categories" | "locations" | "suppliers";
type MasterEntry = InventoryCategory | InventoryLocation | InventorySupplier;

type Props = {
  title: string;
  kind: MasterKind;
  entries: MasterEntry[];
  canManage: boolean;
  onChanged: () => void;
};

export default function MasterDataSection({ title, kind, entries, canManage, onChanged }: Props) {
  const { showToast } = useToast();
  const [editing, setEditing] = useState<MasterEntry | null>(null);
  const [deleteEntry, setDeleteEntry] = useState<MasterEntry | null>(null);
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [pending, setPending] = useState(false);
  const [error, setError] = useState("");

  function startCreate() {
    setEditing({ id: 0, name: "", description: null, created_at: "", updated_at: "" } as MasterEntry);
    setName("");
    setDescription("");
    setError("");
  }

  function startEdit(entry: MasterEntry) {
    setEditing(entry);
    setName(entry.name);
    setDescription("description" in entry && entry.description ? entry.description : "");
    setError("");
  }

  async function save() {
    if (!editing) {
      return;
    }
    if (!name.trim()) {
      setError("Bitte einen Namen angeben.");
      return;
    }
    setPending(true);
    setError("");
    const payload = kind === "suppliers"
      ? { name: name.trim(), notes: description.trim() || null }
      : { name: name.trim(), description: description.trim() || null };
    try {
      if (editing.id) {
        await api.put(`/inventory/${kind}/${editing.id}`, payload);
      } else {
        await api.post(`/inventory/${kind}`, payload);
      }
      showToast({ type: "success", title: `${title} gespeichert` });
      setEditing(null);
      onChanged();
    } catch (err) {
      const message = getErrorMessage(err);
      setError(message);
      showToast({ type: "error", title: `${title} konnte nicht gespeichert werden`, description: message });
    } finally {
      setPending(false);
    }
  }

  async function confirmDelete() {
    if (!deleteEntry) {
      return;
    }
    setPending(true);
    try {
      await api.delete(`/inventory/${kind}/${deleteEntry.id}`);
      showToast({ type: "success", title: `${title} gelöscht`, description: deleteEntry.name });
      setDeleteEntry(null);
      onChanged();
    } catch (err) {
      const message = getErrorMessage(err);
      showToast({ type: "error", title: `${title} konnte nicht gelöscht werden`, description: message });
    } finally {
      setPending(false);
    }
  }

  return (
    <section className="rounded-lg border bg-white p-5">
      <div className="mb-4 flex items-center justify-between gap-3">
        <h2 className="font-semibold text-slate-950">{title}</h2>
        {canManage && <Button type="button" size="sm" onClick={startCreate}><Plus size={14} />Neu</Button>}
      </div>

      <div className="divide-y">
        {entries.length === 0 ? (
          <p className="py-4 text-sm text-slate-500">Noch keine Einträge vorhanden.</p>
        ) : entries.map((entry) => (
          <div key={entry.id} className="flex items-center justify-between gap-3 py-3">
            <div>
              <p className="font-medium text-slate-950">{entry.name}</p>
              {"description" in entry && entry.description && <p className="text-sm text-slate-500">{entry.description}</p>}
              {"notes" in entry && entry.notes && <p className="text-sm text-slate-500">{entry.notes}</p>}
            </div>
            {canManage && (
              <div className="flex gap-2">
                <Button type="button" variant="ghost" size="icon-sm" onClick={() => startEdit(entry)} title="Bearbeiten"><Edit size={16} /></Button>
                <Button type="button" variant="destructive" size="icon-sm" onClick={() => setDeleteEntry(entry)} title="Löschen"><Trash2 size={16} /></Button>
              </div>
            )}
          </div>
        ))}
      </div>

      {editing && (
        <div className="mt-4 grid gap-3 rounded-lg border bg-slate-50 p-4">
          <Input value={name} placeholder="Name" onChange={(event) => setName(event.target.value)} />
          <textarea className="min-h-20 rounded-lg border p-2 text-sm" value={description} placeholder={kind === "suppliers" ? "Notizen" : "Beschreibung"} onChange={(event) => setDescription(event.target.value)} />
          {error && <p className="text-sm text-red-600">{error}</p>}
          <div className="flex gap-2">
            <Button type="button" onClick={save} disabled={pending}>{pending ? "Speichert..." : "Speichern"}</Button>
            <Button type="button" variant="outline" onClick={() => setEditing(null)} disabled={pending}>Abbrechen</Button>
          </div>
        </div>
      )}

      <ConfirmDialog
        open={Boolean(deleteEntry)}
        title={`${title} löschen`}
        description="Der Eintrag wird entfernt. Verknüpfte Artikel behalten ihre sonstigen Daten."
        pending={pending}
        onOpenChange={(open) => !open && setDeleteEntry(null)}
        onConfirm={confirmDelete}
      >
        {deleteEntry?.name}
      </ConfirmDialog>
    </section>
  );
}
