import { useState, useRef, useEffect } from 'react';
import { DayPicker } from 'react-day-picker';
import { zhCN } from 'date-fns/locale';
import { format, parseISO } from 'date-fns';
import 'react-day-picker/style.css';
import './DatePicker.css';

interface DateRangePickerProps {
  from: string; // YYYY-MM-DD
  to: string;   // YYYY-MM-DD
  onChange: (from: string, to: string) => void;
}

export default function DateRangePicker({ from, to, onChange }: DateRangePickerProps) {
  const [open, setOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);

  const selected = {
    from: from ? parseISO(from) : undefined,
    to: to ? parseISO(to) : undefined,
  };

  const isFirstClickRef = useRef(true);

  // 面板打开时重置首次点击标志
  useEffect(() => {
    if (open) {
      isFirstClickRef.current = true;
    }
  }, [open]);

  // 点击外部关闭
  useEffect(() => {
    if (!open) {return;}
    const handleClick = (e: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        setOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, [open]);

  const handleSelect = (range: { from?: Date; to?: Date } | undefined) => {
    if (range?.from) {
      const newFrom = format(range.from, 'yyyy-MM-dd');
      const newTo = range.to ? format(range.to, 'yyyy-MM-dd') : newFrom;
      onChange(newFrom, newTo);
    }
    // 第一次点击（开始日期）不关闭，第二次点击（结束日期）关闭
    if (isFirstClickRef.current) {
      isFirstClickRef.current = false;
      return;
    }
    setOpen(false);
  };

  const displayText =
    from && to ? `${format(parseISO(from), 'yyyy-MM-dd')} ~ ${format(parseISO(to), 'yyyy-MM-dd')}` : '';

  return (
    <div ref={containerRef} className="datepicker-container">
      <input
        type="text"
        readOnly
        value={displayText}
        placeholder="选择日期范围"
        className="datepicker-input range"
        onClick={() => setOpen(!open)}
      />
      {open && (
        <div className="datepicker-panel wide">
          <DayPicker
            mode="range"
            selected={selected}
            onSelect={handleSelect}
            locale={zhCN}
            numberOfMonths={2}
            defaultMonth={selected.from}
            captionLayout="dropdown"
            startMonth={new Date(2024, 0)}
            endMonth={new Date(2030, 11)}
          />
        </div>
      )}
    </div>
  );
}
