import { h } from 'preact';
import { useState, useEffect, useCallback, useMemo } from 'preact/hooks';

import { $t } from '../locale';

import styles from './css/index.less';

const PMGDropDown = (props: any) => {
  // const sidebar = [''];// 滚动数据
  // const selectedValue = '请选择'; // 选中值
  // const inputValue = ''; // 输入框值
  // const isOpenSelect = false; // 是否显示下拉列表
  // const title = ''; // 标题
  // const dropDownWidth = '100%'; // 下拉列表宽度
  // const dropDownHeight = '40px'; // 下拉列表高度
  // const scrollHeight = '200px'; // 下拉列表滚动高度
  // const isTightTitle = true; // 是否是连接标题
  // const readonly = false; // 是否只读不下拉
  // const onToggleDropdown = () => {}; // 切换下拉列表显示状态回调函数
  // const onHandleSelect = () => {}; // 选择回调函数
  // const dropOptionWidth = '100%'; // 下拉列表选项宽度
  // const dropOptionMinWidth = '100%'; // 下拉列表选项最小宽度
  // const dropOptionMaxWidth = '100%'; // 下拉列表选项最大宽度
  // const dropDownType = 1; // 1 下拉 2 输入框
  // const highlightColor = '#a1fff6'; // 高亮颜色
  // const placeholder = '请选择（支持搜索）'; // 输入框占位符
  // const onDropDownInput = () => {};  // 输入框输入回调函数

  const {
    customClass,
    sidebar,
    selectedValue,
    isTightTitle,
    title,
    dropDownWidth,
    dropDownHeight,
    scrollHeight,
    dropOptionWidth = '100%',
    dropOptionMinWidth,
    dropOptionMaxWidth,
    readonly,
    dropDownType = 1, // 1 下拉 2 输入框
    highlightColor = '#a1fff6',
    inputFlexGrow = 1,
    placeholder = $t('请选择（支持搜索）'),
    onToggleDropdown,
    onHandleSelect,
    searchValue,
    setSearchValue,
  } = props;

  const [isOpenSelect, setIsOpenSelect] = useState(false);
  const [selectedIndex, setSelectedIndex] = useState(selectedValue
    ? (sidebar || []).findIndex(item => item === selectedValue)
    : -1);
  // const [searchValue, setSearchValue] = useState(inputValue || '');


  // 高亮关键字的渲染函数
  const renderHighlightText = useCallback((text, keyword) => {
    if (!keyword || !text) return text;

    const regex = new RegExp(`(${keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
    const parts = text.split(regex);

    return parts.map((part, index) => {
      if (regex.test(part)) {
        return (
          <text
            key={index}
            style={{ color: highlightColor }}
            className={styles['pmg-dropdown-highlight']}
          >{part}
          </text>
        );
      }
      return part;
    });
  }, []);

  // 生成唯一的 ID，避免多个下拉组件冲突
  const dropdownId = useMemo(() => `pmg-dropdown-${Date.now()}-${Math.random().toString(36)
    .slice(2, 9)}`, []);

  useEffect(() => {
    // 如果是只读模式，无下拉不需要处理
    if (readonly) {
      return;
    }
    // 使用 setTimeout 确保 DOM 完全加载后再添加事件监听
    const timeoutId = setTimeout(() => {
      // 使用捕获阶段监听，第三个参数设为 true
      document.body.addEventListener('click', handleClickOutside, true);
    }, 0);

    return () => {
      clearTimeout(timeoutId);
      // 移除事件监听时也要使用 true 参数
      document.body.removeEventListener('click', handleClickOutside, true);
    };
  });

  const handleClickOutside = useCallback(() => {
    // 如果下拉列表未打开，不需要处理
    if (!isOpenSelect) {
      return;
    }

    // 通过 ID 获取下拉组件元素
    const dropdownElement = document.getElementById(dropdownId);

    // 如果点击的元素不在下拉组件内部，则关闭下拉列表
    if (dropdownElement) {
      setIsOpenSelect(false);
    }
  }, [isOpenSelect, dropdownId]);

  const toggleDropdown = useCallback(() => {
    if (readonly) {
      onToggleDropdown?.();
      return;
    }

    // 如果是输入框模式且当前关闭状态，打开时清空搜索以显示所有选项
    if (dropDownType === 2 && !isOpenSelect) {
      setSearchValue('');
    }

    setIsOpenSelect(!isOpenSelect);
    onToggleDropdown?.();
  }, [readonly, isOpenSelect, onToggleDropdown, dropDownType]);

  const handleSelect = useCallback((option, index) => {
    setIsOpenSelect(false);
    setSelectedIndex(index);
    // 如果是输入框模式，更新搜索值为选中的选项
    if (dropDownType === 2) {
      setSearchValue(option);
    }
    onHandleSelect?.(option, index);
  }, [onHandleSelect, dropDownType]);

  const onDropDownInput = useCallback((e) => {
    const { value } = e.target;
    // setSearchValue(value);
    setIsOpenSelect(true);
    props.onDropDownInput?.(value);
  }, [props.onDropDownInput]);

  return (
    <div
      id={dropdownId}
      className={`${styles['pmg-dropdown-box']} ${styles[customClass]}`}
    >
      {/* 显示选中项，点击时调用 toggleDropdown 方法切换下拉列表显示状态 */}
      <div
        className={`${styles['pmg-dropdown-selected']} ${title ? styles['pmg-dropdown-selected-title'] : ''} ${isTightTitle ? styles['pmg-dropdown-selected-title-tight'] : ''} `}
        style={{ height: dropDownHeight, width: dropDownWidth }}
        onClick={toggleDropdown}
      >
        {title
         && (
         <div className={styles['pmg-dropdown-title-box']}>
           <text className={styles['pmg-dropdown-title']}>{title}</text>
         </div>
         )}
        {selectedValue && dropDownType === 1
         && (
         <div className={styles['pmg-dropdown-text-box']}>
           <text className={styles['pmg-dropdown-text']}>
             {selectedValue}
           </text>
         </div>
         )}

        {dropDownType === 2
         && (
           <input
             value={searchValue}
             onInput={onDropDownInput}
             className={styles['pmg-form-input']}
             style={{ flexGrow: inputFlexGrow }}
             placeholder={placeholder}
           />
         )}
        {/* {isOpenSelect && (<div className={styles['pmg-dropdown-line']}></div>)} */}
        <div className={styles['pmg-dropdown-icon']}></div>
      </div>
      {/* 根据 isOpen 状态决定是否显示下拉列表 */}
      {(isOpenSelect && sidebar?.length > 0) && (
      <div
        className={styles['pmg-dropdown-options']}
        style={{ width: dropOptionWidth, minWidth: dropOptionMinWidth, maxWidth: dropOptionMaxWidth, maxHeight: scrollHeight, top: dropDownHeight }}

      >
        {/* 遍历过滤后的选项数组，为每个选项添加点击事件 */}
        {sidebar.map((option, index) => {
          const originalIndex = sidebar.findIndex(item => item === option);
          const isSelected = dropDownType === 2 ? selectedValue === option : originalIndex === selectedIndex;

          return (
            <div
              key={index}
              className={`${styles['pmg-dropdown-option']} ${isSelected ? styles['pmg-dropdown-option-select'] : ''} `}
              onClick={() => handleSelect(option, originalIndex)}
            >
              <text className={styles['pmg-dropdown-option-text']}>
                {dropDownType === 2 && searchValue.trim()
                  ? renderHighlightText(option, searchValue.trim())
                  : option}
              </text>
            </div>
          );
        })}
      </div>
      )}
    </div>
  );
};

export default PMGDropDown;
