"use client";

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

import { Button } from "@/components/ui/button";
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
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 { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
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 [educatorToDelete, setEducatorToDelete] = 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 = (educator: EducatorDto) => {
    startTransition(async () => {
      const res = await deleteEducator(educator.id);
      if (res.error) {
        toast.error(res.error);
      } else {
        toast.success("ErzieherIn gelöscht.");
        setEducatorToDelete(null);
      }
    });
  };

  return (
    <div className="flex flex-col gap-4">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div className="relative min-w-72 max-[760px]:w-full max-[760px]:min-w-0">
          <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[var(--ink-muted)] [stroke-width:1.7]" />
          <Input placeholder="Name suchen" className="pl-9" />
        </div>
        <Dialog open={openCreate} onOpenChange={setOpenCreate}>
          <DialogTrigger asChild>
            <Button className="gap-2">
              <Plus className="h-4 w-4 [stroke-width:1.7]" />
              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>

      <Card>
        <CardHeader className="flex-row items-center justify-between">
          <div>
            <CardTitle>Team</CardTitle>
            <p className="mt-1 text-[13.5px] text-[var(--ink-soft)]">
              {educators.length} Einträge im Personalstamm.
            </p>
          </div>
          <Badge variant="secondary" className="tabular-nums">
            {educators.filter((ed) => ed.active).length} aktiv
          </Badge>
        </CardHeader>
        <CardContent className="px-0 pb-0">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="pl-6">Vorname</TableHead>
              <TableHead>Nachname</TableHead>
              <TableHead>Status</TableHead>
              <TableHead className="pr-6 text-right">Aktionen</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {educators.length === 0 ? (
              <TableRow>
                <TableCell colSpan={4} className="h-32 text-center">
                  <div className="flex max-h-[240px] min-h-[200px] flex-col items-center justify-center">
                    <div className="mb-3 flex h-12 w-12 items-center justify-center rounded-2xl bg-[var(--accent-soft)] text-[var(--accent-deep)]">
                      <Plus className="h-6 w-6 [stroke-width:1.7]" />
                    </div>
                    <p className="text-sm font-medium text-[var(--ink)]">
                      Keine Einträge gefunden
                    </p>
                    <p className="mt-1 text-sm text-[var(--ink-soft)]">
                      Lege die erste Person im Team an.
                    </p>
                  </div>
                </TableCell>
              </TableRow>
            ) : (
              educators.map((ed) => (
                <TableRow key={ed.id}>
                  <TableCell className="pl-6 font-medium">{ed.firstName}</TableCell>
                  <TableCell>{ed.lastName}</TableCell>
                  <TableCell>
                    <Badge variant={ed.active ? "success" : "secondary"}>
                      {ed.active ? "Aktiv" : "Inaktiv"}
                    </Badge>
                  </TableCell>
                  <TableCell className="pr-6 text-right">
                    <Button variant="ghost" size="icon" onClick={() => setEditingEducator(ed)}>
                      <Pencil className="h-4 w-4 [stroke-width:1.7]" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="text-[var(--danger)] hover:bg-[var(--danger-soft)] hover:text-[var(--danger)]"
                      onClick={() => setEducatorToDelete(ed)}
                      disabled={isPending}
                      aria-label={`${ed.firstName} ${ed.lastName} löschen`}
                    >
                      <Trash2 className="h-4 w-4 [stroke-width:1.7]" />
                    </Button>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
        </CardContent>
      </Card>

      {/* 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>

      <ConfirmDialog
        open={!!educatorToDelete}
        onOpenChange={(open) => {
          if (!open) setEducatorToDelete(null);
        }}
        title="ErzieherIn löschen?"
        description={
          educatorToDelete
            ? `${educatorToDelete.firstName} ${educatorToDelete.lastName} wird aus dem Personalstamm entfernt.`
            : "Dieser Eintrag wird aus dem Personalstamm entfernt."
        }
        confirmLabel="Löschen"
        pendingLabel="Wird gelöscht..."
        isPending={isPending}
        onConfirm={() => {
          if (educatorToDelete) handleDelete(educatorToDelete);
        }}
      />
    </div>
  );
}
