// src/components/icon/IconifyPicker.tsx
import React, { useState, useEffect, useRef } from 'react';
import { Tabs, Divider, Row, Col, Typography, Card, Input } from 'antd';
import styled from 'styled-components';
import Image from 'next/image';

const { TabPane } = Tabs;
const { Text } = Typography;
const { Search } = Input;

// 一级分类类型定义
type MainCategoryKey = string;

// 二级分类类型定义
type SubCategoryKey = string;

// 本地 SVG 图标组件
interface IconProps {
  mainCategory: MainCategoryKey;
  subCategory: SubCategoryKey;
  name: string;
  size?: string;
}

const LocalSvgIcon = ({ mainCategory, subCategory, name, size = '32px' }: IconProps) => {
  // 将size字符串转换为数字，去掉单位
  const sizeNum = parseInt(size.replace(/px$/, ''), 10) || 32;
  
  return (
    <div style={{ display: 'block', margin: 'auto', width: size, height: size, position: 'relative' }}>
      <Image
        src={`/icons/${mainCategory}/${subCategory}/${name}.svg`}
        alt={name}
        width={sizeNum}
        height={sizeNum}
        style={{ objectFit: 'contain' }}
      />
    </div>
  );
};

// IconifyPicker 组件的 Props 定义
interface IconifyPickerProps {
  onIconSelect: (icon: { mainCategory: string; subCategory: string; name: string }) => void; // 回调函数
}

export const IconifyPicker = ({ onIconSelect }: IconifyPickerProps) => {
  const [mainCategories, setMainCategories] = useState<string[]>([]); // 一级分类
  const [activeMainCategory, setActiveMainCategory] = useState<MainCategoryKey | null>(null); // 当前选中的一级分类
  const [subCategories, setSubCategories] = useState<SubCategoryKey[]>([]); // 二级分类
  const [activeSubCategory, setActiveSubCategory] = useState<SubCategoryKey | null>(null); // 当前选中的二级分类
  const [iconsData, setIconsData] = useState<string[]>([]); // 图标列表
  const [filteredIcons, setFilteredIcons] = useState<string[]>([]); // 用于存储过滤后的图标
  const [searchTerm, setSearchTerm] = useState(''); // 搜索关键词
  const subCategoriesCache = useRef<Record<MainCategoryKey, SubCategoryKey[]>>({}); // 缓存二级分类
  const iconsCache = useRef<Record<MainCategoryKey, Record<SubCategoryKey, string[]>>>({}); // 缓存图标数据

  // 获取一级分类
  const fetchMainCategories = async () => {
    try {
      const response = await fetch(`/api/get-icons`);
      const data = await response.json();
      if (response.ok) {
        setMainCategories(data.mainCategories); // 使用正确的 API 字段
        if (data.mainCategories.length > 0) {
          setActiveMainCategory(data.mainCategories[0]); // 自动选择第一个一级分类
        }
      }
    } catch (error) {
      console.error('Failed to fetch main categories:', error);
    }
  };

  // 获取二级分类
  const fetchSubCategories = async (mainCategory: MainCategoryKey) => {
    // 如果缓存中有数据，直接使用缓存
    if (subCategoriesCache.current[mainCategory]) {
      setSubCategories(subCategoriesCache.current[mainCategory]);
      setActiveSubCategory(subCategoriesCache.current[mainCategory][0]);
      return;
    }

    try {
      const response = await fetch(`/api/get-icons?category=${mainCategory}`);
      const data = await response.json();
      if (response.ok) {
        subCategoriesCache.current[mainCategory] = data.subcategories; // 缓存二级分类
        setSubCategories(data.subcategories); // 设置二级分类
        if (data.subcategories.length > 0) {
          setActiveSubCategory(data.subcategories[0]); // 自动选择第一个二级分类
        }
      }
    } catch (error) {
      console.error('Failed to fetch subcategories:', error);
    }
  };

  // 获取图标列表
  const fetchIcons = async (mainCategory: MainCategoryKey, subCategory: SubCategoryKey) => {
    // 如果缓存中有图标数据，直接使用缓存
    if (iconsCache.current[mainCategory] && iconsCache.current[mainCategory][subCategory]) {
      setIconsData(iconsCache.current[mainCategory][subCategory]);
      setFilteredIcons(iconsCache.current[mainCategory][subCategory]);
      return;
    }

    try {
      const response = await fetch(`/api/get-icons?category=${mainCategory}&subcategory=${subCategory}`);
      const data = await response.json();
      if (response.ok) {
        if (!iconsCache.current[mainCategory]) {
          iconsCache.current[mainCategory] = {};
        }
        iconsCache.current[mainCategory][subCategory] = data.icons; // 缓存图标数据
        setIconsData(data.icons); // 设置图标列表
        setFilteredIcons(data.icons); // 初始化时显示所有图标
      }
    } catch (error) {
      console.error('Failed to fetch icons:', error);
    }
  };

  // 当页面加载时，获取一级分类
  useEffect(() => {
    fetchMainCategories();
  }, []);

  // 当用户切换一级分类时，获取二级分类
  useEffect(() => {
    if (activeMainCategory) {
      fetchSubCategories(activeMainCategory);
    }
  }, [activeMainCategory]);

  // 当用户切换二级分类时，获取该分类下的图标
  useEffect(() => {
    if (activeMainCategory && activeSubCategory) {
      fetchIcons(activeMainCategory, activeSubCategory);
    }
  }, [activeMainCategory, activeSubCategory]);

  // 当搜索内容变化时，过滤当前分类的图标
  useEffect(() => {
    const filtered = iconsData.filter((icon) =>
      icon.toLowerCase().includes(searchTerm.toLowerCase())
    );
    setFilteredIcons(filtered);
  }, [searchTerm, iconsData]);

  // 根据不同的图标库，生成带有前缀的图标名称
  const formatIconName = (mainCategory: string, iconName: string) => {
    if (mainCategory === 'font-awesome6') {
      return `fa6-brands:${iconName}`; // 根据 font-awesome6 格式化图标名称
    }
    // 默认返回 icon 名称
    return iconName;
  };

  // 处理图标选择
  const handleIconSelect = (name: string) => {
    if (activeMainCategory && activeSubCategory) {
      const formattedName = formatIconName(activeMainCategory, name); // 格式化图标名称
      onIconSelect({
        mainCategory: activeMainCategory,
        subCategory: activeSubCategory,
        name: formattedName, // 传递格式化后的名称
      });
    }
  };

  return (
    <Card title="图标选择" style={{ width: 500, margin: 'auto', marginTop: 20 }}>
      {/* 一级分类 */}
      <Tabs
        activeKey={activeMainCategory || undefined} // 确保 Tabs 激活
        onChange={(key) => setActiveMainCategory(key as MainCategoryKey)}
      >
        {mainCategories.map((mainCategory) => (
          <TabPane tab={<span>{mainCategory}</span>} key={mainCategory}>
            {/* 二级分类 */}
            {subCategories.length > 0 && (
              <Tabs
                activeKey={activeSubCategory || undefined} // 确保 Tabs 激活
                onChange={(key) => setActiveSubCategory(key as SubCategoryKey)}
              >
                {subCategories.map((subCategory) => (
                  <TabPane tab={<span>{subCategory}</span>} key={subCategory}>
                    {/* 搜索输入框 */}
                    <Search
                      placeholder="搜索图标"
                      onChange={(e) => setSearchTerm(e.target.value)} // 更新搜索关键词
                      style={{ marginBottom: '16px' }}
                      allowClear
                    />
                    {/* 图标列表 */}
                    <StyledIconList>
                      <Row gutter={[8, 8]}>
                        {filteredIcons.length > 0 ? (
                          filteredIcons.map((iconName) => (
                            <Col span={4} key={iconName}>
                              <StyledIconWrapper
                                onClick={() => handleIconSelect(iconName)}
                              >
                                <LocalSvgIcon
                                  mainCategory={activeMainCategory!}
                                  subCategory={activeSubCategory!}
                                  name={iconName}
                                  size="32px"
                                />
                              </StyledIconWrapper>
                            </Col>
                          ))
                        ) : (
                          <Text>未找到图标</Text>
                        )}
                      </Row>
                    </StyledIconList>
                  </TabPane>
                ))}
              </Tabs>
            )}
          </TabPane>
        ))}
      </Tabs>
      <Divider />
    </Card>
  );
};

// 样式组件
const StyledIconList = styled.div`
  padding: 16px;
  max-height: calc(32px * 7 + 16px * 7); /* 限制7行的高度 */
  overflow-y: auto; /* 超出的部分滚动显示 */
`;

const StyledIconWrapper = styled.div`
  padding: 8px;
  text-align: center;
  cursor: pointer;
  border: 2px solid transparent;
  border-radius: 4px;
  transition: border-color 0.3s;

  &:hover {
    border-color: #1890ff;
  }
`;
