import { useState, useEffect } from 'react'
import { Outlet, NavLink, useLocation } from 'react-router'
import {
  CircleArrowRight,
  CircleArrowLeft,
  Database,
  SearchCheck,
  Filter,
  Bolt,
  Cone,
  ChartArea,
  Wallpaper,
} from 'lucide-react'
import { Menu, MenuProps } from 'antd'
import './DataLayout.scss'
import AIChat from '@/ai/AIChat'

type MyMenuItem = {
  name: string
  path: string
  children?: MyMenuItem[]
  disabled?: boolean
  icon?: React.ReactNode
}

type MenuItem = Required<MenuProps>['items'][number]

const menus: MyMenuItem[] = [
  {
    icon: <Database />,
    name: '数据采集',
    path: '/data/write',
    children: [
      { name: '我的数据集', path: '/data/write/my' },
      { name: '数据复制', path: '/data/write/copy' },
      { name: '数据导入', path: '/data/write/upload' },
      { name: '数据爬虫', path: '/data/write/crawler', disabled: true },
      { name: 'API数据采集', path: '/data/write/api', disabled: true },
      { name: '数据库对接', path: '/data/write/db', disabled: true },
      { name: '内置数据集管理', path: '/data/write/built' },
    ],
  },
  {
    icon: <SearchCheck />,
    name: '数据理解与探索',
    path: '/data/read',
    children: [
      { name: '数据理解', path: '/data/read/understanding' },
      { name: '数据探索', path: '/data/read/exploration' },
    ],
  },
  {
    icon: <Filter />,
    name: '数据预处理',
    path: '/data/preprocess',
    children: [
      { name: '缺失值处理', path: '/data/preprocess/null' },
      { name: '重复值处理', path: '/data/preprocess/repeat' },
      { name: '过大值处理', path: '/data/preprocess/max' },
      { name: '过小值处理', path: '/data/preprocess/min' },
      { name: '逻辑错误值处理', path: '/data/preprocess/error' },
      { name: '数据拆分', path: '/data/preprocess/split' },
      { name: '数据去空格', path: '/data/preprocess/space' },
      { name: '数据去标点', path: '/data/preprocess/symbol' },
      { name: '数据类型转换', path: '/data/preprocess/type' },
      { name: '数据排序', path: '/data/preprocess/sort' },
      { name: '数据拼接', path: '/data/preprocess/splice' },
    ],
  },
  {
    icon: <Bolt />,
    name: '数据加工',
    path: '/data/process',
    children: [
      { name: '值映射', path: '/data/process/mapping' },
      { name: '数据分箱', path: '/data/process/binning' },
      { name: '数据分组', path: '/data/process/group' },
      { name: '数据脱敏', path: '/data/process/desensitization' },
      { name: '日期计算', path: '/data/process/date' },
      { name: '文本计算', path: '/data/process/string' },
      { name: '数值计算', path: '/data/process/number' },
      { name: '逻辑计算', path: '/data/process/logic' },
      // { name: '数据透视', path: '/data/process/perspective', disabled: true },
    ],
  },
  {
    icon: <Cone />,
    name: '数据挖掘',
    path: '/data/digging',
    children: [
      { name: '线性回归', path: '/data/digging/linear' },
      { name: '逻辑回归', path: '/data/digging/logistic' },
      { name: '决策树', path: '/data/digging/tree' },
      { name: '随机森林', path: '/data/digging/forest' },
      { name: '支持向量机', path: '/data/digging/svm' },
      { name: 'K-Means', path: '/data/digging/kmeans' },
      { name: '层次聚类', path: '/data/digging/hierarchical' },
      { name: 'Apriori', path: '/data/digging/apriori' },
      { name: 'FP-Growth', path: '/data/digging/fpgrowth' },
      { name: 'Holt-Winters', path: '/data/digging/holtwinters' },
    ],
  },
  {
    icon: <ChartArea />,
    name: '数据可视化组件',
    path: '/data/chart',
    children: [
      { name: '柱状图', path: '/data/chart/bar' },
      { name: '折线图', path: '/data/chart/line' },
      { name: '饼状图', path: '/data/chart/pie' },
      { name: '雷达图', path: '/data/chart/radar' },
      { name: '散点图', path: '/data/chart/point' },
      { name: '气泡图', path: '/data/chart/bubble' },
      { name: '词云', path: '/data/chart/wordCloud' },
      { name: '地图', path: '/data/chart/map', disabled: true },
      { name: '指标卡', path: '/data/chart/indicator' },
      { name: '漏斗图', path: '/data/chart/funnel' },
      { name: '直方图', path: '/data/chart/histogram' },
      { name: '表格', path: '/data/chart/table' },
      { name: '帕累托图', path: '/data/chart/pareto' },
      { name: '矩形树图', path: '/data/chart/treeMap' },
    ],
  },
  {
    icon: <Wallpaper />,
    name: '数据可视化大屏',
    path: '/data/screen',
  },
]

export default function DataLayout() {
  const [collapsed, setCollapsed] = useState(false)
  const [openKeys, setOpenKeys] = useState<string[]>([])

  const toggleCollapsed = () => {
    setCollapsed(!collapsed)
  }

  const location = useLocation()
  const selectedKeys = [location.pathname]

  useEffect(() => {
    // 根据当前路径计算需要展开的菜单项
    const calculateOpenKeys = (menus: MyMenuItem[]): string[] => {
      for (const menu of menus) {
        if (menu.children) {
          if (menu.children.some((child) => child.path === location.pathname)) {
            return [menu.path]
          }
          const result = calculateOpenKeys(menu.children)
          if (result.length > 0) {
            return [menu.path, ...result]
          }
        }
      }
      return []
    }
    setOpenKeys(calculateOpenKeys(menus))
  }, [location.pathname])

  const menusToMenuItems = (menus: MyMenuItem[]): MenuItem[] => {
    return menus.map((item) => {
      if (item.children) {
        return {
          ...item,
          label: item.name,
          key: item.path,
          children: menusToMenuItems(item.children),
        }
      }
      return {
        ...item,
        label: <NavLink to={item.path}>{item.name}</NavLink>,
        key: item.path,
      }
    })
  }

  const items = menusToMenuItems(menus)

  const onOpenChange = (keys: string[]) => {
    if (keys.length > 1) {
      setOpenKeys([keys[keys.length - 1]])
    } else {
      setOpenKeys(keys)
    }
  }

  return (
    <div className={`data-layout ${collapsed ? 'collapsed' : ''}`}>
      <div className="data-layout-sidebar">
        <div className="data-layout-sidebar-header">
          {collapsed ? '' : <h2>AI数据分析功能区</h2>}
          <span onClick={toggleCollapsed}>{collapsed ? <CircleArrowRight /> : <CircleArrowLeft />}</span>
        </div>
        <div className="data-layout-sidebar-nav">
          <Menu
            items={items}
            mode="inline"
            inlineCollapsed={collapsed}
            selectedKeys={selectedKeys}
            openKeys={openKeys}
            onOpenChange={onOpenChange}
          />
        </div>
      </div>
      <div className="data-layout-container">
        <Outlet />
      </div>
      <AIChat></AIChat>
    </div>
  )
}
