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

export interface OpsStaffOption {
  name: string;
  role: string;
}

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

interface PopoverPosition {
  top: number;
  left: number;
  width: number;
}

export function OpsManagerMultiSelect({ value, options, onChange }: OpsManagerMultiSelectProps) {
  const [open, setOpen] = useState(false);
  const [editing, setEditing] = useState(false);
  const [query, setQuery] = useState('');
  const [position, setPosition] = useState<PopoverPosition>({ top: 0, left: 0, width: 0 });
  const anchorRef = useRef<HTMLDivElement>(null);
  const popoverRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

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

  useDismissOnFocusOutside(open, [anchorRef, popoverRef], dismiss);

  const updatePosition = useCallback(() => {
    const anchor = anchorRef.current;
    if (!anchor) return;
    const rect = anchor.getBoundingClientRect();
    setPosition({
      top: rect.bottom + 6,
      left: rect.left,
      width: rect.width,
    });
  }, []);

  useEffect(() => {
    if (!open) return;
    updatePosition();
    window.addEventListener('resize', updatePosition);
    window.addEventListener('scroll', updatePosition, true);
    return () => {
      window.removeEventListener('resize', updatePosition);
      window.removeEventListener('scroll', updatePosition, true);
    };
  }, [open, updatePosition]);

  const summary = value.length <= 2
    ? value.join('、')
    : value.length > 0
      ? `已选 ${value.length} 人`
      : '';

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

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

  const clearAll = (event: React.MouseEvent) => {
    event.preventDefault();
    event.stopPropagation();
    onChange([]);
    setQuery('');
    setOpen(false);
    setEditing(false);
    inputRef.current?.focus();
  };

  const openPicker = () => {
    setEditing(true);
    setOpen(true);
    setQuery('');
    window.requestAnimationFrame(() => {
      updatePosition();
      inputRef.current?.focus();
    });
  };

  const popover =
    open && typeof document !== 'undefined'
      ? createPortal(
          <div
            ref={popoverRef}
            className="vm-filter-picker-popover vm-ops-picker-popover vm-ops-picker-popover--portal"
            role="listbox"
            aria-label="运维负责人列表"
            aria-multiselectable="true"
            style={{
              top: position.top,
              left: position.left,
              width: position.width,
            }}
          >
            <div className="vm-filter-picker-options vm-ops-picker-options">
              {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' : ''}`}
                      onMouseDown={(event) => event.preventDefault()}
                    >
                      <input
                        type="checkbox"
                        checked={checked}
                        onChange={() => toggle(staff.name)}
                      />
                      <span className="vm-ops-picker-name">{staff.name}</span>
                      <span className="vm-ops-picker-role">{staff.role}</span>
                    </label>
                  );
                })
              )}
            </div>

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

  return (
    <div className="vm-ops-picker">
      <div className="vm-ops-picker-control" ref={anchorRef}>
        <div className={`vm-filter-picker-control ${open ? 'open' : ''}`}>
          <input
            ref={inputRef}
            type="text"
            className="vm-filter-picker-input"
            value={editing ? query : summary}
            placeholder="请输入姓名搜索并选择"
            aria-label="运维负责人"
            aria-expanded={open}
            aria-autocomplete="list"
            role="combobox"
            readOnly={!editing}
            onFocus={openPicker}
            onChange={(event) => {
              setQuery(event.target.value);
              setOpen(true);
              window.requestAnimationFrame(updatePosition);
            }}
            onKeyDown={(event) => {
              if (event.key === 'Escape') dismiss();
            }}
          />
          {value.length > 0 ? (
            <button
              type="button"
              className="vm-filter-picker-clear"
              onClick={clearAll}
              aria-label="清空运维负责人"
              tabIndex={-1}
            >
              <X size={14} aria-hidden />
            </button>
          ) : null}
          <ChevronDown size={14} className="vm-filter-picker-chevron" aria-hidden />
        </div>
      </div>
      {popover}
    </div>
  );
}
