// GroupTagSelect.tsx - 适配真实数据结构

import { Select, Tag } from 'antd';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import GroupTagCore from './GroupTagCore';
import type { GroupTagSelectProps, TagItem } from './types';
import './GroupTagSelect.less';

const GroupTagSelect: React.FC<GroupTagSelectProps> = ({
  value = [],
  onChange,
  placeholder = '请选择标签',
  className = '',
  request,
  editable = false,
}) => {
  const [dropdownVisible, setDropdownVisible] = useState(false);
  const [selectedTags, setSelectedTags] = useState<TagItem[]>([]);

  useEffect(() => {
    const v = selectedTags.map((tag) => tag.id);
    onChange?.(v);
  }, [selectedTags]);
  const onTagsItem = (value: TagItem[]) => {
    console.log(value, 'value');
    setSelectedTags(value);
  };
  // 渲染下拉内容
  const dropdownRender = useCallback(
    () => (
      <GroupTagCore
        value={selectedTags}
        requset={request}
        editable={false}
        onChange={onTagsItem}
      />
    ),
    [selectedTags, request, editable],
  );

  // const

  // 获取选中标签的详细信息
  const options = useMemo(() => {
    return selectedTags.map((item: TagItem) => ({
      ...item,
      label: item.tagName,
      value: item.id,
    }));
  }, [selectedTags]);
  return (
    <div className={`group-tag-select-wrapper ${className}`}>
      <Select
        mode="multiple"
        value={value}
        fieldNames={{ label: 'tagName', value: 'id' }}
        onChange={(newValue) => {
          // console.log(newValue, "newValue");
          const selectedItems = options.filter((option) =>
            newValue.includes(option.id),
          );
          setSelectedTags(selectedItems);
          onChange?.(selectedItems as unknown as number[]);
        }}
        placeholder={placeholder}
        className="group-tag-select"
        popupRender={dropdownRender}
        classNames={{
          popup: {
            root: 'group-tag-select-dropdown-wrapper',
          },
        }}
        popupMatchSelectWidth={false}
        dropdownStyle={{
          width: 600,
          minWidth: 600,
        }}
        options={options}
        tagRender={(props) => {
          const { label, closable, onClose } = props;
          console.log(props);
          return (
            <Tag closable={closable} onClose={onClose} className="selected-tag">
              {label}
            </Tag>
          );
        }}
        showSearch={false}
        onSelect={() => {}}
        onDeselect={() => {}}
        allowClear={true}
        onClear={() => setSelectedTags([])}
        open={dropdownVisible}
        onOpenChange={setDropdownVisible}
      />
    </div>
  );
};

export default GroupTagSelect;
