import React, { useCallback, useMemo, useRef, useState } from 'react';
import { ChevronDown } from 'lucide-react';
import { useDismissOnFocusOutside } from './useDismissOnFocusOutside';

interface OperateCityProvincePickerProps {
  provinces: string[];
  value: string;
  onChange: (province: string) => void;
  ariaLabel?: string;
  placeholder?: string;
}

export function OperateCityProvincePicker({
  provinces,
  value,
  onChange,
  ariaLabel = '选择省份',
  placeholder = '请选择省份',
}: OperateCityProvincePickerProps) {
  const [open, setOpen] = useState(false);
  const fieldRef = useRef<HTMLDivElement>(null);

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

  useDismissOnFocusOutside(open, fieldRef, dismiss);

  const filtered = useMemo(() => {
    return [...provinces].sort((a, b) => a.localeCompare(b, 'zh-CN'));
  }, [provinces]);

  const pick = (next: string) => {
    onChange(next);
    setOpen(false);
  };

  return (
    <div className="vm-filter-picker-field" ref={fieldRef}>
      <button
        type="button"
        className={`vm-filter-picker-control vm-region-province-trigger ${open ? 'open' : ''}`}
        aria-label={ariaLabel}
        aria-expanded={open}
        aria-haspopup="listbox"
        onClick={() => setOpen((prev) => !prev)}
      >
        <span className={`vm-region-province-value${value ? '' : ' is-placeholder'}`}>
          {value || placeholder}
        </span>
        <ChevronDown size={14} className="vm-filter-picker-chevron" aria-hidden />
      </button>

      {open && (
        <div className="vm-filter-picker-popover vm-region-province-popover" role="listbox" aria-label={ariaLabel}>
          <div className="vm-filter-picker-options">
            {filtered.length === 0 ? (
              <p className="vm-filter-picker-empty">暂无省份</p>
            ) : (
              filtered.map((item) => (
                <button
                  key={item}
                  type="button"
                  role="option"
                  aria-selected={value === item}
                  className={`vm-filter-picker-option ${value === item ? 'checked' : ''}`}
                  onMouseDown={(event) => event.preventDefault()}
                  onClick={() => pick(item)}
                >
                  {item}
                </button>
              ))
            )}
          </div>
        </div>
      )}
    </div>
  );
}
