import React, { useCallback, useRef, useState } from 'react';
import { Calendar, X } from 'lucide-react';
import { DateRangeCalendarPanel } from './DateRangeCalendarPanel';
import { useDismissOnFocusOutside } from './useDismissOnFocusOutside';
import type { DateRangeValue } from '../utils/dateRangeCalendar';

export type { DateRangeValue };

interface DateRangeFilterFieldProps {
  startDate: string;
  endDate: string;
  onChange: (range: DateRangeValue) => void;
  ariaLabel?: string;
  startPlaceholder?: string;
  endPlaceholder?: string;
}

function formatDisplayText(
  startDate: string,
  endDate: string,
  startPlaceholder: string,
  endPlaceholder: string,
): string {
  if (startDate && endDate) return `${startDate} ~ ${endDate}`;
  if (startDate) return `${startDate} ~ ${endPlaceholder}`;
  if (endDate) return `${startPlaceholder} ~ ${endDate}`;
  return '';
}

export function DateRangeFilterField({
  startDate,
  endDate,
  onChange,
  ariaLabel = '日期范围',
  startPlaceholder = '开始日期',
  endPlaceholder = '结束日期',
}: DateRangeFilterFieldProps) {
  const [open, setOpen] = useState(false);
  const fieldRef = useRef<HTMLDivElement>(null);
  const hasValue = Boolean(startDate || endDate);
  const displayText = formatDisplayText(startDate, endDate, startPlaceholder, endPlaceholder);
  const placeholder = `${startPlaceholder} ~ ${endPlaceholder}`;

  const dismiss = useCallback(() => {
    setOpen(false);
  }, []);

  useDismissOnFocusOutside(open, fieldRef, dismiss);

  const openPicker = () => {
    setOpen(true);
  };

  const clear = (event: React.MouseEvent) => {
    event.preventDefault();
    event.stopPropagation();
    onChange({ startDate: '', endDate: '' });
    setOpen(false);
  };

  return (
    <div className="vm-date-range-field vm-filter-picker-field" ref={fieldRef}>
      <div
        className={`vm-filter-picker-control vm-date-range-trigger ${open ? 'open' : ''}`}
      >
        <input
          type="text"
          readOnly
          className="vm-filter-picker-input"
          value={displayText}
          placeholder={placeholder}
          aria-label={ariaLabel}
          aria-expanded={open}
          onFocus={openPicker}
          onClick={openPicker}
          onKeyDown={(event) => {
            if (event.key === 'Escape') dismiss();
            if (event.key === 'Enter' || event.key === ' ') {
              event.preventDefault();
              openPicker();
            }
          }}
        />
        {hasValue ? (
          <button
            type="button"
            className="vm-filter-picker-clear"
            onClick={clear}
            aria-label={`清空${ariaLabel}`}
            tabIndex={-1}
          >
            <X size={14} aria-hidden />
          </button>
        ) : null}
        <Calendar size={14} className="vm-date-range-icon" aria-hidden />
      </div>

      {open ? (
        <div className="vm-date-range-popover" role="dialog" aria-label={ariaLabel}>
          <DateRangeCalendarPanel
            startDate={startDate}
            endDate={endDate}
            onChange={onChange}
            onComplete={dismiss}
          />
        </div>
      ) : null}
    </div>
  );
}
