"use client"

import { usePathname, useRouter, useSearchParams } from "next/navigation"

import { useT } from "@/components/locale-provider"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"

/**
 * Which year's calendar is on screen.
 *
 * Every year that was ever loaded stays. Replacing on import only touches the
 * years a file actually mentions, so loading 2027 leaves 2026 where it is, and
 * that is deliberate: a report about last year has to be able to say which days
 * the factory was shut when the work was due, and a calendar that only knows
 * the current year cannot answer it.
 *
 * A select and not a row of buttons, unlike the day/week/month switch on My
 * Tasks. That one has three choices for ever; this one gains a year every
 * January, and a row that is fine at two is a wrapped mess at twelve.
 *
 * The year goes in the url so a view of 2026 is a link somebody can send, which
 * is the same reason the task views live there.
 */
export function YearSelect({
  years,
  current,
}: {
  years: { year: number; days: number }[]
  current: number
}) {
  const t = useT()
  const router = useRouter()
  const pathname = usePathname()
  const params = useSearchParams()

  return (
    <Select
      value={String(current)}
      onValueChange={(value) => {
        if (!value) return
        const next = new URLSearchParams(params)
        next.set("year", String(value))
        router.push(`${pathname}?${next}`)
      }}
    >
      <SelectTrigger className="w-40" aria-label={t("holidays.whichYear")}>
        <SelectValue />
      </SelectTrigger>
      <SelectContent>
        {years.map((y) => (
          <SelectItem key={y.year} value={String(y.year)}>
            {/*
              The count travels with the year. Somebody looking for the year a
              calendar was never loaded for should see that it holds no days
              without having to select it first.
            */}
            {y.year} · {t("holidays.days", { count: y.days })}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  )
}
