import { DeleteOutlined, SearchOutlined } from "@ant-design/icons";
import { Button, Input, Popconfirm } from "antd";
import React, { useEffect, useState } from "react";
import CustomColorPicker from "@/components/CustomColorPicker";
import { useModel } from "umi";
import noData from "@/assets/no-data.png";

export default function ThemePanel() {
  const { project, addTopicArea, deleteTopicArea, updateTopicArea } = useModel("erModel");

  const { topicAreas = [] } = project;
  const [search, setSearch] = React.useState("");
  const [topicAreaList, setTopicAreaList] = useState(topicAreas);

  useEffect(() => {
    setTopicAreaList(topicAreas.filter(item => item.name.includes(search)));
  }, [topicAreas, search]);
  
  const handleChange = (index: number, key: string, value: any) => {
    const data = topicAreas[index];
    const newData = { ...data, [key]: value };
    updateTopicArea(newData);
    setTopicAreaList(topicAreas.map((item, i) => (i === index ? newData : item)));
  };

  return (
    <div className="px-12px">
      <div className="flex gap-12px">
        <Input
          placeholder="输入关键字搜索"
          className="m-b-10px"
          suffix={<SearchOutlined />}
          value={search}
          onChange={(e) => setSearch(e.target.value)}
        />
        <Button type="primary" onClick={addTopicArea}>
          添加区域
        </Button>
      </div>
      {topicAreaList.map((item, index) => {
        return (
          <div key={item.id} className="m-b-10px flex justify-between gap-12px">
            <Input placeholder="主题名称" value={item.name} onChange={(e) => handleChange(index, 'name', e.target.value)}/>
            <CustomColorPicker
              color={item.style.background}
              onChange={(color) => {handleChange(index, 'style', {...item.style, background: color})}}
            >
              <div
                className="rounded-4px cus-btn w-32px h-32px bg-#eee flex-none cursor-pointer shadow-inner"
                style={{ background: item.style.background }}
              ></div>
            </CustomColorPicker>
            <Popconfirm
              okType="primary"
              title="确定删除该主题区域？"
              okText="确定"
              cancelText="取消"
              onConfirm={() => deleteTopicArea(item.id)}
            >
              <div className="rounded-4px cus-btn w-32px h-32px bg-#eee flex-none cursor-pointer text-center leading-32px color-red">
                <DeleteOutlined />
              </div>
            </Popconfirm>
          </div>
        );
      })}
      {
        topicAreaList.length === 0 && (
          <div className="flex flex-col items-center justify-center h-[300px]">
            <img src={noData} alt="暂无数据" className="w-[200px] h-[200px]" />
            <div className="text-gray-400">添加主题区域对表进行分组！</div>
          </div>
        )
      }
    </div>
  );
}
