// GroupTagModal.tsx - 修复死循环问题

import { Modal } from 'antd';
import React, { useCallback, useEffect, useState } from 'react';
import GroupTagCore from './GroupTagCore';
import type { GroupTagModalProps, TagItem } from './types';

const GroupTagModal: React.FC<GroupTagModalProps> = ({
  visible,
  title,
  width,
  editable,
  request,
  onCancel,
  onChange,
}) => {
  const [data, setData] = useState<TagItem[]>([]);

  const handleOk = () => {
    if (onChange) {
      // const ids = data.map((item) => item.id);
      onChange(data);
    }

    onCancel();
  };

  useEffect(() => {
    if (!visible) {
      setData([]);
    }
  }, [visible]);

  const handleChange = useCallback(
    (data: TagItem[]) => {
      setData(data);
    },
    [data],
  );

  return (
    <Modal
      title={title}
      open={visible}
      onCancel={onCancel}
      onOk={handleOk}
      width={width}
      okText="确定"
      cancelText="取消"
      destroyOnHidden
      maskClosable={false}
    >
      <GroupTagCore
        value={data}
        requset={request}
        editable={editable}
        onChange={handleChange}
      />
    </Modal>
  );
};

export default GroupTagModal;
