"use client"

import { useCallback, useMemo, useRef, useState } from "react"
import { CalendarDays, ChevronDown } from "lucide-react"
import { useRouter, useSearchParams } from "next/navigation"
import { useOutsideClick } from "@/components/hooks/useOutsideClick"

export function YearSelector({ selectedYear }: { selectedYear: number }) {
  const router = useRouter()
  const searchParams = useSearchParams()
  const [isOpen, setIsOpen] = useState(false)
  const dropdownRef = useOutsideClick(() => setIsOpen(false))

  const currentYear = new Date().getFullYear()
  const availableYears = useMemo(() => {
    const baseYear = 2025
    return Array.from(
      { length: Math.max(1, currentYear - baseYear + 1) },
      (_, i) => baseYear + i,
    ).filter(year => year <= currentYear)
  }, [currentYear])

  const handleYearChange = useCallback(
    (year: number) => {
      setIsOpen(false)
      const params = new URLSearchParams(searchParams.toString())
      if (year === currentYear) {
        params.delete("year")
      } else {
        params.set("year", String(year))
      }
      const query = params.toString()
      router.push(query ? `?${query}` : "/dashboard", { scroll: false })
    },
    [router, searchParams, currentYear],
  )

  return (
    <div className="relative" ref={dropdownRef}>
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center gap-1 px-2 py-1 text-xs bg-background border border-border rounded-md hover:border-primary/50 transition-colors"
        disabled={availableYears.length <= 1}
      >
        <CalendarDays size={12} className="text-muted-foreground" />
        <span>{selectedYear}</span>
        {availableYears.length > 1 && (
          <ChevronDown
            size={12}
            className={`transition-transform text-muted-foreground ${isOpen ? "rotate-180" : ""}`}
          />
        )}
      </button>

      {isOpen && availableYears.length > 1 && (
        <div className="absolute right-0 z-10 mt-1 w-32 bg-card rounded-md shadow-lg overflow-hidden border border-border animate-in fade-in-50 slide-in-from-top-5">
          <div className="py-1">
            {availableYears.map(year => (
              <button
                key={year}
                onClick={() => handleYearChange(year)}
                className={`w-full px-3 py-1.5 text-left hover:bg-muted flex items-center ${selectedYear === year ? "bg-primary/10 text-primary font-medium" : ""}`}
              >
                <span className="w-4 h-4 mr-1.5 flex items-center justify-center">
                  {selectedYear === year && (
                    <span className="w-1.5 h-1.5 rounded-full bg-primary"></span>
                  )}
                </span>
                {year}
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}
