"use client"

import { useRouter, useSearchParams, usePathname } from "next/navigation"
import { useCallback } from "react"
import { CalendarDays, CalendarRange, CalendarClock } from "lucide-react"

import { Button } from "@/shared/components/ui/button"
import { cn } from "@/shared/lib/utils"
import { useTranslations } from "next-intl"

/** 时间范围选项 */
export type TimeRange = "today" | "week" | "month"

const RANGE_OPTIONS: { value: TimeRange; icon: typeof CalendarDays }[] = [
  { value: "today", icon: CalendarDays },
  { value: "week", icon: CalendarRange },
  { value: "month", icon: CalendarClock },
]

/**
 * 仪表盘时间范围筛选器（L2）。
 *
 * 通过 URL search param `?range=` 持久化选择，
 * 切换时触发页面重新获取数据。
 * 默认值为 "today"。
 */
export function DashboardTimeRangeFilter({ className }: { className?: string }) {
  const t = useTranslations("dashboard.timeRange")
  const router = useRouter()
  const pathname = usePathname()
  const searchParams = useSearchParams()

  const currentRange = (searchParams.get("range") as TimeRange | null) ?? "today"

  const handleRangeChange = useCallback(
    (range: TimeRange) => {
      const params = new URLSearchParams(searchParams.toString())
      params.set("range", range)
      router.push(`${pathname}?${params.toString()}`, { scroll: false })
    },
    [router, pathname, searchParams],
  )

  return (
    <div className={cn("inline-flex items-center gap-1 rounded-lg border bg-muted/40 p-1", className)} role="radiogroup" aria-label={t("label")}>
      {RANGE_OPTIONS.map(({ value, icon: Icon }) => (
        <Button
          key={value}
          variant={currentRange === value ? "default" : "ghost"}
          size="sm"
          className="gap-1.5"
          onClick={() => handleRangeChange(value)}
          role="radio"
          aria-checked={currentRange === value}
        >
          <Icon className="h-3.5 w-3.5" aria-hidden />
          {t(value)}
        </Button>
      ))}
    </div>
  )
}
