"use client"

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

import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/components/ui/table"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/shared/components/ui/dialog"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { formatDate } from "@/shared/lib/utils"
import { resolveActionError } from "@/shared/lib/resolve-action-error"
import { usePermission } from "@/shared/hooks/use-permission"
import { Permissions } from "@/shared/types/permissions"

import { deleteAttendanceAction } from "../actions"
import {
  ATTENDANCE_STATUS_BADGE_VARIANTS,
  ATTENDANCE_STATUS_LABEL_KEYS,
} from "../constants"
import type { AttendanceListItem, AttendancePeriod } from "../types"

/** L-6：节次 i18n key 映射（与 attendance-sheet 一致）。 */
const ATTENDANCE_PERIOD_LABEL_KEYS: Record<AttendancePeriod, string> = {
  full_day: "period.full_day",
  morning_reading: "period.morning_reading",
  morning: "period.morning",
  afternoon: "period.afternoon",
  evening: "period.evening",
}

export function AttendanceRecordList({ records }: { records: AttendanceListItem[] }) {
  const router = useRouter()
  const t = useTranslations("attendance")
  const { hasPermission } = usePermission()
  const canManage = hasPermission(Permissions.ATTENDANCE_MANAGE)
  const [deleteId, setDeleteId] = useState<string | null>(null)
  const [isDeleting, setIsDeleting] = useState(false)

  const handleDelete = async () => {
    if (!deleteId) return
    setIsDeleting(true)
    try {
      const result = await deleteAttendanceAction(deleteId)
      if (result.success) {
        toast.success(result.message || t("sheet.deleted"))
        setDeleteId(null)
        router.refresh()
      } else {
        toast.error(resolveActionError(result, t, t("errors.unexpected")))
      }
    } catch {
      toast.error(t("errors.unexpected"))
    } finally {
      setIsDeleting(false)
    }
  }

  if (records.length === 0) {
    return (
      <EmptyState
        icon={Inbox}
        title={t("list.empty")}
        description={t("list.emptyDescription")}
        className="h-auto border-none shadow-none"
      />
    )
  }

  return (
    <>
      <div className="rounded-md border bg-card">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>{t("list.columns.student")}</TableHead>
              <TableHead>{t("list.columns.class")}</TableHead>
              <TableHead>{t("list.columns.date")}</TableHead>
              {/* L-6：节次列，null 视为 full_day */}
              <TableHead>{t("period.label")}</TableHead>
              <TableHead>{t("list.columns.status")}</TableHead>
              <TableHead>{t("list.columns.reason")}</TableHead>
              <TableHead>{t("list.columns.remark")}</TableHead>
              <TableHead>{t("list.columns.recorder")}</TableHead>
              <TableHead>{t("list.columns.createdAt")}</TableHead>
              <TableHead className="w-12"></TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {records.map((r) => {
              // L-6：节次 null 视为 full_day，对外统一展示
              const periodValue: AttendancePeriod = r.period ?? "full_day"
              return (
              <TableRow key={r.id}>
                <TableCell className="font-medium">{r.studentName}</TableCell>
                <TableCell>{r.className}</TableCell>
                <TableCell>{r.date}</TableCell>
                <TableCell className="text-muted-foreground">
                  {t(ATTENDANCE_PERIOD_LABEL_KEYS[periodValue])}
                </TableCell>
                <TableCell>
                  <Badge variant={ATTENDANCE_STATUS_BADGE_VARIANTS[r.status]} className="capitalize">
                    {t(ATTENDANCE_STATUS_LABEL_KEYS[r.status])}
                  </Badge>
                </TableCell>
                <TableCell className="max-w-[200px] truncate text-muted-foreground">
                  {r.reason ?? "-"}
                </TableCell>
                <TableCell className="max-w-[200px] truncate text-muted-foreground">
                  {r.remark ?? "-"}
                </TableCell>
                <TableCell className="text-muted-foreground">{r.recorderName}</TableCell>
                <TableCell className="text-muted-foreground">{formatDate(r.createdAt)}</TableCell>
                <TableCell>
                  {canManage ? (
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-8 w-8 text-destructive"
                      onClick={() => setDeleteId(r.id)}
                      aria-label={t("actions.delete")}
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  ) : null}
                </TableCell>
              </TableRow>
              )
            })}
          </TableBody>
        </Table>
      </div>

      <Dialog open={deleteId !== null} onOpenChange={(open) => !open && setDeleteId(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{t("sheet.confirmDelete")}</DialogTitle>
            <DialogDescription>
              {t("sheet.confirmDelete")}
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeleteId(null)} disabled={isDeleting}>
              {t("actions.cancel")}
            </Button>
            <Button variant="destructive" onClick={handleDelete} disabled={isDeleting}>
              {isDeleting ? t("actions.delete") + "..." : t("actions.delete")}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  )
}
