'use client';

import { useState, useEffect } from 'react';
import { toast } from 'sonner';

import { MenuManagementHeader } from './components/MenuManagementHeader';
import { MenuManagementStatsCards } from './components/MenuManagementStatsCards';
import { MenuTree } from './components/MenuTree';
import { MenuFormDialog } from './components/MenuFormDialog';
import { MenuManagementInstructions } from './components/MenuManagementInstructions';
import { Menu, MenuType } from './types';

/**
 * 菜单管理页面组件
 * 提供菜单的增删改查、展开折叠等功能
 */
export default function MenuManagementPage() {
  // 菜单列表状态
  const [menus, setMenus] = useState<Menu[]>([]);
  // 展开的菜单ID集合
  const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());
  // 控制表单显示状态
  const [showForm, setShowForm] = useState(false);
  // 当前编辑的菜单
  const [editingMenu, setEditingMenu] = useState<Menu | null>(null);
  // 父级菜单
  const [parentMenu, setParentMenu] = useState<Menu | null>(null);
  // 表单数据
  const [formData, setFormData] = useState<Partial<Menu>>({
    type: 'menu',
    visible: true,
    status: 'active',
    sort: 0,
  });

  // 组件挂载时加载菜单数据
  useEffect(() => {
    loadMenus();
  }, []);

  /**
   * 加载菜单数据
   * 优先从localStorage读取，若不存在则使用示例数据
   */
  const loadMenus = () => {
    const data = localStorage.getItem('smart_agriculture_menus');
    if (data) {
      setMenus(JSON.parse(data));
    } else {
      // 初始化示例数据 - 三级菜单结构
      const mockMenus: Menu[] = [
        {
          id: 'menu-1',
          name: '智能农机管理系统',
          code: 'machinery',
          icon: 'Tractor',
          type: 'directory',
          sort: 1,
          visible: true,
          status: 'active',
          children: [
            {
              id: 'menu-1-1',
              parentId: 'menu-1',
              name: '农机档案',
              code: 'machinery:archive',
              icon: 'Archive',
              type: 'directory',
              sort: 1,
              visible: true,
              status: 'active',
              children: [
                {
                  id: 'menu-1-1-1',
                  parentId: 'menu-1-1',
                  name: '农机录入',
                  code: 'machinery:archive:entry',
                  path: '/machinery/archive/entry',
                  type: 'menu',
                  sort: 1,
                  visible: true,
                  status: 'active',
                },
                {
                  id: 'menu-1-1-2',
                  parentId: 'menu-1-1',
                  name: '农机分类',
                  code: 'machinery:archive:classification',
                  path: '/machinery/archive/classification',
                  type: 'menu',
                  sort: 2,
                  visible: true,
                  status: 'active',
                },
                {
                  id: 'menu-1-1-3',
                  parentId: 'menu-1-1',
                  name: '二维码管理',
                  code: 'machinery:archive:qrcode',
                  path: '/machinery/archive/qrcode',
                  type: 'menu',
                  sort: 3,
                  visible: true,
                  status: 'active',
                },
              ],
            },
            {
              id: 'menu-1-2',
              parentId: 'menu-1',
              name: '驾驶员管理',
              code: 'machinery:driver',
              icon: 'User',
              type: 'directory',
              sort: 2,
              visible: true,
              status: 'active',
              children: [
                {
                  id: 'menu-1-2-1',
                  parentId: 'menu-1-2',
                  name: '驾驶员信息',
                  code: 'machinery:driver:info',
                  path: '/machinery/driver/info',
                  type: 'menu',
                  sort: 1,
                  visible: true,
                  status: 'active',
                },
                {
                  id: 'menu-1-2-2',
                  parentId: 'menu-1-2',
                  name: '任务管理',
                  code: 'machinery:driver:task',
                  path: '/machinery/driver/task',
                  type: 'menu',
                  sort: 2,
                  visible: true,
                  status: 'active',
                },
              ],
            },
          ],
        },
        {
          id: 'menu-2',
          name: '中心配置管理系统',
          code: 'config',
          icon: 'Settings',
          type: 'directory',
          sort: 7,
          visible: true,
          status: 'active',
          children: [
            {
              id: 'menu-2-1',
              parentId: 'menu-2',
              name: '租户管理',
              code: 'config:tenant',
              icon: 'Building2',
              type: 'directory',
              sort: 1,
              visible: true,
              status: 'active',
              children: [
                {
                  id: 'menu-2-1-1',
                  parentId: 'menu-2-1',
                  name: '企业信息',
                  code: 'config:tenant:enterprise',
                  path: '/config/tenant/enterprise',
                  type: 'menu',
                  sort: 1,
                  visible: true,
                  status: 'active',
                },
                {
                  id: 'menu-2-1-2',
                  parentId: 'menu-2-1',
                  name: '企业审核',
                  code: 'config:tenant:audit',
                  path: '/config/tenant/audit',
                  type: 'menu',
                  sort: 2,
                  visible: true,
                  status: 'active',
                },
              ],
            },
            {
              id: 'menu-2-2',
              parentId: 'menu-2',
              name: '用户管理',
              code: 'config:user',
              icon: 'Users',
              type: 'directory',
              sort: 2,
              visible: true,
              status: 'active',
              children: [
                {
                  id: 'menu-2-2-1',
                  parentId: 'menu-2-2',
                  name: '员工管理',
                  code: 'config:user:employee',
                  path: '/config/user/employee',
                  type: 'menu',
                  sort: 1,
                  visible: true,
                  status: 'active',
                },
                {
                  id: 'menu-2-2-2',
                  parentId: 'menu-2-2',
                  name: '角色管理',
                  code: 'config:user:role',
                  path: '/config/user/role',
                  type: 'menu',
                  sort: 2,
                  visible: true,
                  status: 'active',
                },
                {
                  id: 'menu-2-2-3',
                  parentId: 'menu-2-2',
                  name: '菜单管理',
                  code: 'config:user:menu',
                  path: '/config/user/menu',
                  type: 'menu',
                  sort: 3,
                  visible: true,
                  status: 'active',
                },
                {
                  id: 'menu-2-2-4',
                  parentId: 'menu-2-2',
                  name: '权限管理',
                  code: 'config:user:permission',
                  path: '/config/user/permission',
                  type: 'menu',
                  sort: 4,
                  visible: true,
                  status: 'active',
                },
              ],
            },
          ],
        },
      ];
      localStorage.setItem('smart_agriculture_menus', JSON.stringify(mockMenus));
      setMenus(mockMenus);
      // 默认展开所有一级菜单
      setExpandedIds(new Set(mockMenus.map(m => m.id)));
    }
  };

  const toggleExpand = (id: string) => {
    const newExpanded = new Set(expandedIds);
    if (newExpanded.has(id)) {
      newExpanded.delete(id);
    } else {
      newExpanded.add(id);
    }
    setExpandedIds(newExpanded);
  };

  const expandAll = () => {
    const getAllMenuIds = (menus: Menu[]): string[] => {
      let ids: string[] = [];
      menus.forEach(menu => {
        if (menu.children && menu.children.length > 0) {
          ids.push(menu.id);
          ids.push(...getAllMenuIds(menu.children));
        }
      });
      return ids;
    };
    setExpandedIds(new Set(getAllMenuIds(menus)));
  };

  const collapseAll = () => {
    setExpandedIds(new Set());
  };

  const handleAdd = (parent?: Menu) => {
    setEditingMenu(null);
    setParentMenu(parent || null);

    // 根据父菜单决定默认类型
    let defaultType: MenuType = 'menu';
    if (!parent) {
      defaultType = 'directory'; // 一级菜单默认为目录
    } else if (parent.type === 'directory' && !parent.parentId) {
      defaultType = 'directory'; // 二级菜单默认为目录
    } else {
      defaultType = 'menu'; // 三级菜单默认为菜单
    }

    setFormData({
      parentId: parent?.id,
      type: defaultType,
      visible: true,
      status: 'active',
      sort: 0,
    });
    setShowForm(true);
  };

  const handleEdit = (menu: Menu) => {
    setEditingMenu(menu);
    setParentMenu(null);
    setFormData({
      ...menu,
      children: undefined, // 不包含子菜单
    });
    setShowForm(true);
  };

  const handleSave = () => {
    if (!formData.name || !formData.code) {
      toast.error('请填写必填项');
      return;
    }

    // 验证路径：三级菜单必须填写路径
    if (formData.type === 'menu' && !formData.path) {
      toast.error('菜单类型必须填写路径');
      return;
    }

    if (editingMenu) {
      // 更新菜单
      const updateMenuInTree = (items: Menu[]): Menu[] => {
        return items.map(item => {
          if (item.id === editingMenu.id) {
            return {
              ...item,
              ...formData,
              children: item.children, // 保留子菜单
            } as Menu;
          }
          if (item.children) {
            return {
              ...item,
              children: updateMenuInTree(item.children),
            };
          }
          return item;
        });
      };

      const updated = updateMenuInTree(menus);
      setMenus(updated);
      localStorage.setItem('smart_agriculture_menus', JSON.stringify(updated));
      toast.success('菜单更新成功');
    } else {
      // 新增菜单
      const newMenu: Menu = {
        id: `menu-${Date.now()}`,
        ...formData as Menu,
      };

      if (parentMenu) {
        // 添加到父菜单下
        const addToParent = (items: Menu[]): Menu[] => {
          return items.map(item => {
            if (item.id === parentMenu.id) {
              return {
                ...item,
                children: [...(item.children || []), newMenu],
              };
            }
            if (item.children) {
              return {
                ...item,
                children: addToParent(item.children),
              };
            }
            return item;
          });
        };

        const updated = addToParent(menus);
        setMenus(updated);
        localStorage.setItem('smart_agriculture_menus', JSON.stringify(updated));
        // 自动展开父菜单
        setExpandedIds(prev => new Set([...prev, parentMenu.id]));
      } else {
        // 添加为一级菜单
        const updated = [...menus, newMenu];
        setMenus(updated);
        localStorage.setItem('smart_agriculture_menus', JSON.stringify(updated));
      }

      toast.success('菜单添加成功');
    }

    setShowForm(false);
  };

  const handleDelete = (menu: Menu) => {
    if (menu.children && menu.children.length > 0) {
      toast.error('请先删除该菜单下的子菜单');
      return;
    }

    if (!confirm(`确定要删除菜单"${menu.name}"吗？`)) return;

    const deleteFromTree = (items: Menu[]): Menu[] => {
      return items
        .filter(item => item.id !== menu.id)
        .map(item => {
          if (item.children) {
            return {
              ...item,
              children: deleteFromTree(item.children),
            };
          }
          return item;
        });
    };

    const updated = deleteFromTree(menus);
    setMenus(updated);
    localStorage.setItem('smart_agriculture_menus', JSON.stringify(updated));
    toast.success('菜单删除成功');
  };

  return (
    <div className="space-y-6">
      <MenuManagementHeader onAddMenu={() => handleAdd()} />

      {/* 统计卡片 */}
      <MenuManagementStatsCards menus={menus} />

      {/* 菜单树 */}
      <MenuTree
        menus={menus}
        expandedIds={expandedIds}
        onToggleExpand={toggleExpand}
        onExpandAll={expandAll}
        onCollapseAll={collapseAll}
        onAdd={handleAdd}
        onEdit={handleEdit}
        onDelete={handleDelete}
      />

      {/* 添加/编辑表单 */}
      <MenuFormDialog
        open={showForm}
        onOpenChange={setShowForm}
        editingMenu={editingMenu}
        parentMenu={parentMenu}
        formData={formData}
        onFormDataChange={setFormData}
        onSave={handleSave}
      />

      {/* 功能说明 */}
      <MenuManagementInstructions />
    </div>
  );
}