import React, { useMemo, useState } from 'react';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import {
  addMonths,
  buildMonthCells,
  formatISODate,
  formatMonthTitle,
  parseISODate,
  sameCalendarDay,
  startOfMonth,
  WEEKDAY_LABELS,
} from '../utils/dateRangeCalendar';

interface SingleDateCalendarPanelProps {
  value: string;
  onChange: (iso: string) => void;
  onComplete?: () => void;
}

export function SingleDateCalendarPanel({
  value,
  onChange,
  onComplete,
}: SingleDateCalendarPanelProps) {
  const selected = parseISODate(value);
  const [viewMonth, setViewMonth] = useState(() => startOfMonth(selected || new Date()));
  const cells = useMemo(() => buildMonthCells(viewMonth), [viewMonth]);
  const today = useMemo(() => new Date(), []);

  const pickDate = (date: Date) => {
    onChange(formatISODate(date));
    onComplete?.();
  };

  return (
    <div className="vm-single-date-calendar">
      <div className="vm-single-date-calendar-nav">
        <button
          type="button"
          className="vm-date-range-nav-btn"
          aria-label="上一月"
          onClick={() => setViewMonth((prev) => addMonths(prev, -1))}
        >
          <ChevronLeft size={16} aria-hidden />
        </button>
        <span className="vm-single-date-calendar-title">{formatMonthTitle(viewMonth)}</span>
        <button
          type="button"
          className="vm-date-range-nav-btn"
          aria-label="下一月"
          onClick={() => setViewMonth((prev) => addMonths(prev, 1))}
        >
          <ChevronRight size={16} aria-hidden />
        </button>
      </div>

      <div className="vm-date-range-weekdays" aria-hidden>
        {WEEKDAY_LABELS.map((label) => (
          <span key={label} className="vm-date-range-weekday">{label}</span>
        ))}
      </div>

      <div className="vm-date-range-days" role="grid">
        {cells.map((cell) => {
          const key = formatISODate(cell.date);
          const isSelected = selected ? sameCalendarDay(cell.date, selected) : false;
          const isToday = sameCalendarDay(cell.date, today);
          const classNames = [
            'vm-date-range-day',
            !cell.inMonth ? 'is-outside' : '',
            isSelected ? 'is-selected' : '',
            isToday ? 'is-today' : '',
          ].filter(Boolean).join(' ');

          return (
            <button
              key={key}
              type="button"
              role="gridcell"
              className={classNames}
              aria-label={key}
              aria-pressed={isSelected}
              onClick={() => pickDate(cell.date)}
            >
              <span>{cell.date.getDate()}</span>
            </button>
          );
        })}
      </div>

      <div className="vm-single-date-calendar-footer">
        <button
          type="button"
          className="vm-detail-inline-picker-quick"
          onClick={() => pickDate(today)}
        >
          今天
        </button>
      </div>
    </div>
  );
}
