"use client"

import { ChevronDown } from "lucide-react"
import { cn } from "@/lib/utils"
import { type Locale, locales } from "@/lib/date-utils"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { Button } from "@/components/ui/button"

interface MonthYearSelectorProps {
  month: number
  year: number
  onMonthChange: (month: number) => void
  onYearChange: (year: number) => void
  locale: Locale
  minYear?: number
  maxYear?: number
}

export function MonthYearSelector({
  month,
  year,
  onMonthChange,
  onYearChange,
  locale,
  minYear = 1900,
  maxYear = 2100,
}: MonthYearSelectorProps) {
  const config = locales[locale]
  const isRTL = config.direction === "rtl"

  const years = Array.from({ length: maxYear - minYear + 1 }, (_, i) => minYear + i)

  return (
    <div className={cn("flex items-center gap-1", isRTL && "flex-row-reverse")}>
      {/* Month selector */}
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button
            variant="ghost"
            size="sm"
            className="h-8 gap-1 font-semibold"
            aria-label={`Select month, currently ${config.months[month]}`}
          >
            {config.months[month]}
            <ChevronDown className="h-4 w-4" />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="start" className="max-h-48 overflow-y-auto">
          {config.months.map((monthName, index) => (
            <DropdownMenuItem
              key={index}
              onClick={() => onMonthChange(index)}
              className={cn(index === month && "bg-accent font-medium")}
            >
              {monthName}
            </DropdownMenuItem>
          ))}
        </DropdownMenuContent>
      </DropdownMenu>

      {/* Year selector */}
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button
            variant="ghost"
            size="sm"
            className="h-8 gap-1 font-semibold"
            aria-label={`Select year, currently ${year}`}
          >
            {year}
            <ChevronDown className="h-4 w-4" />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="start" className="max-h-64 overflow-y-auto">
          {years.map((y) => (
            <DropdownMenuItem
              key={y}
              onClick={() => onYearChange(y)}
              className={cn(y === year && "bg-accent font-medium")}
            >
              {y}
            </DropdownMenuItem>
          ))}
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  )
}
