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/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("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 || [])]);
    }
  };

  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) => (
                <CustomTag key={item.name} color={item.color}>
                  {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) => (
                <CustomTag
                  key={item.name}
                  color={item.color}
                  onClick={() => handleAddTag(item)}
                >
                  {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
                key={item.name}
                color={item.color}
                onClick={() => handleAddTag(item, true)}
              >
                {item.name}
              </CustomTag>
            ))}
          </div>
        </div>
      </Tabs.TabPane>
    </Tabs>
  );
}
