import React, { useState, useEffect } from "react";
import { Button } from "@/shared/common/ui/button";
import { Label } from "@/shared/common/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/shared/common/ui/popover";
import { CalendarIcon } from "lucide-react";
import { cn } from "@/shared/lib/utils";
import HabeshaCalendarUtils, {
  HabeshaDate,
} from "@/shared/utils/habeshaCalendar";

export interface HabeshaDatePickerProps {
  value?: Date;
  onChange?: (date: Date) => void;
  placeholder?: string;
  disabled?: boolean;
  className?: string;
  language?: "am" | "en";
}

export const HabeshaDatePicker: React.FC<HabeshaDatePickerProps> = ({
  value,
  onChange,
  placeholder = "Select date",
  disabled = false,
  className,
  language = "am",
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const [selectedYear, setSelectedYear] = useState<string>("");
  const [selectedMonth, setSelectedMonth] = useState<string>("");
  const [selectedDay, setSelectedDay] = useState<string>("");
  const [displayText, setDisplayText] = useState<string>("");

  // Initialize with current date or provided value
  useEffect(() => {
    if (value && value instanceof Date && !isNaN(value.getTime())) {
      const habeshaDate = HabeshaCalendarUtils.gregorianToHabesha(value);
      setSelectedYear(habeshaDate.year.toString());
      setSelectedMonth(habeshaDate.month.toString());
      setSelectedDay(habeshaDate.day.toString());
    } else {
      const current = HabeshaCalendarUtils.getCurrentHabeshaDate();
      setSelectedYear(current.year.toString());
      setSelectedMonth(current.month.toString());
      setSelectedDay("");
    }
  }, [value]);

  // Update display text when language or value changes
  useEffect(() => {
    if (value && value instanceof Date && !isNaN(value.getTime())) {
      setDisplayText(HabeshaCalendarUtils.formatForDisplay(value, language));
    } else {
      setDisplayText("");
    }
  }, [value, language]);

  const yearOptions = HabeshaCalendarUtils.generateHabeshaYearOptions(10, 5);
  const monthOptions = React.useMemo(
    () => HabeshaCalendarUtils.getMonthOptions(language),
    [language]
  );

  // Generate day options based on selected month and year
  const getDayOptions = () => {
    if (!selectedYear || !selectedMonth) return [];

    const year = parseInt(selectedYear);
    const month = parseInt(selectedMonth);
    const daysInMonth = HabeshaCalendarUtils.getDaysInHabeshaMonth(year, month);

    return Array.from({ length: daysInMonth }, (_, i) => ({
      label: (i + 1).toString(),
      value: (i + 1).toString(),
    }));
  };

  const handleDateSelect = () => {
    if (selectedYear && selectedMonth && selectedDay) {
      const year = parseInt(selectedYear);
      const month = parseInt(selectedMonth);
      const day = parseInt(selectedDay);

      try {
        const gregorianDate = HabeshaCalendarUtils.habeshaToGregorian(
          year,
          month,
          day
        );
        onChange?.(gregorianDate);
        setIsOpen(false);
      } catch (error) {
        console.error("Invalid Habesha date:", error);
      }
    }
  };

  const handleClear = () => {
    setSelectedYear("");
    setSelectedMonth("");
    setSelectedDay("");
    onChange?.(new Date()); // Reset to current date
  };

  const displayValue = displayText;

  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}
        >
          <CalendarIcon className="mr-2 h-4 w-4" />
          {displayValue || placeholder}
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-auto p-4" align="start">
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <h4 className="font-medium">
              {language === "am" ? "ቀን ይምረጡ" : "Select Date"}
            </h4>
            <Button
              variant="ghost"
              size="sm"
              onClick={handleClear}
              className="text-xs"
            >
              {language === "am" ? "አጽዳ" : "Clear"}
            </Button>
          </div>

          <div className="grid grid-cols-3 gap-2">
            {/* Year Selection */}
            <div className="space-y-2">
              <Label className="text-xs">
                {language === "am" ? "ዓመት" : "Year"}
              </Label>
              <Select value={selectedYear} onValueChange={setSelectedYear}>
                <SelectTrigger className="h-8">
                  <SelectValue
                    placeholder={language === "am" ? "ዓመት" : "Year"}
                  />
                </SelectTrigger>
                <SelectContent>
                  {yearOptions.map((year) => (
                    <SelectItem key={year.value} value={year.value}>
                      {year.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* Month Selection */}
            <div className="space-y-2">
              <Label className="text-xs">
                {language === "am" ? "ወር" : "Month"}
              </Label>
              <Select value={selectedMonth} onValueChange={setSelectedMonth}>
                <SelectTrigger className="h-8">
                  <SelectValue
                    placeholder={language === "am" ? "ወር" : "Month"}
                  />
                </SelectTrigger>
                <SelectContent>
                  {monthOptions.map((month) => (
                    <SelectItem key={month.value} value={month.value}>
                      {month.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* Day Selection */}
            <div className="space-y-2">
              <Label className="text-xs">
                {language === "am" ? "ቀን" : "Day"}
              </Label>
              <Select
                value={selectedDay}
                onValueChange={setSelectedDay}
                disabled={!selectedYear || !selectedMonth}
              >
                <SelectTrigger className="h-8">
                  <SelectValue placeholder={language === "am" ? "ቀን" : "Day"} />
                </SelectTrigger>
                <SelectContent>
                  {getDayOptions().map((day) => (
                    <SelectItem key={day.value} value={day.value}>
                      {day.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>

          <div className="flex justify-end gap-2 pt-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setIsOpen(false)}
            >
              {language === "am" ? "ሰርዝ" : "Cancel"}
            </Button>
            <Button
              size="sm"
              onClick={handleDateSelect}
              disabled={!selectedYear || !selectedMonth || !selectedDay}
            >
              {language === "am" ? "ምረጥ" : "Select"}
            </Button>
          </div>
        </div>
      </PopoverContent>
    </Popover>
  );
};

export default HabeshaDatePicker;
