import React, { useMemo, useState } from 'react';
import { Search, X } from 'lucide-react';
import type { OpsStaffOption } from './OpsManagerMultiSelect';

interface OpsManagerPickerPanelProps {
  value: string[];
  options: OpsStaffOption[];
  onChange: (names: string[]) => void;
}

export function OpsManagerPickerPanel({
  value,
  options,
  onChange,
}: OpsManagerPickerPanelProps) {
  const [query, setQuery] = useState('');

  const filtered = useMemo(() => {
    const q = query.trim();
    if (!q) return options;
    return options.filter((item) => item.name.includes(q));
  }, [options, query]);

  const toggle = (name: string) => {
    if (value.includes(name)) {
      onChange(value.filter((item) => item !== name));
      return;
    }
    onChange([...value, name]);
  };

  return (
    <div className="vm-ops-picker-panel">
      <label className="vm-operate-city-edit-search vm-ops-picker-panel-search">
        <Search size={16} aria-hidden className="vm-operate-city-edit-search-icon" />
        <input
          type="text"
          className="vm-operate-city-edit-search-input"
          value={query}
          placeholder="输入姓名搜索"
          aria-label="搜索运维负责人"
          autoComplete="off"
          onChange={(event) => setQuery(event.target.value)}
        />
        {query ? (
          <button
            type="button"
            className="vm-operate-city-edit-search-clear"
            onClick={() => setQuery('')}
            aria-label="清空搜索"
          >
            <X size={14} aria-hidden />
          </button>
        ) : null}
      </label>

      {value.length > 0 ? (
        <div className="vm-ops-picker-tags vm-ops-picker-panel-tags">
          {value.map((name) => (
            <span key={name} className="vm-ops-picker-tag">
              {name}
              <button
                type="button"
                aria-label={`移除${name}`}
                onClick={() => onChange(value.filter((item) => item !== name))}
              >
                <X size={12} aria-hidden />
              </button>
            </span>
          ))}
        </div>
      ) : null}

      <div className="vm-filter-picker-options vm-ops-picker-options vm-ops-picker-panel-options" role="listbox" aria-multiselectable="true" aria-label="运维负责人列表">
        {filtered.length === 0 ? (
          <p className="vm-filter-picker-empty">暂无匹配人员</p>
        ) : (
          filtered.map((staff) => {
            const checked = value.includes(staff.name);
            return (
              <label
                key={staff.name}
                className={`vm-ops-picker-option ${checked ? 'checked' : ''}`}
              >
                <input
                  type="checkbox"
                  checked={checked}
                  onChange={() => toggle(staff.name)}
                />
                <span className="vm-ops-picker-name">{staff.name}</span>
              </label>
            );
          })
        )}
      </div>
    </div>
  );
}
