"use client";

import React, { useState, useEffect, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { ChevronLeft, ChevronRight } from "lucide-react";
import {
  format,
  addMonths,
  subMonths,
  startOfMonth,
  endOfMonth,
  eachDayOfInterval,
  isSameMonth,
  isSameDay,
  isToday,
} from "date-fns";
import { ko } from "date-fns/locale";
import { cn } from "@/lib/utils";

interface InlineCellDatePickerProps {
  value: string;
  onChange: (value: string) => void;
  onSave: () => void;
  onKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => void;
  inputRef?: React.RefObject<HTMLInputElement>;
}

export const InlineCellDatePicker: React.FC<InlineCellDatePickerProps> = ({
  value,
  onChange,
  onSave,
  onKeyDown,
  inputRef,
}) => {
  const [isOpen, setIsOpen] = useState(true);
  const [currentMonth, setCurrentMonth] = useState(new Date());
  const [viewMode, setViewMode] = useState<"calendar" | "year" | "month">("calendar");
  const [yearRangeStart, setYearRangeStart] = useState(() => Math.floor(new Date().getFullYear() / 12) * 12);
  const localInputRef = useRef<HTMLInputElement>(null);
  const actualInputRef = inputRef || localInputRef;

  const parseDate = (val: string): Date | undefined => {
    if (!val) return undefined;
    try {
      const date = new Date(val);
      if (isNaN(date.getTime())) return undefined;
      return date;
    } catch {
      return undefined;
    }
  };

  const selectedDate = parseDate(value);

  useEffect(() => {
    if (selectedDate) {
      setCurrentMonth(new Date(selectedDate.getFullYear(), selectedDate.getMonth(), 1));
    }
  }, []);

  const handleDateClick = (date: Date) => {
    const dateStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
    onChange(dateStr);
    setIsOpen(false);
    setTimeout(() => onSave(), 50);
  };

  const handleSetToday = () => {
    const today = new Date();
    const dateStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;
    onChange(dateStr);
    setIsOpen(false);
    setTimeout(() => onSave(), 50);
  };

  const handleClear = () => {
    onChange("");
    setIsOpen(false);
    setTimeout(() => onSave(), 50);
  };

  const handleInputChange = (raw: string) => {
    onChange(raw);
    const digitsOnly = raw.replace(/\D/g, "");
    if (digitsOnly.length === 8) {
      const y = parseInt(digitsOnly.slice(0, 4), 10);
      const m = parseInt(digitsOnly.slice(4, 6), 10) - 1;
      const d = parseInt(digitsOnly.slice(6, 8), 10);
      const date = new Date(y, m, d);
      if (date.getFullYear() === y && date.getMonth() === m && date.getDate() === d && y >= 1900 && y <= 2100) {
        const dateStr = `${y}-${String(m + 1).padStart(2, "0")}-${String(d).padStart(2, "0")}`;
        onChange(dateStr);
        setIsOpen(false);
        setTimeout(() => onSave(), 50);
      }
    }
  };

  const handlePopoverClose = (open: boolean) => {
    if (!open) {
      setIsOpen(false);
      onSave();
    }
  };

  const monthStart = startOfMonth(currentMonth);
  const monthEnd = endOfMonth(currentMonth);
  const days = eachDayOfInterval({ start: monthStart, end: monthEnd });

  const startDate = new Date(monthStart);
  const dayOfWeek = startDate.getDay();
  const paddingDays = dayOfWeek === 0 ? 6 : dayOfWeek - 1;
  const allDays = [...Array(paddingDays).fill(null), ...days];

  return (
    <Popover open={isOpen} onOpenChange={handlePopoverClose}>
      <PopoverTrigger asChild>
        <input
          ref={actualInputRef as any}
          type="text"
          inputMode="numeric"
          value={value}
          onChange={(e) => handleInputChange(e.target.value)}
          onKeyDown={onKeyDown}
          onClick={() => setIsOpen(true)}
          placeholder="YYYYMMDD"
          className="border-primary bg-background h-full w-full border-2 px-2 py-1 text-xs focus:outline-none sm:px-4 sm:py-1.5 sm:text-sm"
        />
      </PopoverTrigger>
      <PopoverContent className="w-auto p-0" align="start" onOpenAutoFocus={(e) => e.preventDefault()} onCloseAutoFocus={(e) => e.preventDefault()}>
        <div className="p-3">
          <div className="mb-2 flex items-center gap-2">
            <Button variant="outline" size="sm" className="h-6 text-xs" onClick={handleSetToday}>
              오늘
            </Button>
            <Button variant="outline" size="sm" className="h-6 text-xs" onClick={handleClear}>
              초기화
            </Button>
          </div>

          {viewMode === "year" ? (
            <>
              <div className="mb-3 flex items-center justify-between">
                <Button variant="ghost" size="sm" className="h-7 w-7 p-0" onClick={() => setYearRangeStart(yearRangeStart - 12)}>
                  <ChevronLeft className="h-3.5 w-3.5" />
                </Button>
                <div className="text-xs font-medium">
                  {yearRangeStart} - {yearRangeStart + 11}
                </div>
                <Button variant="ghost" size="sm" className="h-7 w-7 p-0" onClick={() => setYearRangeStart(yearRangeStart + 12)}>
                  <ChevronRight className="h-3.5 w-3.5" />
                </Button>
              </div>
              <div className="grid grid-cols-4 gap-1.5">
                {Array.from({ length: 12 }, (_, i) => yearRangeStart + i).map((year) => (
                  <Button
                    key={year}
                    variant="ghost"
                    size="sm"
                    className={cn(
                      "h-8 text-xs",
                      year === currentMonth.getFullYear() && "bg-primary text-primary-foreground hover:bg-primary",
                      year === new Date().getFullYear() && year !== currentMonth.getFullYear() && "border-primary border",
                    )}
                    onClick={() => {
                      setCurrentMonth(new Date(year, currentMonth.getMonth(), 1));
                      setViewMode("month");
                    }}
                  >
                    {year}
                  </Button>
                ))}
              </div>
            </>
          ) : viewMode === "month" ? (
            <>
              <div className="mb-3 flex items-center justify-between">
                <Button variant="ghost" size="sm" className="h-7 w-7 p-0" onClick={() => setCurrentMonth(new Date(currentMonth.getFullYear() - 1, currentMonth.getMonth(), 1))}>
                  <ChevronLeft className="h-3.5 w-3.5" />
                </Button>
                <button
                  type="button"
                  className="hover:bg-accent rounded-md px-2 py-0.5 text-xs font-medium transition-colors"
                  onClick={() => {
                    setYearRangeStart(Math.floor(currentMonth.getFullYear() / 12) * 12);
                    setViewMode("year");
                  }}
                >
                  {currentMonth.getFullYear()}년
                </button>
                <Button variant="ghost" size="sm" className="h-7 w-7 p-0" onClick={() => setCurrentMonth(new Date(currentMonth.getFullYear() + 1, currentMonth.getMonth(), 1))}>
                  <ChevronRight className="h-3.5 w-3.5" />
                </Button>
              </div>
              <div className="grid grid-cols-4 gap-1.5">
                {Array.from({ length: 12 }, (_, i) => i).map((month) => (
                  <Button
                    key={month}
                    variant="ghost"
                    size="sm"
                    className={cn(
                      "h-8 text-xs",
                      month === currentMonth.getMonth() && "bg-primary text-primary-foreground hover:bg-primary",
                      month === new Date().getMonth() && currentMonth.getFullYear() === new Date().getFullYear() && month !== currentMonth.getMonth() && "border-primary border",
                    )}
                    onClick={() => {
                      setCurrentMonth(new Date(currentMonth.getFullYear(), month, 1));
                      setViewMode("calendar");
                    }}
                  >
                    {month + 1}월
                  </Button>
                ))}
              </div>
            </>
          ) : (
            <>
              <div className="mb-3 flex items-center justify-between">
                <Button variant="ghost" size="sm" className="h-7 w-7 p-0" onClick={() => setCurrentMonth(subMonths(currentMonth, 1))}>
                  <ChevronLeft className="h-3.5 w-3.5" />
                </Button>
                <button
                  type="button"
                  className="hover:bg-accent rounded-md px-2 py-0.5 text-xs font-medium transition-colors"
                  onClick={() => {
                    setYearRangeStart(Math.floor(currentMonth.getFullYear() / 12) * 12);
                    setViewMode("year");
                  }}
                >
                  {format(currentMonth, "yyyy년 MM월", { locale: ko })}
                </button>
                <Button variant="ghost" size="sm" className="h-7 w-7 p-0" onClick={() => setCurrentMonth(addMonths(currentMonth, 1))}>
                  <ChevronRight className="h-3.5 w-3.5" />
                </Button>
              </div>

              <div className="mb-1 grid grid-cols-7 gap-0.5">
                {["월", "화", "수", "목", "금", "토", "일"].map((day) => (
                  <div key={day} className="text-muted-foreground p-1 text-center text-[10px] font-medium">
                    {day}
                  </div>
                ))}
              </div>

              <div className="grid grid-cols-7 gap-0.5">
                {allDays.map((date, index) => {
                  if (!date) return <div key={index} className="p-1" />;

                  const isCurrentMonth = isSameMonth(date, currentMonth);
                  const isSelected = selectedDate ? isSameDay(date, selectedDate) : false;
                  const isTodayDate = isToday(date);

                  return (
                    <Button
                      key={date.toISOString()}
                      variant="ghost"
                      size="sm"
                      className={cn(
                        "h-7 w-7 p-0 text-[11px]",
                        !isCurrentMonth && "text-muted-foreground opacity-50",
                        isSelected && "bg-primary text-primary-foreground hover:bg-primary",
                        isTodayDate && !isSelected && "border-primary border",
                      )}
                      onClick={() => handleDateClick(date)}
                      disabled={!isCurrentMonth}
                    >
                      {format(date, "d")}
                    </Button>
                  );
                })}
              </div>
            </>
          )}
        </div>
      </PopoverContent>
    </Popover>
  );
};
