"use client"

import { useState } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { useCallback } from "react"
import { toast } from "sonner"
import { FileText, Trash2, Send } from "lucide-react"

import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { Label } from "@/shared/components/ui/label"
import { EmptyState } from "@/shared/components/ui/empty-state"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select"
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 { formatDate } from "@/shared/lib/utils"
import { usePermission } from "@/shared/hooks"
import { Permissions } from "@/shared/types/permissions"
import { publishReportAction, deleteReportAction } from "../actions"
import type { DiagnosticReportWithDetails } from "../types"

const typeLabels: Record<string, string> = {
  individual: "Individual",
  class: "Class",
  grade: "Grade",
}

const statusColors: Record<string, "default" | "secondary" | "destructive" | "outline"> = {
  draft: "secondary",
  published: "default",
  archived: "outline",
}

interface ReportListProps {
  reports: DiagnosticReportWithDetails[]
}

export function ReportList({ reports }: ReportListProps) {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { hasPermission } = usePermission()
  const canManage = hasPermission(Permissions.DIAGNOSTIC_MANAGE)

  const [deleteId, setDeleteId] = useState<string | null>(null)
  const [publishId, setPublishId] = useState<string | null>(null)
  const [isBusy, setIsBusy] = useState(false)

  const updateParam = useCallback(
    (key: string, value: string) => {
      const params = new URLSearchParams(searchParams.toString())
      if (value && value !== "all") {
        params.set(key, value)
      } else {
        params.delete(key)
      }
      router.push(`?${params.toString()}`)
    },
    [router, searchParams]
  )

  const handlePublish = async () => {
    if (!publishId) return
    setIsBusy(true)
    const formData = new FormData()
    formData.set("id", publishId)
    const result = await publishReportAction(null, formData)
    setIsBusy(false)
    if (result.success) {
      toast.success(result.message)
      setPublishId(null)
      router.refresh()
    } else {
      toast.error(result.message || "Failed to publish")
    }
  }

  const handleDelete = async () => {
    if (!deleteId) return
    setIsBusy(true)
    const formData = new FormData()
    formData.set("id", deleteId)
    const result = await deleteReportAction(null, formData)
    setIsBusy(false)
    if (result.success) {
      toast.success(result.message)
      setDeleteId(null)
      router.refresh()
    } else {
      toast.error(result.message || "Failed to delete")
    }
  }

  const reportType = searchParams.get("reportType") ?? "all"
  const status = searchParams.get("status") ?? "all"

  return (
    <div className="space-y-4">
      {/* 过滤器 */}
      <div className="grid grid-cols-1 gap-4 rounded-lg border bg-card p-4 md:grid-cols-2">
        <div className="grid gap-2">
          <Label className="text-xs">Report Type</Label>
          <Select value={reportType} onValueChange={(v) => updateParam("reportType", v)}>
            <SelectTrigger className="h-9">
              <SelectValue placeholder="All types" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All types</SelectItem>
              <SelectItem value="individual">Individual</SelectItem>
              <SelectItem value="class">Class</SelectItem>
              <SelectItem value="grade">Grade</SelectItem>
            </SelectContent>
          </Select>
        </div>
        <div className="grid gap-2">
          <Label className="text-xs">Status</Label>
          <Select value={status} onValueChange={(v) => updateParam("status", v)}>
            <SelectTrigger className="h-9">
              <SelectValue placeholder="All statuses" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All statuses</SelectItem>
              <SelectItem value="draft">Draft</SelectItem>
              <SelectItem value="published">Published</SelectItem>
              <SelectItem value="archived">Archived</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

      {reports.length === 0 ? (
        <EmptyState
          title="No diagnostic reports"
          description="Generate diagnostic reports to see them here."
          icon={FileText}
          className="border-none shadow-none"
        />
      ) : (
        <div className="rounded-md border bg-card">
          <Table>
            <caption className="sr-only">学情诊断报告列表</caption>
            <TableHeader>
              <TableRow>
                <TableHead>Type</TableHead>
                <TableHead>Student / Target</TableHead>
                <TableHead>Period</TableHead>
                <TableHead className="text-right">Score</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Generated By</TableHead>
                <TableHead>Date</TableHead>
                {canManage ? <TableHead className="w-24">Actions</TableHead> : null}
              </TableRow>
            </TableHeader>
            <TableBody>
              {reports.map((r) => (
                <TableRow key={r.id}>
                  <TableCell>
                    <Badge variant="outline">{typeLabels[r.reportType] ?? r.reportType}</Badge>
                  </TableCell>
                  <TableCell className="font-medium">{r.studentName ?? (r.reportType === "class" ? "（班级报告）" : r.reportType === "grade" ? "（年级报告）" : "-")}</TableCell>
                  <TableCell>{r.period ?? "-"}</TableCell>
                  <TableCell className="text-right font-mono">
                    {r.overallScore !== null ? `${r.overallScore.toFixed(1)}%` : "-"}
                  </TableCell>
                  <TableCell>
                    <Badge variant={statusColors[r.status] ?? "secondary"}>{r.status}</Badge>
                  </TableCell>
                  <TableCell className="text-muted-foreground">{r.generatedByName ?? "-"}</TableCell>
                  <TableCell className="text-muted-foreground">{formatDate(r.createdAt)}</TableCell>
                  {canManage ? (
                    <TableCell>
                      <div className="flex gap-1">
                        {r.status === "draft" ? (
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-8 w-8 text-green-600"
                            onClick={() => setPublishId(r.id)}
                            title="Publish"
                            aria-label={`发布报告 ${r.studentName}`}
                          >
                            <Send className="h-4 w-4" />
                          </Button>
                        ) : null}
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8 text-destructive"
                          onClick={() => setDeleteId(r.id)}
                          title="Delete"
                          aria-label={`删除报告 ${r.studentName}`}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  ) : null}
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      )}

      {/* 发布确认 */}
      <Dialog open={publishId !== null} onOpenChange={(open) => !open && setPublishId(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Publish Report</DialogTitle>
            <DialogDescription>
              Once published, the report will be visible to students. Continue?
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setPublishId(null)} disabled={isBusy}>
              Cancel
            </Button>
            <Button onClick={handlePublish} disabled={isBusy}>
              {isBusy ? "Publishing..." : "Publish"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除确认 */}
      <Dialog open={deleteId !== null} onOpenChange={(open) => !open && setDeleteId(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Delete Report</DialogTitle>
            <DialogDescription>
              Are you sure you want to delete this diagnostic report? This action cannot be undone.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeleteId(null)} disabled={isBusy}>
              Cancel
            </Button>
            <Button variant="destructive" onClick={handleDelete} disabled={isBusy}>
              {isBusy ? "Deleting..." : "Delete"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
