"use client"

import { useMemo } from "react"
import { toast } from "sonner"
import { useRouter } from "next/navigation"
import { useTranslations } from "next-intl"

import type { AdminClassListItem, TeacherOption } from "../types"
import { createAdminClassAction, deleteAdminClassAction, updateAdminClassAction } from "../actions"
import { useClassData } from "../hooks/use-class-data"
import { useClassFilters } from "../hooks/use-class-filters"
import type { ClassFormGrade } from "./class-form-utils"
import { ClassDeleteDialog } from "./class-delete-dialog"
import { ClassFormDialog } from "./class-form-dialog"
import { ClassListTable } from "./class-list-table"
import { ClassListToolbar } from "./class-list-toolbar"

export function AdminClassesClient({
  classes,
  teachers,
  schools,
  grades,
}: {
  classes: AdminClassListItem[]
  teachers: TeacherOption[]
  schools: { id: string; name: string }[]
  grades: { id: string; name: string; school: { id: string; name: string } }[]
}) {
  const t = useTranslations("classes")
  const router = useRouter()
  const defaultTeacherId = useMemo(() => teachers[0]?.id ?? "", [teachers])
  const defaultSchoolId = useMemo(() => schools[0]?.id ?? "", [schools])
  const data = useClassData({ defaultTeacherId, defaultSchoolId, defaultGradeId: "" })

  const formGrades: ClassFormGrade[] = useMemo(
    () => grades.map((g) => ({ id: g.id, name: g.name, schoolId: g.school.id, schoolName: g.school.name })),
    [grades],
  )
  const { createGrades, editGrades } = useClassFilters(formGrades, data.createSchoolId, data.editSchoolId)

  const handleCreate = async (formData: FormData): Promise<void> => {
    data.setIsWorking(true)
    try {
      const res = await createAdminClassAction(undefined, formData)
      if (res.success) {
        toast.success(res.message)
        data.setCreateOpen(false)
        router.refresh()
      } else {
        toast.error(res.message || t("list.failedCreate"))
      }
    } catch {
      toast.error(t("list.failedCreate"))
    } finally {
      data.setIsWorking(false)
    }
  }

  const handleUpdate = async (formData: FormData): Promise<void> => {
    if (!data.editItem) return
    data.setIsWorking(true)
    try {
      const res = await updateAdminClassAction(data.editItem.id, undefined, formData)
      if (res.success) {
        toast.success(res.message)
        data.setEditItem(null)
        router.refresh()
      } else {
        toast.error(res.message || t("list.failedUpdate"))
      }
    } catch {
      toast.error(t("list.failedUpdate"))
    } finally {
      data.setIsWorking(false)
    }
  }

  const handleDelete = async (): Promise<void> => {
    if (!data.deleteItem) return
    data.setIsWorking(true)
    try {
      const res = await deleteAdminClassAction(data.deleteItem.id)
      if (res.success) {
        toast.success(res.message)
        data.setDeleteItem(null)
        router.refresh()
      } else {
        toast.error(res.message || t("list.failedDelete"))
      }
    } catch {
      toast.error(t("list.failedDelete"))
    } finally {
      data.setIsWorking(false)
    }
  }

  return (
    <>
      <ClassListToolbar count={classes.length} onNew={() => data.setCreateOpen(true)} isWorking={data.isWorking} />

      <ClassListTable
        classes={classes}
        onEdit={data.setEditItem}
        onDelete={data.setDeleteItem}
        isWorking={data.isWorking}
      />

      <ClassFormDialog
        open={data.createOpen}
        onOpenChange={data.setCreateOpen}
        mode="create"
        teachers={teachers}
        schools={schools}
        grades={createGrades}
        onSubmit={handleCreate}
        isWorking={data.isWorking}
        teacherId={data.createTeacherId}
        schoolId={data.createSchoolId}
        gradeId={data.createGradeId}
        onTeacherIdChange={data.setCreateTeacherId}
        onSchoolIdChange={data.setCreateSchoolId}
        onGradeIdChange={data.setCreateGradeId}
      />

      <ClassFormDialog
        open={Boolean(data.editItem)}
        onOpenChange={(o) => {
          if (!o) data.setEditItem(null)
        }}
        mode="edit"
        editItem={data.editItem}
        teachers={teachers}
        schools={schools}
        grades={editGrades}
        onSubmit={handleUpdate}
        isWorking={data.isWorking}
        teacherId={data.editTeacherId}
        schoolId={data.editSchoolId}
        gradeId={data.editGradeId}
        subjectTeachers={data.editSubjectTeachers}
        onTeacherIdChange={data.setEditTeacherId}
        onSchoolIdChange={data.setEditSchoolId}
        onGradeIdChange={data.setEditGradeId}
        onSubjectTeacherChange={data.setSubjectTeacher}
      />

      <ClassDeleteDialog
        open={Boolean(data.deleteItem)}
        onOpenChange={(o) => {
          if (!o) data.setDeleteItem(null)
        }}
        item={data.deleteItem}
        onConfirm={handleDelete}
        isWorking={data.isWorking}
      />
    </>
  )
}
