import CustomColorPicker from "@/components/CustomColorPicker";
import { useLocalStorageState } from "ahooks";
import { Tabs, Input } from "antd";
import React, { useEffect, useState } from "react";
import { useModel } from "umi";
import CustomTag from "@/components/mindMap/CustomTag";

interface TagItem {
  name: string;
  color: string;
}
// 我的标签 存服务器
const defaultTags: TagItem[] = [
  { name: "待定", color: "#6e4dbe" },
  { name: "已确认", color: "rgb(80, 194, 139)" },
  { name: "已完成", color: "rgb(109, 109, 109)" },
  { name: "已关闭", color: "rgb(196, 196, 196)" },
  { name: "进行中", color: "rgb(39, 96, 242)" },
];
export default function TagConfig() {
  const { selectedCell } = useModel("mindmap.mindMapModel");
  const [newTag, setNewTag] = useState<TagItem>({
    name: "",
    color: "#EC7270",
  });
  const [recentTags, setRecentTags] = useLocalStorageState<TagItem[]>(
    "recentTags",
    {
      defaultValue: [],
      listenStorageChange: true,
    }
  );
  const [currentTags, setCurrentTags] = useState<TagItem[]>([]);

  useEffect(() => {
    if (selectedCell) {
      const firstNode = selectedCell.find((item) => item.isNode());
      const tags = firstNode?.getData()?.tags || [];
      setCurrentTags(tags);
    }
  }, [selectedCell]);
  const handleAddTag = (tag: TagItem, ignore = false) => {
    if (!tag) return;
    if (currentTags.find((item) => item.name === tag.name)) return;

    selectedCell.forEach((cell) => {
      if (cell.isNode()) {
        const tags = cell.getData()?.tags || [];
        cell.setData({
          tags: [...tags, tag],
        });
      }
    });

    setCurrentTags((state) => [...state, tag]);
    setNewTag((state) => ({ ...state, name: "" }));
    if (!recentTags?.find((item) => item.name === tag.name) && !ignore) {
      setRecentTags([tag, ...(recentTags || [])]);
    }
  };

  const handleCurrentChange = (tag: TagItem, index: number) => {
    const firstNode = selectedCell.find((item) => item.isNode());
    console.log(tag)
    const tags = (firstNode?.data?.tags || []).map((item: TagItem, i: number) => {
      if (index === i) {
        return {
          ...item,
          ...tag
        };
      }
      return item
    });
    setCurrentTags(tags);
    firstNode?.setData({
      tags,
    }, {
      deep: false
    })
  };

  const handleCurrentDelete = (index: number) => {
    const firstNode = selectedCell.find((item) => item.isNode());
    const tags =  firstNode?.data?.tags?.filter((item: TagItem, i: number) => index !== i);
    setCurrentTags(tags);
    firstNode?.setData({
      tags
    }, {
      deep: false
    })
  }

  const handleRecentChange = (tag: TagItem, index: number) => {
    setRecentTags(recentTags?.map((item: TagItem, i: number) => {
      if (i === index) {
        return {
          ...item,
          ...tag
        };
      } else {
        return item;
      }
    }))
  };

  const handleRecentDelete = (index: number) => {
    setRecentTags(recentTags?.filter((item: TagItem, i: number) => i !== index))
  }

  return (
    <Tabs>
      <Tabs.TabPane key="1" tab="标签">
        <div
          className={`px-8px ${!selectedCell.length ? "opacity-50 pointer-events-none" : ""}`}
        >
          <div className="text-14px color-#000 font-bold my-8px mt-0">
            当前标签
          </div>
          <div className="flex flex-wrap gap-4px">
            {currentTags.length ? (
              currentTags.map((item, index) => (
                <CustomTag
                  key={item.name}
                  title={item.name}
                  color={item.color}
                  onChangeTag={(tag) => handleCurrentChange(tag, index)}
                  onDelete={() => handleCurrentDelete(index)}
                >
                  {item.name}
                </CustomTag>
              ))
            ) : (
              <span className="text-12px color-#999">
                暂无标签，请在下方输入创建
              </span>
            )}
          </div>
          <div className="text-14px color-#000 font-bold my-8px mt-16px">
            创建标签
          </div>
          <div className="flex items-center gap-8px">
            <CustomColorPicker
              color={newTag.color}
              onChange={(color) => setNewTag((state) => ({ ...state, color }))}
            />
            <Input
              className="flex-1"
              maxLength={20}
              placeholder="不超过20个字,回车添加"
              value={newTag.name}
              onChange={(e) =>
                setNewTag((state) => ({ ...state, name: e.target.value }))
              }
              onPressEnter={() => newTag.name && handleAddTag(newTag)}
              onBlur={() => newTag.name && handleAddTag(newTag)}
            />
          </div>
          <div className="text-12px color-#999 my-8px mt-16px">最近标签</div>
          <div className="flex flex-wrap gap-4px">
            {recentTags?.length ? (
              recentTags.map((item, index) => (
                <CustomTag
                  key={item.name}
                  color={item.color}
                  title={item.name}
                  onClick={() => handleAddTag(item)}
                  onChangeTag={(tag) => handleRecentChange(tag, index)}
                  onDelete={() => handleRecentDelete(index)}
                >
                  {item.name}
                </CustomTag>
              ))
            ) : (
              <span className="text-12px color-#999">暂无最近标签</span>
            )}
          </div>

          <div className="text-12px color-#999 my-8px mt-16px">我的标签</div>
          <div className="flex flex-wrap gap-4px">
            {defaultTags.map((item) => (
              <CustomTag
                hideAdd
                key={item.name}
                color={item.color}
                title={item.name}
                onClick={() => handleAddTag(item, true)}
                onChangeTag={() => {}}
              >
                {item.name}
              </CustomTag>
            ))}
          </div>
        </div>
      </Tabs.TabPane>
    </Tabs>
  );
}
