import React, { useState, useRef, useEffect } from 'react';
import { ChevronDownIcon } from "lucide-react";
import { XMarkIcon, CheckIcon } from '@heroicons/react/24/outline';

// 单选下拉选择组件
export const CustomSelect: React.FC<{
  value: string | number | null | undefined;
  onChange: (value: string) => void;
  options: { value: string | number; label: string; description?: string }[];
  placeholder?: string;
  className?: string;
  disabled?: boolean;
}> = ({ value, onChange, options, placeholder, className = '', disabled = false }) => {
  // 确保 value 是字符串，处理 null 和 undefined
  const safeValue = value === null || value === undefined ? '' : String(value);
  return (
    <div className={`relative ${className}`}>
      <select
        value={safeValue}
        onChange={(e) => onChange(e.target.value)}
        disabled={disabled}
        className={`w-full appearance-none bg-white border border-gray-200 rounded-lg px-3 py-2 pr-8 text-sm text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all duration-200 hover:border-gray-300 cursor-pointer ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
      >
        {placeholder && <option value="">{placeholder}</option>}
        {options.map((option) => (
          <option key={option.value} value={option.value}>
            {option.label}
          </option>
        ))}
      </select>
      <div className="absolute inset-y-0 right-0 flex items-center pr-2 pointer-events-none">
        <ChevronDownIcon className="h-4 w-4 text-gray-400" />
      </div>
    </div>
  );
};

// 多选下拉选择组件
interface MultiSelectOption {
  value: string;
  label: string;
  disabled?: boolean;
}

interface CustomMultiSelectProps {
  options: MultiSelectOption[];
  value: string[];
  onChange: (value: string[]) => void;
  placeholder?: string;
  disabled?: boolean;
  className?: string;
  maxDisplayItems?: number;
  searchable?: boolean;
}

export const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
  options,
  value = [],
  onChange,
  placeholder = "请选择...",
  disabled = false,
  className = "",
  maxDisplayItems = 3,
  searchable = false
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const dropdownRef = useRef<HTMLDivElement>(null);
  const searchInputRef = useRef<HTMLInputElement>(null);

  // 过滤选项
  const filteredOptions = searchable && searchTerm
    ? options.filter(option =>
        option.label.toLowerCase().includes(searchTerm.toLowerCase())
      )
    : options;

  // 获取选中的选项标签
  const getSelectedLabels = () => {
    return value.map(val => {
      const option = options.find(opt => opt.value === val);
      return option ? option.label : val;
    });
  };

  // 显示的文本
  const getDisplayText = () => {
    const selectedLabels = getSelectedLabels();

    if (selectedLabels.length === 0) {
      return placeholder;
    }

    if (selectedLabels.length <= maxDisplayItems) {
      return selectedLabels.join(', ');
    }

    return `${selectedLabels.slice(0, maxDisplayItems).join(', ')} +${selectedLabels.length - maxDisplayItems}`;
  };

  // 处理选项点击
  const handleOptionClick = (optionValue: string) => {
    if (value.includes(optionValue)) {
      // 取消选择
      onChange(value.filter(val => val !== optionValue));
    } else {
      // 添加选择
      onChange([...value, optionValue]);
    }
  };

  // 移除单个选项
  const removeOption = (optionValue: string, e: React.MouseEvent) => {
    e.stopPropagation();
    onChange(value.filter(val => val !== optionValue));
  };

  // 清空所有选择
  const clearAll = (e: React.MouseEvent) => {
    e.stopPropagation();
    onChange([]);
  };

  // 点击外部关闭下拉框
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false);
        setSearchTerm('');
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  // 打开下拉框时聚焦搜索框
  useEffect(() => {
    if (isOpen && searchable && searchInputRef.current) {
      searchInputRef.current.focus();
    }
  }, [isOpen, searchable]);

  return (
    <div className={`relative ${className}`} ref={dropdownRef}>
      {/* 主选择框 */}
      <div
        className={`
          relative w-full cursor-pointer rounded-lg border border-gray-200 bg-white py-2 pl-3 pr-10 text-left shadow-sm
          focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500
          ${disabled ? 'cursor-not-allowed bg-gray-50 text-gray-500' : 'hover:border-gray-300'}
          ${isOpen ? 'border-primary-500 ring-2 ring-primary-500' : ''}
        `}
        onClick={() => !disabled && setIsOpen(!isOpen)}
      >
        <div className="flex items-center justify-between">
          <div className="flex-1 min-w-0">
            {value.length > 0 ? (
              <div className="flex flex-wrap gap-1">
                {value.length <= maxDisplayItems ? (
                  // 显示所有选中的标签
                  getSelectedLabels().map((label, index) => (
                    <span
                      key={value[index]}
                      className="inline-flex items-center px-2 py-1 rounded-md text-xs font-medium bg-primary-100 text-primary-800"
                    >
                      {label}
                      {!disabled && (
                        <button
                          type="button"
                          onClick={(e) => removeOption(value[index], e)}
                          className="ml-1 inline-flex items-center justify-center w-4 h-4 rounded-full hover:bg-primary-200 focus:outline-none"
                        >
                          <XMarkIcon className="w-3 h-3" />
                        </button>
                      )}
                    </span>
                  ))
                ) : (
                  // 显示简化文本
                  <span className="text-gray-900 truncate text-sm">
                    {getDisplayText()}
                  </span>
                )}
              </div>
            ) : (
              <span className="text-gray-500 truncate text-sm">{placeholder}</span>
            )}
          </div>

          <div className="flex items-center space-x-1">
            {value.length > 0 && !disabled && (
              <button
                type="button"
                onClick={clearAll}
                className="inline-flex items-center justify-center w-5 h-5 rounded-full hover:bg-gray-200 focus:outline-none"
              >
                <XMarkIcon className="w-4 h-4 text-gray-400" />
              </button>
            )}
            <ChevronDownIcon
              className={`w-4 h-4 text-gray-400 transition-transform duration-200 ${
                isOpen ? 'transform rotate-180' : ''
              }`}
            />
          </div>
        </div>
      </div>

      {/* 下拉选项 */}
      {isOpen && (
        <div className="absolute z-10 mt-1 w-full bg-white shadow-lg max-h-60 rounded-lg py-1 text-base ring-1 ring-black ring-opacity-5 overflow-auto focus:outline-none">
          {/* 搜索框 */}
          {searchable && (
            <div className="px-3 py-2 border-b border-gray-200">
              <input
                ref={searchInputRef}
                type="text"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                placeholder="搜索选项..."
                className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500"
              />
            </div>
          )}

          {/* 全选/取消全选 */}
          {filteredOptions.length > 1 && (
            <div className="px-3 py-2 border-b border-gray-200">
              <button
                type="button"
                onClick={() => {
                  const allValues = filteredOptions.map(opt => opt.value);
                  const isAllSelected = allValues.every(val => value.includes(val));

                  if (isAllSelected) {
                    // 取消选择当前过滤的所有选项
                    onChange(value.filter(val => !allValues.includes(val)));
                  } else {
                    // 选择当前过滤的所有选项
                    const newValue = [...new Set([...value, ...allValues])];
                    onChange(newValue);
                  }
                }}
                className="text-sm text-primary-600 hover:text-primary-800 font-medium"
              >
                {filteredOptions.every(opt => value.includes(opt.value)) ? '取消全选' : '全选'}
              </button>
            </div>
          )}

          {/* 选项列表 */}
          {filteredOptions.length === 0 ? (
            <div className="px-3 py-2 text-sm text-gray-500">
              {searchTerm ? '没有找到匹配的选项' : '暂无选项'}
            </div>
          ) : (
            filteredOptions.map((option) => {
              const isSelected = value.includes(option.value);

              return (
                <div
                  key={option.value}
                  className={`
                    relative cursor-pointer select-none py-2 pl-3 pr-9 hover:bg-gray-50
                    ${option.disabled ? 'cursor-not-allowed opacity-50' : ''}
                    ${isSelected ? 'bg-primary-50 text-primary-900' : 'text-gray-900'}
                  `}
                  onClick={() => !option.disabled && handleOptionClick(option.value)}
                >
                  <div className="flex items-center">
                    <span className={`block truncate text-sm ${isSelected ? 'font-medium' : 'font-normal'}`}>
                      {option.label}
                    </span>
                  </div>

                  {isSelected && (
                    <span className="absolute inset-y-0 right-0 flex items-center pr-4 text-primary-600">
                      <CheckIcon className="w-4 h-4" />
                    </span>
                  )}
                </div>
              );
            })
          )}
        </div>
      )}
    </div>
  );
};