"use client";

import { useState, useTransition } from "react";
import { Plus, Pencil, Trash2 } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Badge } from "@/components/ui/badge";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";

import { createEducator, updateEducator, deleteEducator } from "../actions";

type EducatorDto = {
  id: string;
  firstName: string;
  lastName: string;
  active: boolean;
};

export function ErzieherList({ educators }: { educators: EducatorDto[] }) {
  const [openCreate, setOpenCreate] = useState(false);
  const [editingEducator, setEditingEducator] = useState<EducatorDto | null>(null);
  const [isPending, startTransition] = useTransition();

  const handleCreate = (formData: FormData) => {
    const data = {
      firstName: formData.get("firstName") as string,
      lastName: formData.get("lastName") as string,
      active: formData.get("active") === "on",
    };

    startTransition(async () => {
      const res = await createEducator(data);
      if (res.error) {
        toast.error(res.error);
      } else {
        toast.success("ErzieherIn angelegt.");
        setOpenCreate(false);
      }
    });
  };

  const handleUpdate = (formData: FormData) => {
    if (!editingEducator) return;
    const data = {
      firstName: formData.get("firstName") as string,
      lastName: formData.get("lastName") as string,
      active: formData.get("active") === "on",
    };

    startTransition(async () => {
      const res = await updateEducator(editingEducator.id, data);
      if (res.error) {
        toast.error(res.error);
      } else {
        toast.success("Daten aktualisiert.");
        setEditingEducator(null);
      }
    });
  };

  const handleDelete = (id: string) => {
    if (!confirm("Wirklich löschen? Diese Aktion kann nicht rückgängig gemacht werden.")) return;
    startTransition(async () => {
      const res = await deleteEducator(id);
      if (res.error) {
        toast.error(res.error);
      } else {
        toast.success("ErzieherIn gelöscht.");
      }
    });
  };

  return (
    <div className="flex flex-col gap-4">
      <div className="flex justify-end">
        <Dialog open={openCreate} onOpenChange={setOpenCreate}>
          <DialogTrigger asChild>
            <Button className="gap-2">
              <Plus className="h-4 w-4" />
              ErzieherIn anlegen
            </Button>
          </DialogTrigger>
          <DialogContent>
            <form action={handleCreate}>
              <DialogHeader>
                <DialogTitle>Neue(n) ErzieherIn anlegen</DialogTitle>
                <DialogDescription>
                  Erfasse die Stammdaten des Kita-Personals.
                </DialogDescription>
              </DialogHeader>
              <div className="grid gap-4 py-4">
                <div className="grid gap-2">
                  <Label htmlFor="firstName">Vorname</Label>
                  <Input id="firstName" name="firstName" required />
                </div>
                <div className="grid gap-2">
                  <Label htmlFor="lastName">Nachname</Label>
                  <Input id="lastName" name="lastName" required />
                </div>
                <div className="flex items-center gap-2 mt-2">
                  <Switch id="active" name="active" defaultChecked />
                  <Label htmlFor="active">Aktiv (Arbeitet aktuell hier)</Label>
                </div>
              </div>
              <DialogFooter>
                <Button type="button" variant="ghost" onClick={() => setOpenCreate(false)}>Abbrechen</Button>
                <Button type="submit" disabled={isPending}>Speichern</Button>
              </DialogFooter>
            </form>
          </DialogContent>
        </Dialog>
      </div>

      <div className="rounded-md border bg-background">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Vorname</TableHead>
              <TableHead>Nachname</TableHead>
              <TableHead>Status</TableHead>
              <TableHead className="text-right">Aktionen</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {educators.length === 0 ? (
              <TableRow>
                <TableCell colSpan={4} className="text-center text-muted-foreground h-24">
                  Keine Einträge gefunden.
                </TableCell>
              </TableRow>
            ) : (
              educators.map((ed) => (
                <TableRow key={ed.id}>
                  <TableCell className="font-medium">{ed.firstName}</TableCell>
                  <TableCell>{ed.lastName}</TableCell>
                  <TableCell>
                    <Badge variant={ed.active ? "success" : "secondary"}>
                      {ed.active ? "Aktiv" : "Inaktiv"}
                    </Badge>
                  </TableCell>
                  <TableCell className="text-right">
                    <Button variant="ghost" size="icon" onClick={() => setEditingEducator(ed)}>
                      <Pencil className="h-4 w-4" />
                    </Button>
                    <Button variant="ghost" size="icon" className="text-destructive hover:text-destructive" onClick={() => handleDelete(ed.id)} disabled={isPending}>
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* Edit Dialog */}
      <Dialog open={!!editingEducator} onOpenChange={(open) => !open && setEditingEducator(null)}>
        <DialogContent>
          <form action={handleUpdate}>
            <DialogHeader>
              <DialogTitle>ErzieherIn bearbeiten</DialogTitle>
            </DialogHeader>
            {editingEducator && (
              <div className="grid gap-4 py-4">
                <div className="grid gap-2">
                  <Label htmlFor="edit-firstName">Vorname</Label>
                  <Input id="edit-firstName" name="firstName" defaultValue={editingEducator.firstName} required />
                </div>
                <div className="grid gap-2">
                  <Label htmlFor="edit-lastName">Nachname</Label>
                  <Input id="edit-lastName" name="lastName" defaultValue={editingEducator.lastName} required />
                </div>
                <div className="flex items-center gap-2 mt-2">
                  <Switch id="edit-active" name="active" defaultChecked={editingEducator.active} />
                  <Label htmlFor="edit-active">Aktiv</Label>
                </div>
              </div>
            )}
            <DialogFooter>
              <Button type="button" variant="ghost" onClick={() => setEditingEducator(null)}>Abbrechen</Button>
              <Button type="submit" disabled={isPending}>Aktualisieren</Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  );
}
