import React, { useState } from "react";
import { Button } from "@/shared/common/ui/button";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/shared/common/ui/popover";
import { ChevronLeft, ChevronRight, Calendar } from "lucide-react";
import { cn } from "@/shared/lib/utils";
import HabeshaCalendarUtils from "@/shared/utils/habeshaCalendar";

export interface YearPickerProps {
  value?: number;
  onChange?: (year: number) => void;
  placeholder?: string;
  disabled?: boolean;
  className?: string;
  calendarType?: "gregorian" | "habesha";
  language?: "am" | "en";
  minYear?: number;
  maxYear?: number;
}

export const YearPicker: React.FC<YearPickerProps> = ({
  value,
  onChange,
  placeholder = "Select year",
  disabled = false,
  className,
  calendarType = "habesha",
  language = "am",
  minYear,
  maxYear,
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const [viewYear, setViewYear] = useState(() => {
    if (value) return value;
    return calendarType === "habesha"
      ? HabeshaCalendarUtils.getCurrentHabeshaDate().year
      : new Date().getFullYear();
  });

  // Calculate year range
  const currentYear =
    calendarType === "habesha"
      ? HabeshaCalendarUtils.getCurrentHabeshaDate().year
      : new Date().getFullYear();

  const defaultMinYear = currentYear - 50;
  const defaultMaxYear = currentYear + 10;

  const yearMin = minYear ?? defaultMinYear;
  const yearMax = maxYear ?? defaultMaxYear;

  // Generate years for the current view (show 12 years at a time)
  const generateYearGrid = (centerYear: number) => {
    const startYear = Math.floor(centerYear / 12) * 12;
    return Array.from({ length: 12 }, (_, i) => startYear + i);
  };

  const yearGrid = generateYearGrid(viewYear);
  const gridStartYear = yearGrid[0];
  const gridEndYear = yearGrid[yearGrid.length - 1];

  const handleYearSelect = (year: number) => {
    if (year >= yearMin && year <= yearMax) {
      onChange?.(year);
      setIsOpen(false);
    }
  };

  const handlePrevious = () => {
    setViewYear((prev) => Math.max(prev - 12, yearMin));
  };

  const handleNext = () => {
    setViewYear((prev) => Math.min(prev + 12, yearMax));
  };

  const displayValue = value ? value.toString() : "";
  const calendarLabel =
    calendarType === "habesha"
      ? language === "am"
        ? "የሀበሻ ዘመን አቆጣጠር"
        : "Habesha Calendar"
      : language === "am"
      ? "የግሪጎሪያን ዘመን አቆጣጠር"
      : "Gregorian Calendar";

  return (
    <Popover open={isOpen} onOpenChange={setIsOpen}>
      <PopoverTrigger asChild>
        <Button
          variant="outline"
          className={cn(
            "w-full justify-start text-left font-normal",
            !value && "text-muted-foreground",
            className
          )}
          disabled={disabled}
        >
          <Calendar className="mr-2 h-4 w-4" />
          {displayValue || placeholder}
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-80 p-4" align="start">
        <div className="space-y-4">
          {/* Header */}
          <div className="flex items-center justify-between">
            <div>
              <h4 className="font-medium">
                {language === "am" ? "ዓመት ይምረጡ" : "Select Year"}
              </h4>
              <p className="text-xs text-muted-foreground">{calendarLabel}</p>
            </div>
          </div>

          {/* Navigation */}
          <div className="flex items-center justify-between">
            <Button
              variant="outline"
              size="sm"
              onClick={handlePrevious}
              disabled={gridStartYear <= yearMin}
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>

            <span className="text-sm font-medium">
              {gridStartYear} - {gridEndYear}
            </span>

            <Button
              variant="outline"
              size="sm"
              onClick={handleNext}
              disabled={gridEndYear >= yearMax}
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>

          {/* Year Grid */}
          <div className="grid grid-cols-3 gap-2">
            {yearGrid.map((year) => {
              const isSelected = year === value;
              const isDisabled = year < yearMin || year > yearMax;
              const isCurrent = year === currentYear;

              return (
                <Button
                  key={year}
                  variant={isSelected ? "default" : "outline"}
                  size="sm"
                  className={cn(
                    "h-10 text-sm",
                    isSelected && "bg-primary text-primary-foreground",
                    isCurrent && !isSelected && "border-primary text-primary",
                    isDisabled && "opacity-50 cursor-not-allowed"
                  )}
                  onClick={() => handleYearSelect(year)}
                  disabled={isDisabled}
                >
                  {year}
                </Button>
              );
            })}
          </div>

          {/* Quick Navigation */}
          <div className="flex gap-2">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => {
                setViewYear(currentYear);
                handleYearSelect(currentYear);
              }}
              className="flex-1 text-xs"
            >
              {language === "am" ? "የአሁኑ ዓመት" : "Current Year"}
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setIsOpen(false)}
              className="flex-1 text-xs"
            >
              {language === "am" ? "ሰርዝ" : "Cancel"}
            </Button>
          </div>
        </div>
      </PopoverContent>
    </Popover>
  );
};

export default YearPicker;
