"use client"

import { useState } from "react"
import { MoreHorizontal, Pencil, Plus, Trash2 } from "lucide-react"
import { toast } from "sonner"
import { useRouter } from "next/navigation"
import { useTranslations } from "next-intl"

import type { DepartmentListItem } from "../types"
import { createDepartmentAction, deleteDepartmentAction, updateDepartmentAction } from "../actions"
import { Button } from "@/shared/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/shared/components/ui/dialog"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import { Textarea } from "@/shared/components/ui/textarea"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { Badge } from "@/shared/components/ui/badge"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/components/ui/alert-dialog"
import { formatDate } from "@/shared/lib/utils"

export function DepartmentsClient({ departments }: { departments: DepartmentListItem[] }) {
  const t = useTranslations("school")
  const router = useRouter()
  const [isWorking, setIsWorking] = useState(false)
  const [createOpen, setCreateOpen] = useState(false)
  const [editItem, setEditItem] = useState<DepartmentListItem | null>(null)
  const [deleteItem, setDeleteItem] = useState<DepartmentListItem | null>(null)

  const handleCreate = async (formData: FormData) => {
    setIsWorking(true)
    try {
      const res = await createDepartmentAction(undefined, formData)
      if (res.success) {
        toast.success(res.message)
        setCreateOpen(false)
        router.refresh()
      } else {
        toast.error(res.message || t("departments.delete.title"))
      }
    } catch {
      toast.error(t("departments.delete.title"))
    } finally {
      setIsWorking(false)
    }
  }

  const handleUpdate = async (formData: FormData) => {
    if (!editItem) return
    setIsWorking(true)
    try {
      const res = await updateDepartmentAction(editItem.id, undefined, formData)
      if (res.success) {
        toast.success(res.message)
        setEditItem(null)
        router.refresh()
      } else {
        toast.error(res.message || t("departments.delete.title"))
      }
    } catch {
      toast.error(t("departments.delete.title"))
    } finally {
      setIsWorking(false)
    }
  }

  const handleDelete = async () => {
    if (!deleteItem) return
    setIsWorking(true)
    try {
      const res = await deleteDepartmentAction(deleteItem.id)
      if (res.success) {
        toast.success(res.message)
        setDeleteItem(null)
        router.refresh()
      } else {
        toast.error(res.message || t("departments.delete.title"))
      }
    } catch {
      toast.error(t("departments.delete.title"))
    } finally {
      setIsWorking(false)
    }
  }

  return (
    <>
      <div className="flex justify-end">
        <Button onClick={() => setCreateOpen(true)} disabled={isWorking}>
          <Plus className="mr-2 h-4 w-4" />
          {t("departments.new")}
        </Button>
      </div>

      <Card className="shadow-none">
        <CardHeader className="flex flex-row items-center justify-between space-y-0">
          <CardTitle className="text-base">{t("departments.all")}</CardTitle>
          <Badge variant="secondary" className="tabular-nums">
            {departments.length}
          </Badge>
        </CardHeader>
        <CardContent>
          {departments.length === 0 ? (
            <EmptyState
              title={t("departments.empty.title")}
              description={t("departments.empty.description")}
              className="h-auto border-none shadow-none"
            />
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>{t("departments.column.name")}</TableHead>
                  <TableHead>{t("departments.column.description")}</TableHead>
                  <TableHead>{t("departments.column.updated")}</TableHead>
                  <TableHead className="w-[60px]" />
                </TableRow>
              </TableHeader>
              <TableBody>
                {departments.map((d) => (
                  <TableRow key={d.id}>
                    <TableCell className="font-medium">{d.name}</TableCell>
                    <TableCell className="text-muted-foreground">{d.description || "-"}</TableCell>
                    <TableCell className="text-muted-foreground">{formatDate(d.updatedAt)}</TableCell>
                    <TableCell className="text-right">
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" size="icon" className="h-8 w-8" disabled={isWorking}>
                            <MoreHorizontal className="h-4 w-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuItem onClick={() => setEditItem(d)}>
                            <Pencil className="mr-2 h-4 w-4" />
                            {t("departments.actions.edit")}
                          </DropdownMenuItem>
                          <DropdownMenuSeparator />
                          <DropdownMenuItem
                            className="text-destructive focus:text-destructive"
                            onClick={() => setDeleteItem(d)}
                          >
                            <Trash2 className="mr-2 h-4 w-4" />
                            {t("departments.actions.delete")}
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      <Dialog open={createOpen} onOpenChange={setCreateOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{t("departments.form.createTitle")}</DialogTitle>
          </DialogHeader>
          <form action={handleCreate} className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="name">{t("departments.form.name")}</Label>
              <Input id="name" name="name" placeholder={t("departments.form.namePlaceholder")} autoFocus />
            </div>
            <div className="space-y-2">
              <Label htmlFor="description">{t("departments.form.description")}</Label>
              <Textarea id="description" name="description" placeholder={t("departments.form.descriptionPlaceholder")} />
            </div>
            <DialogFooter>
              <Button type="button" variant="outline" onClick={() => setCreateOpen(false)} disabled={isWorking}>
                {t("departments.form.cancel")}
              </Button>
              <Button type="submit" disabled={isWorking}>
                {t("departments.form.create")}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      <Dialog open={Boolean(editItem)} onOpenChange={(open) => {
        if (!open) setEditItem(null)
      }}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{t("departments.form.editTitle")}</DialogTitle>
          </DialogHeader>
          {editItem ? (
            <form action={handleUpdate} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="edit-name">{t("departments.form.name")}</Label>
                <Input id="edit-name" name="name" defaultValue={editItem.name} />
              </div>
              <div className="space-y-2">
                <Label htmlFor="edit-description">{t("departments.form.description")}</Label>
                <Textarea id="edit-description" name="description" defaultValue={editItem.description || ""} />
              </div>
              <DialogFooter>
                <Button type="button" variant="outline" onClick={() => setEditItem(null)} disabled={isWorking}>
                  {t("departments.form.cancel")}
                </Button>
                <Button type="submit" disabled={isWorking}>
                  {t("departments.form.save")}
                </Button>
              </DialogFooter>
            </form>
          ) : null}
        </DialogContent>
      </Dialog>

      <AlertDialog open={Boolean(deleteItem)} onOpenChange={(open) => {
        if (!open) setDeleteItem(null)
      }}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{t("departments.delete.title")}</AlertDialogTitle>
            <AlertDialogDescription>
              {t("departments.delete.description", { name: deleteItem?.name || "" })}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isWorking}>{t("departments.delete.cancel")}</AlertDialogCancel>
            <AlertDialogAction onClick={handleDelete} disabled={isWorking}>
              {t("departments.delete.confirm")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  )
}
