"use client"

import { useState } from "react"
import { useTranslations } from "next-intl"
import { useRouter, usePathname, useSearchParams } from "next/navigation"
import { Printer, FileText } from "lucide-react"

import { Button } from "@/shared/components/ui/button"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/components/ui/table"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { cn } from "@/shared/lib/utils"

import { ATTENDANCE_STATUS_LABEL_KEYS } from "@/shared/constants/attendance-status"
import type { ClassAttendanceSummary } from "../types"

interface AttendanceReportPrintProps {
  summary: ClassAttendanceSummary | null
  classes: Array<{ id: string; name: string }>
  currentClassId: string
  currentClassName: string
  startDate: string
  endDate: string
  reportType: "weekly" | "monthly"
}

export function AttendanceReportPrint({
  summary,
  classes,
  currentClassId,
  currentClassName,
  startDate,
  endDate,
  reportType,
}: AttendanceReportPrintProps) {
  const t = useTranslations("attendance")
  const router = useRouter()
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const [isPrinting, setIsPrinting] = useState(false)

  const handleParamChange = (key: string, value: string) => {
    const params = new URLSearchParams(searchParams.toString())
    if (value) {
      params.set(key, value)
    } else {
      params.delete(key)
    }
    router.push(`${pathname}?${params.toString()}`)
  }

  const handlePrint = () => {
    setIsPrinting(true)
    // 使用 setTimeout 确保 UI 更新后再触发打印
    setTimeout(() => {
      window.print()
      setIsPrinting(false)
    }, 100)
  }

  return (
    <>
      {/* 控制面板（打印时隐藏） */}
      <Card className="print:hidden">
        <CardHeader>
          <CardTitle>{t("report.controls")}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 gap-4 md:grid-cols-4">
            <div className="grid gap-2">
              <Label htmlFor="report-class">{t("filters.class")}</Label>
              <Select value={currentClassId} onValueChange={(v) => handleParamChange("classId", v)}>
                <SelectTrigger id="report-class">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {classes.map((c) => (
                    <SelectItem key={c.id} value={c.id}>{c.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="grid gap-2">
              <Label htmlFor="report-type">{t("report.type")}</Label>
              <Select
                value={reportType}
                onValueChange={(v) => handleParamChange("reportType", v)}
              >
                <SelectTrigger id="report-type">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="weekly">{t("report.types.weekly")}</SelectItem>
                  <SelectItem value="monthly">{t("report.types.monthly")}</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="grid gap-2">
              <Label htmlFor="report-start">{t("report.startDate")}</Label>
              <Input
                id="report-start"
                type="date"
                value={startDate}
                onChange={(e) => handleParamChange("startDate", e.target.value)}
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="report-end">{t("report.endDate")}</Label>
              <Input
                id="report-end"
                type="date"
                value={endDate}
                onChange={(e) => handleParamChange("endDate", e.target.value)}
              />
            </div>
          </div>
          <div className="flex justify-end">
            <Button onClick={handlePrint} disabled={isPrinting || !summary} className="gap-2">
              <Printer className="h-4 w-4" aria-hidden="true" />
              {isPrinting ? t("report.printing") : t("report.print")}
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* 打印区域（屏幕上也可见，但样式针对打印优化） */}
      {!summary || summary.studentRecords.length === 0 ? (
        <Card className="print:hidden">
          <CardContent className="pt-6">
            <EmptyState
              title={t("report.noData")}
              description={t("report.noDataDescription")}
              icon={FileText}
              className="border-none shadow-none"
            />
          </CardContent>
        </Card>
      ) : (
        <div className="report-card space-y-6">
          {/* 报告头部 */}
          <div className="border-b pb-4">
            <h1 className="text-2xl font-bold">
              {currentClassName} - {t(`report.types.${reportType}`)}
            </h1>
            <p className="text-sm text-muted-foreground">
              {t("report.period")}: {startDate || summary.date} ~ {endDate || summary.date}
            </p>
            <p className="text-sm text-muted-foreground">
              {t("report.generatedAt")}: {new Date().toISOString().slice(0, 10)}
            </p>
          </div>

          {/* 统计汇总 */}
          <div>
            <h2 className="mb-3 text-lg font-semibold">{t("report.summary")}</h2>
            <div className="grid grid-cols-3 gap-3 text-sm sm:grid-cols-6">
              <div className="border rounded p-2">
                <div className="text-muted-foreground">{t("stats.totalRecords")}</div>
                <div className="text-lg font-bold">{summary.stats.total}</div>
              </div>
              <div className="border rounded p-2">
                <div className="text-muted-foreground">{t("stats.present")}</div>
                <div className="text-lg font-bold text-green-600">{summary.stats.present}</div>
              </div>
              <div className="border rounded p-2">
                <div className="text-muted-foreground">{t("stats.absent")}</div>
                <div className="text-lg font-bold text-red-600">{summary.stats.absent}</div>
              </div>
              <div className="border rounded p-2">
                <div className="text-muted-foreground">{t("stats.late")}</div>
                <div className="text-lg font-bold text-yellow-600">{summary.stats.late}</div>
              </div>
              <div className="border rounded p-2">
                <div className="text-muted-foreground">{t("stats.earlyLeave")}</div>
                <div className="text-lg font-bold text-blue-600">{summary.stats.earlyLeave}</div>
              </div>
              <div className="border rounded p-2">
                <div className="text-muted-foreground">{t("stats.attendanceRate")}</div>
                <div className="text-lg font-bold">{summary.stats.presentRate.toFixed(1)}%</div>
              </div>
            </div>
          </div>

          {/* 学生明细 */}
          <div>
            <h2 className="mb-3 text-lg font-semibold">{t("report.studentDetails")}</h2>
            <div className="rounded-md border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-12">#</TableHead>
                    <TableHead>{t("list.columns.student")}</TableHead>
                    <TableHead>{t("list.columns.date")}</TableHead>
                    <TableHead>{t("list.columns.status")}</TableHead>
                    <TableHead>{t("list.columns.reason")}</TableHead>
                    <TableHead>{t("list.columns.remark")}</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {summary.studentRecords.map((r, idx) => (
                    <TableRow key={r.id}>
                      <TableCell className="tabular-nums">{idx + 1}</TableCell>
                      <TableCell className="font-medium">{r.studentName}</TableCell>
                      <TableCell>{r.date}</TableCell>
                      <TableCell>
                        <span className={cn(
                          "inline-block rounded px-2 py-0.5 text-xs font-medium",
                          r.status === "present" && "bg-green-100 text-green-700",
                          r.status === "absent" && "bg-red-100 text-red-700",
                          r.status === "late" && "bg-yellow-100 text-yellow-700",
                          r.status === "early_leave" && "bg-blue-100 text-blue-700",
                          r.status === "excused" && "bg-purple-100 text-purple-700",
                          r.status === "school_activity" && "bg-cyan-100 text-cyan-700",
                        )}>
                          {t(ATTENDANCE_STATUS_LABEL_KEYS[r.status])}
                        </span>
                      </TableCell>
                      <TableCell>{r.reason ?? "-"}</TableCell>
                      <TableCell>{r.remark ?? "-"}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </div>

          {/* 家长签字单 */}
          <div className="border-t-2 border-dashed pt-6">
            <h2 className="mb-3 text-lg font-semibold">{t("report.parentSignature")}</h2>
            <div className="rounded border p-4">
              <p className="mb-4 text-sm">
                {t("report.parentSignatureNotice")}
              </p>
              <div className="grid grid-cols-2 gap-6">
                <div>
                  <div className="mb-1 text-sm text-muted-foreground">{t("report.parentName")}</div>
                  <div className="border-b border-dashed pb-1">&nbsp;</div>
                </div>
                <div>
                  <div className="mb-1 text-sm text-muted-foreground">{t("report.signature")}</div>
                  <div className="border-b border-dashed pb-1">&nbsp;</div>
                </div>
                <div>
                  <div className="mb-1 text-sm text-muted-foreground">{t("report.relationship")}</div>
                  <div className="border-b border-dashed pb-1">&nbsp;</div>
                </div>
                <div>
                  <div className="mb-1 text-sm text-muted-foreground">{t("report.signDate")}</div>
                  <div className="border-b border-dashed pb-1">&nbsp;</div>
                </div>
              </div>
              <div className="mt-4">
                <div className="mb-1 text-sm text-muted-foreground">{t("report.parentComment")}</div>
                <div className="border border-dashed rounded h-20">&nbsp;</div>
              </div>
            </div>
          </div>

          {/* 报告页脚 */}
          <div className="border-t pt-2 text-xs text-muted-foreground">
            <p>{t("report.footer")}</p>
          </div>
        </div>
      )}
    </>
  )
}
