"use client"

import { useMemo } from "react"
import { useTranslations } from "next-intl"
import { useRouter, usePathname, useSearchParams } from "next/navigation"
import { TrendingUp } from "lucide-react"

import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Button } from "@/shared/components/ui/button"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { TrendLineChart, type TrendLineSeries } from "@/shared/components/charts/trend-line-chart"
import { cn } from "@/shared/lib/utils"

import { formatBucketLabel, type TrendGranularity } from "../trend-compute"
import type { AttendanceTrendSummary } from "../types"

interface AttendanceTrendChartProps {
  summary: AttendanceTrendSummary | null
  /** 当前粒度（从 searchParams 传入）。 */
  granularity: TrendGranularity
}

const GRANULARITIES: TrendGranularity[] = ["daily", "weekly", "monthly"]

export function AttendanceTrendChart({
  summary,
  granularity,
}: AttendanceTrendChartProps) {
  const t = useTranslations("attendance.trend")
  const router = useRouter()
  const pathname = usePathname()
  const searchParams = useSearchParams()

  const chartData = useMemo(() => {
    if (!summary) return []
    return summary.points.map((p) => ({
      title: formatBucketLabel(p.date, summary.granularity),
      fullTitle: formatBucketLabel(p.date, summary.granularity),
      presentRate: p.presentRate,
      lateRate: p.lateRate,
      absentRate: p.absentRate,
      total: p.total,
    }))
  }, [summary])

  const series: TrendLineSeries[] = [
    { dataKey: "presentRate", name: t("series.presentRate"), color: "hsl(var(--chart-1))" },
    { dataKey: "lateRate", name: t("series.lateRate"), color: "hsl(var(--chart-2))" },
    { dataKey: "absentRate", name: t("series.absentRate"), color: "hsl(var(--chart-3))" },
  ]

  const handleGranularityChange = (g: TrendGranularity) => {
    const params = new URLSearchParams(searchParams.toString())
    params.set("granularity", g)
    router.push(`${pathname}?${params.toString()}`)
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center justify-between gap-2">
          <span className="flex items-center gap-2">
            <TrendingUp className="h-5 w-5" />
            {t("title")}
          </span>
          <div className="flex items-center gap-1">
            {GRANULARITIES.map((g) => (
              <Button
                key={g}
                type="button"
                variant={granularity === g ? "default" : "outline"}
                size="sm"
                className={cn("h-7 px-2 text-xs")}
                onClick={() => handleGranularityChange(g)}
              >
                {t(`granularity.${g}`)}
              </Button>
            ))}
          </div>
        </CardTitle>
        <p className="text-sm text-muted-foreground">
          {t("description", {
            start: summary ? formatBucketLabel(summary.startDate, summary.granularity) : "-",
            end: summary ? formatBucketLabel(summary.endDate, summary.granularity) : "-",
          })}
        </p>
      </CardHeader>
      <CardContent>
        {!summary || summary.points.length === 0 ? (
          <EmptyState
            title={t("noData")}
            description={t("noDataDescription")}
            icon={TrendingUp}
            className="border-none shadow-none"
          />
        ) : (
          <TrendLineChart
            data={chartData}
            series={series}
            xKey="title"
            yDomain={[0, 100]}
            heightClassName="h-[320px]"
          />
        )}
      </CardContent>
    </Card>
  )
}
