// GroupTagCore.tsx - 修复缺失函数和API参数

import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
import {
  Button,
  type CheckboxChangeEvent,
  Input,
  message,
  Space,
  Spin,
} from 'antd';
import React, { useCallback, useEffect, useState } from 'react';
import type { GroupItem, GroupTagCoreProps, TagItem } from './types';
import './GroupTagCore.less';
import { renderGroups, renderTags } from './component';
import TagsModal from './TagsModal';

const GroupTagCore: React.FC<GroupTagCoreProps> = (props) => {
  const {
    requset: { groupsApi, tagsApi },
    editable = false,
    value = [],
    onChange,
  } = props;
  const [isInEditMode, _setIsInEditMode] = useState<boolean>(false);
  // 编辑状态
  const [loading, setLoading] = useState<boolean>(false);
  const [loadingTags, setLoadingTags] = useState<boolean>(false);
  const [groups, setGroups] = useState<GroupItem[]>([]);
  const [currentGroup, setCurrentGroup] = useState<GroupItem>();
  const [modalType, setModalType] = useState<'add' | 'edit' | 'delete'>();
  const [type, setType] = useState<'group' | 'tag'>('group');
  const [visible, setVisible] = useState<boolean>(false);
  const [name, setName] = useState<string>('');
  const [tagName, setTagName] = useState<string>('');
  const [total, setTotal] = useState<number>(0);
  const [currentId, setCurrentId] = useState<number>();
  const [tagsModalValue, setTagsModalValue] = useState<{
    tagName?: string;
    groupName?: string;
    groupIds?: number[];
    id?: number;
  }>({});
  const [pageNo, setPageNo] = useState<number>(1);
  const fetchGroups = useCallback(async () => {
    try {
      setLoading(true);
      const groups = await groupsApi.get();
      groups.length && setCurrentGroup(groups[0]);
      setGroups(groups);
      setCurrentId(groups[0].id);
    } finally {
      setLoading(false);
    }
  }, [groupsApi]);

  const fetchTagsApi = useCallback(async () => {
    try {
      setLoadingTags(true);
      const res = await tagsApi.get({
        groupId: currentId,
        pageNo: 1,
        tagName: tagName,
      });
      const newGroup = { ...currentGroup, tags: res.list };
      const newData = groups.map((g) => (g.id === currentId ? newGroup : g));
      setGroups(newData as GroupItem[]);
      setCurrentGroup(newGroup as GroupItem);
      setTotal(res.total);
      setPageNo(1);
    } finally {
      setLoadingTags(false);
    }
  }, [tagsApi, groups, currentId]);
  useEffect(() => {
    fetchGroups();
  }, []);

  useEffect(() => {
    if (currentId) {
      fetchTagsApi();
    }
  }, [currentId]);

  const onGroupClick = (group: GroupItem) => {
    if (currentId !== group.id) {
      setCurrentId(group.id);
      setCurrentGroup(group);
    }
  };

  useEffect(() => {
    if (modalType === 'edit' && visible) {
      if (type === 'group' && currentGroup) {
        setName(currentGroup.groupName || '');
      } else if (type === 'tag' && tagsModalValue) {
        setName(tagsModalValue.tagName || '');
      }
    }
    if (modalType === 'add') {
      setName('');
    }
  }, [type, modalType, currentGroup, tagsModalValue, visible]);
  const handleGroup = (type: 'add' | 'edit' | 'delete', group?: GroupItem) => {
    setType('group');
    setModalType(type);
    if (type === 'add' || type === 'edit') {
      setVisible(true);
    }
    if (type === 'edit') {
      console.log('group', group);
      setTagsModalValue({ groupName: group?.groupName, id: group?.id });
    }
  };

  const handleTag = (type: 'add' | 'edit' | 'delete', tag?: TagItem) => {
    setType('tag');
    setModalType(type);
    if (type === 'add' || type === 'edit') {
      setVisible(true);
    }
    if (type === 'edit') {
      setTagsModalValue({ tagName: tag?.tagName, id: tag?.id });
    }
  };

  const handleAdd = async (value: {
    groupIds?: number[];
    groupName?: string;
  }) => {
    if (type === 'group') {
      const id = await groupsApi.create({ groupName: value.groupName });
      setGroups([{ id, groupName: value.groupName || '' }, ...groups]);
    } else {
      await tagsApi.create(value);
      message.success('添加成功');
      fetchTagsApi();
    }
    setVisible(false);
  };

  const handleEdit = async (value: {
    tagName?: string;
    groupName?: string;
    groupIds?: number[];
  }) => {
    if (type === 'group') {
      try {
        await groupsApi.update({
          id: currentGroup?.id,
          groupName: value.groupName,
        });
        const newData = groups.map((item) => {
          if (item.id === currentGroup?.id) {
            const itemData = { ...item, groupName: value.groupName };
            setCurrentGroup(itemData);
            return itemData;
          } else {
            return item;
          }
        });
        setGroups(newData);
      } catch (error) {
        message.success('修改失败');
      }
    } else {
      await tagsApi.update({
        groupIds: [currentGroup?.id],
        id: tagsModalValue?.id,
        ...value,
      });
      fetchTagsApi();
    }
    setVisible(false);
    message.success('修改成功');
  };

  const handleDelete = async (type: 'group' | 'tag', id: number) => {
    if (type === 'group' && currentGroup) {
      await groupsApi.delete(id);
      const newGroups = groups.filter((group) => group.id !== id);
      setGroups(newGroups);
      if (id === currentId) {
        setCurrentId(newGroups[0].id);
        setCurrentGroup(newGroups[0]);
      }
    } else {
      await tagsApi.delete(id);
      fetchTagsApi();
    }
  };

  const handleConfirm = useCallback(
    async (value: { groupIds?: number[]; name?: string }) => {
      if (modalType === 'add') {
        await handleAdd(value);
      }

      if (modalType === 'edit') {
        await handleEdit(value);
      }
    },
    [visible, type, modalType],
  );

  const handleCancle = useCallback(() => {
    setVisible(false);
    setTagsModalValue({});
  }, [visible]);

  const onTagItemChange = (tag: TagItem, e: CheckboxChangeEvent) => {
    if (e.target.checked) {
      const data = [...value, tag];
      onChange?.(data);
    } else if (!editable) {
      const data = value.filter((item) => item.id !== tag.id);
      onChange?.(data);
    }
  };

  const loadMoreData = async () => {
    const res = await tagsApi.get({ groupId: currentId, pageNo: pageNo + 1 });
    if (res.list.length === 0) {
      return;
    }

    const newGroup = {
      ...currentGroup,
      tags: [...(currentGroup?.tags || []), ...res.list],
    };
    setCurrentGroup(newGroup as GroupItem);
    setPageNo((prev) => prev + 1);
  };

  const onSearchTags = async (e: React.KeyboardEvent<HTMLInputElement>) => {
    const searchValue = (e.target as HTMLInputElement).value;
    setTagName(searchValue);
    const res = await tagsApi.get({
      groupId: currentId,
      pageNo: 1,
      tagName: searchValue,
    });
    const newGroup = {
      ...currentGroup,
      tags: res.list,
    };
    setTotal(res.total);
    document.getElementById('scrollableDiv')?.scrollTo(0, 0);
    setCurrentGroup(newGroup as GroupItem);
    setPageNo(1);
  };
  const onSearchTagsClear = async () => {
    setTagName('');
    fetchTagsApi();
  };
  return (
    <div className={`group-tag-core`}>
      <div className="search-wrapper">
        <Input
          prefix={<SearchOutlined />}
          placeholder="搜索"
          onPressEnter={onSearchTags}
          allowClear
          onClear={onSearchTagsClear}
          disabled={isInEditMode}
        />
      </div>

      <div className="content-wrapper">
        {loading ? (
          <div className="loading-wrapper">
            <Spin />
            <div style={{ marginTop: 8 }}>加载数据中...</div>
          </div>
        ) : (
          <div className="split-layout">
            {/* 左侧分组列表 */}
            <div className="groups-panel">
              <div className="panel-header">
                <span>分组</span>
                {editable && !isInEditMode && (
                  <Button
                    type="text"
                    size="small"
                    icon={<PlusOutlined />}
                    onClick={() => handleGroup('add')}
                  >
                    添加
                  </Button>
                )}
              </div>
              <div className="groups-list">
                {renderGroups({
                  editable,
                  groups,
                  currentId,
                  onGroupClick,
                  onEdit: (groud) => handleGroup('edit', groud),
                  onDelete: (id) => handleDelete('group', id),
                })}
              </div>
            </div>

            {/* 右侧标签列表 */}
            <div className="tags-panel">
              <div className="panel-header">
                <span>标签</span>
                <Space>
                  {editable && currentGroup && !isInEditMode && (
                    <Button
                      type="text"
                      size="small"
                      icon={<PlusOutlined />}
                      onClick={() => handleTag('add')}
                    >
                      添加
                    </Button>
                  )}
                </Space>
              </div>

              <div className="tags-list" id="scrollableDiv">
                <Spin spinning={loadingTags}>
                  {renderTags({
                    editable,
                    value,
                    list: currentGroup?.tags ?? [],
                    total,
                    loadMoreData,
                    onEdit: (tag) => handleTag('edit', tag),
                    onDelete: (id) => handleDelete('tag', id),
                    onTagItemChange: onTagItemChange,
                  })}
                </Spin>
              </div>
            </div>
          </div>
        )}
      </div>
      {/* 添加标签Modal */}
      <TagsModal
        value={tagsModalValue}
        visible={visible}
        type={type}
        modalType={modalType}
        onCancel={handleCancle}
        onConfirm={handleConfirm}
        groups={groups}
      />
    </div>
  );
};

export default GroupTagCore;
