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 DatePickerProps {
  value: string; // ISO date string YYYY-MM-DD
  onChange: (value: string) => void;
  placeholder?: string;
}

export default function DatePicker({ value, onChange, placeholder = '选择日期' }: DatePickerProps) {
  const [open, setOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);

  // 点击外部关闭
  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 selected = value ? parseISO(value) : undefined;

  const handleSelect = (date: Date | undefined) => {
    if (date) {
      onChange(format(date, 'yyyy-MM-dd'));
    }
    setOpen(false);
  };

  return (
    <div ref={containerRef} className="datepicker-container">
      <input
        type="text"
        readOnly
        value={value ? format(parseISO(value), 'yyyy/MM/dd') : ''}
        placeholder={placeholder}
        className="datepicker-input"
        onClick={() => setOpen(!open)}
      />
      {open && (
        <div className="datepicker-panel">
          <DayPicker
            mode="single"
            selected={selected}
            onSelect={handleSelect}
            locale={zhCN}
            defaultMonth={selected}
            captionLayout="dropdown"
            startMonth={new Date(2024, 0)}
            endMonth={new Date(2030, 11)}
          />
        </div>
      )}
    </div>
  );
}
