"use client"

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

import type { AdminClassListItem, ClassSubjectTeacherAssignment, TeacherOption } from "../types"
import { DEFAULT_CLASS_SUBJECTS } from "../types"
import { createGradeClassAction, deleteGradeClassAction, updateGradeClassAction } 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 { 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/shared/components/ui/select"
import { formatDate } from "@/shared/lib/utils"

export function GradeClassesClient({
  classes,
  teachers,
  managedGrades,
}: {
  classes: AdminClassListItem[]
  teachers: TeacherOption[]
  managedGrades: { id: string; name: string; schoolId: string; schoolName: string | null }[]
}) {
  const router = useRouter()
  const [isWorking, setIsWorking] = useState(false)
  const [createOpen, setCreateOpen] = useState(false)
  const [editItem, setEditItem] = useState<AdminClassListItem | null>(null)
  const [deleteItem, setDeleteItem] = useState<AdminClassListItem | null>(null)

  const defaultTeacherId = useMemo(() => teachers[0]?.id ?? "", [teachers])
  const [createTeacherId, setCreateTeacherId] = useState(defaultTeacherId)
  const [createGradeId, setCreateGradeId] = useState(managedGrades[0]?.id ?? "")

  const [editTeacherId, setEditTeacherId] = useState("")
  const [editGradeId, setEditGradeId] = useState("")
  const [editSubjectTeachers, setEditSubjectTeachers] = useState<Array<{ subject: string; teacherId: string | null }>>([])

  useEffect(() => {
    if (!createOpen) return
    setCreateTeacherId(defaultTeacherId)
    setCreateGradeId(managedGrades[0]?.id ?? "")
  }, [createOpen, defaultTeacherId, managedGrades])

  useEffect(() => {
    if (!editItem) return
    setEditTeacherId(editItem.teacher.id)
    setEditGradeId(editItem.gradeId ?? managedGrades[0]?.id ?? "")
    setEditSubjectTeachers(
      DEFAULT_CLASS_SUBJECTS.map((s) => ({
        subject: s,
        teacherId: editItem.subjectTeachers.find((st) => st.subject === s)?.teacher?.id ?? null,
      }))
    )
  }, [editItem, managedGrades])

  const handleCreate = async (formData: FormData) => {
    setIsWorking(true)
    try {
      const res = await createGradeClassAction(undefined, formData)
      if (res.success) {
        toast.success(res.message)
        setCreateOpen(false)
        router.refresh()
      } else {
        toast.error(res.message || "Failed to create class")
      }
    } catch {
      toast.error("Failed to create class")
    } finally {
      setIsWorking(false)
    }
  }

  const handleUpdate = async (formData: FormData) => {
    if (!editItem) return
    setIsWorking(true)
    try {
      const res = await updateGradeClassAction(editItem.id, undefined, formData)
      if (res.success) {
        toast.success(res.message)
        setEditItem(null)
        router.refresh()
      } else {
        toast.error(res.message || "Failed to update class")
      }
    } catch {
      toast.error("Failed to update class")
    } finally {
      setIsWorking(false)
    }
  }

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

  const setSubjectTeacher = (subject: string, teacherId: string | null) => {
    setEditSubjectTeachers((prev) => prev.map((p) => (p.subject === subject ? { ...p, teacherId } : p)))
  }

  const formatSubjectTeachers = (list: ClassSubjectTeacherAssignment[]) => {
    const pairs = list
      .filter((x) => x.teacher)
      .map((x) => `${x.subject}: ${x.teacher?.name ?? ""}`)
      .filter((x) => x.length > 0)
    return pairs.length > 0 ? pairs.join(", ") : "-"
  }

  const selectedCreateGrade = managedGrades.find(g => g.id === createGradeId)
  const selectedEditGrade = managedGrades.find(g => g.id === editGradeId)

  return (
    <>
      <div className="flex justify-end">
        <Button onClick={() => setCreateOpen(true)} disabled={isWorking || managedGrades.length === 0}>
          <Plus className="mr-2 h-4 w-4" />
          New class
        </Button>
      </div>

      <Card className="shadow-none">
        <CardHeader className="flex flex-row items-center justify-between space-y-0">
          <CardTitle className="text-base">All classes</CardTitle>
          <Badge variant="secondary" className="tabular-nums">
            {classes.length}
          </Badge>
        </CardHeader>
        <CardContent>
          {classes.length === 0 ? (
            <EmptyState
              title="No classes"
              description={managedGrades.length === 0 ? "You are not managing any grades yet." : "Create classes to manage students and schedules."}
              className="h-auto border-none shadow-none"
            />
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>School</TableHead>
                  <TableHead>Name</TableHead>
                  <TableHead>Grade</TableHead>
                  <TableHead>Homeroom</TableHead>
                  <TableHead>Room</TableHead>
                  <TableHead>Homeroom Teacher</TableHead>
                  <TableHead>Subject Teachers</TableHead>
                  <TableHead className="text-right">Students</TableHead>
                  <TableHead>Updated</TableHead>
                  <TableHead className="w-[60px]" />
                </TableRow>
              </TableHeader>
              <TableBody>
                {classes.map((c) => (
                  <TableRow key={c.id}>
                    <TableCell className="text-muted-foreground">{c.schoolName ?? "-"}</TableCell>
                    <TableCell className="font-medium">{c.name}</TableCell>
                    <TableCell className="text-muted-foreground">{c.grade}</TableCell>
                    <TableCell className="text-muted-foreground">{c.homeroom ?? "-"}</TableCell>
                    <TableCell className="text-muted-foreground">{c.room ?? "-"}</TableCell>
                    <TableCell className="text-muted-foreground">{c.teacher.name}</TableCell>
                    <TableCell className="text-muted-foreground">{formatSubjectTeachers(c.subjectTeachers)}</TableCell>
                    <TableCell className="text-muted-foreground tabular-nums text-right">{c.studentCount}</TableCell>
                    <TableCell className="text-muted-foreground">{formatDate(c.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(c)}>
                            <Pencil className="mr-2 h-4 w-4" />
                            Edit
                          </DropdownMenuItem>
                          <DropdownMenuSeparator />
                          <DropdownMenuItem
                            className="text-destructive focus:text-destructive"
                            onClick={() => setDeleteItem(c)}
                          >
                            <Trash2 className="mr-2 h-4 w-4" />
                            Delete
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      <Dialog open={createOpen} onOpenChange={setCreateOpen}>
        <DialogContent className="sm:max-w-[560px]">
          <DialogHeader>
            <DialogTitle>New class</DialogTitle>
          </DialogHeader>
          <form action={handleCreate} className="space-y-4">
            <div className="grid grid-cols-4 items-center gap-4">
              <Label className="text-right">Grade</Label>
              <div className="col-span-3">
                <Select value={createGradeId} onValueChange={setCreateGradeId} disabled={managedGrades.length === 0}>
                  <SelectTrigger>
                    <SelectValue placeholder={managedGrades.length === 0 ? "No managed grades" : "Select a grade"} />
                  </SelectTrigger>
                  <SelectContent>
                    {managedGrades.map((g) => (
                      <SelectItem key={g.id} value={g.id}>
                        {g.name} ({g.schoolName})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <input type="hidden" name="gradeId" value={createGradeId} />
                <input type="hidden" name="grade" value={selectedCreateGrade?.name ?? ""} />
                <input type="hidden" name="schoolId" value={selectedCreateGrade?.schoolId ?? ""} />
                <input type="hidden" name="schoolName" value={selectedCreateGrade?.schoolName ?? ""} />
              </div>
            </div>

            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="create-name" className="text-right">
                Name
              </Label>
              <Input id="create-name" name="name" className="col-span-3" placeholder="e.g. Class 3" autoFocus />
            </div>

            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="create-homeroom" className="text-right">
                Homeroom
              </Label>
              <Input id="create-homeroom" name="homeroom" className="col-span-3" placeholder="Optional" />
            </div>

            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="create-room" className="text-right">
                Room
              </Label>
              <Input id="create-room" name="room" className="col-span-3" placeholder="Optional" />
            </div>

            <div className="grid grid-cols-4 items-center gap-4">
              <Label className="text-right">Homeroom Teacher</Label>
              <div className="col-span-3">
                <Select value={createTeacherId} onValueChange={setCreateTeacherId} disabled={teachers.length === 0}>
                  <SelectTrigger>
                    <SelectValue placeholder={teachers.length === 0 ? "No teachers" : "Select a teacher"} />
                  </SelectTrigger>
                  <SelectContent>
                    {teachers.map((t) => (
                      <SelectItem key={t.id} value={t.id}>
                        {t.name} ({t.email})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <input type="hidden" name="teacherId" value={createTeacherId} />
              </div>
            </div>

            <DialogFooter>
              <Button type="button" variant="outline" onClick={() => setCreateOpen(false)} disabled={isWorking}>
                Cancel
              </Button>
              <Button type="submit" disabled={isWorking || teachers.length === 0 || !createTeacherId || !createGradeId}>
                Create
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      <Dialog
        open={Boolean(editItem)}
        onOpenChange={(open) => {
          if (isWorking) return
          if (!open) setEditItem(null)
        }}
      >
        <DialogContent className="sm:max-w-[560px]">
          <DialogHeader>
            <DialogTitle>Edit class</DialogTitle>
          </DialogHeader>
          {editItem ? (
            <form action={handleUpdate} className="space-y-4">
              <div className="grid grid-cols-4 items-center gap-4">
                <Label className="text-right">Grade</Label>
                <div className="col-span-3">
                  <Select value={editGradeId} onValueChange={setEditGradeId} disabled={managedGrades.length === 0}>
                    <SelectTrigger>
                      <SelectValue placeholder="Select a grade" />
                    </SelectTrigger>
                    <SelectContent>
                      {managedGrades.map((g) => (
                        <SelectItem key={g.id} value={g.id}>
                          {g.name} ({g.schoolName})
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <input type="hidden" name="gradeId" value={editGradeId} />
                  <input type="hidden" name="grade" value={selectedEditGrade?.name ?? ""} />
                  <input type="hidden" name="schoolId" value={selectedEditGrade?.schoolId ?? ""} />
                  <input type="hidden" name="schoolName" value={selectedEditGrade?.schoolName ?? ""} />
                </div>
              </div>

              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-name" className="text-right">
                  Name
                </Label>
                <Input id="edit-name" name="name" className="col-span-3" defaultValue={editItem.name} />
              </div>

              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-homeroom" className="text-right">
                  Homeroom
                </Label>
                <Input id="edit-homeroom" name="homeroom" className="col-span-3" defaultValue={editItem.homeroom ?? ""} />
              </div>

              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-room" className="text-right">
                  Room
                </Label>
                <Input id="edit-room" name="room" className="col-span-3" defaultValue={editItem.room ?? ""} />
              </div>

              <div className="grid grid-cols-4 items-center gap-4">
              <Label className="text-right">Homeroom Teacher</Label>
              <div className="col-span-3">
                <Select value={editTeacherId} onValueChange={setEditTeacherId} disabled={teachers.length === 0}>
                    <SelectTrigger>
                      <SelectValue placeholder={teachers.length === 0 ? "No teachers" : "Select a teacher"} />
                    </SelectTrigger>
                    <SelectContent>
                      {teachers.map((t) => (
                        <SelectItem key={t.id} value={t.id}>
                          {t.name} ({t.email})
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <input type="hidden" name="teacherId" value={editTeacherId} />
                </div>
              </div>

              <div className="space-y-3 rounded-md border p-4">
                <div className="text-sm font-medium">Subject Teachers</div>
                <div className="grid gap-3">
                  {DEFAULT_CLASS_SUBJECTS.map((subject) => {
                    const selected = editSubjectTeachers.find((x) => x.subject === subject)?.teacherId ?? null
                    return (
                      <div key={subject} className="grid grid-cols-4 items-center gap-4">
                        <Label className="text-right">{subject}</Label>
                        <div className="col-span-3">
                          <Select
                            value={selected ?? ""}
                            onValueChange={(v) => setSubjectTeacher(subject, v ? v : null)}
                            disabled={teachers.length === 0}
                          >
                            <SelectTrigger>
                              <SelectValue placeholder={teachers.length === 0 ? "No teachers" : "Select a teacher"} />
                            </SelectTrigger>
                            <SelectContent>
                              {teachers.map((t) => (
                                <SelectItem key={t.id} value={t.id}>
                                  {t.name} ({t.email})
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>
                      </div>
                    )
                  })}
                </div>
                <input type="hidden" name="subjectTeachers" value={JSON.stringify(editSubjectTeachers)} />
              </div>

              <DialogFooter>
                <Button type="button" variant="outline" onClick={() => setEditItem(null)} disabled={isWorking}>
                  Cancel
                </Button>
                <Button type="submit" disabled={isWorking || !editTeacherId}>
                  Save
                </Button>
              </DialogFooter>
            </form>
          ) : null}
        </DialogContent>
      </Dialog>

      <AlertDialog
        open={Boolean(deleteItem)}
        onOpenChange={(open) => {
          if (!open) setDeleteItem(null)
        }}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete class</AlertDialogTitle>
            <AlertDialogDescription>This will permanently delete {deleteItem?.name || "this class"}.</AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isWorking}>Cancel</AlertDialogCancel>
            <AlertDialogAction onClick={handleDelete} disabled={isWorking}>
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  )
}