import KFIcon from '@/components/KFIcon';
import { isEmpty } from '@/utils';
import { Flex, Popconfirm, Typography } from 'antd';
import classNames from 'classnames';
import { useEffect, useRef, useState } from 'react';
import ParameterRange from '../ParameterRange';
import { ParameterType } from '../utils';
import styles from './index.less';

type ParameterRangeProps = {
  type: ParameterType;
  value?: any[];
  onChange?: (value: any[]) => void;
};

function PopParameterRange({ type, value, onChange }: ParameterRangeProps) {
  const [open, setOpen] = useState(false);
  const popconfirmRef = useRef<HTMLDivElement | null>(null);
  const disabled = !type;
  const jsonText = JSON.stringify(value);

  const handleClickOutside = (event: MouseEvent) => {
    // 判断点击是否在 Popconfirm 内
    const popconfirmNode = document.getElementById('pop-parameter');
    if (popconfirmNode && !popconfirmNode.contains(event.target as Node)) {
      setOpen(false);
    }
  };

  useEffect(() => {
    if (open) {
      document.addEventListener('mousedown', handleClickOutside);
    } else {
      document.removeEventListener('mousedown', handleClickOutside);
    }
    // 清理事件监听器
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [open]);

  const handleClick = () => {
    if (!disabled) {
      setOpen(true);
    }
  };

  const handleCancel = () => {
    setOpen(false);
  };

  const handleConfirm = (value: number[]) => {
    onChange?.(value);
    setOpen(false);
  };

  return (
    <div ref={popconfirmRef}>
      <Popconfirm
        id="pop-parameter"
        title={<PopconfirmTitle title="参数范围" onClose={handleCancel} />}
        disabled={disabled}
        description={
          <ParameterRange type={type} value={value} onConfirm={handleConfirm}></ParameterRange>
        }
        overlayClassName={styles['parameter-range']}
        icon={null}
        open={open}
        destroyTooltipOnHide
      >
        <div
          className={classNames(styles['parameter-range__input'], {
            [styles['parameter-range__input--disabled']]: disabled,
            [styles['parameter-range__input--empty']]: isEmpty(jsonText),
          })}
          onClick={handleClick}
        >
          <Typography.Text
            ellipsis={{ tooltip: jsonText }}
            className={styles['parameter-range__input__text']}
          >
            {jsonText ?? '请选择'}
          </Typography.Text>
          <KFIcon type="icon-bianji" className={styles['parameter-range__input__icon']} />
        </div>
      </Popconfirm>
    </div>
  );
}

function PopconfirmTitle({ title, onClose }: { title: string; onClose: () => void }) {
  return (
    <Flex align="center" justify="space-between">
      <span className={styles['parameter-range-title']}>{title}</span>
      <KFIcon
        className={styles['parameter-range-title-icon']}
        type="icon-guanbi"
        font={17}
        onClick={onClose}
      />
    </Flex>
  );
}

export default PopParameterRange;
