import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Menu, MenuType } from '../../types/user-management';
import { 
  Menu as MenuIcon, 
  ChevronRight,
  ChevronDown,
  Eye,
  EyeOff,
  Folder,
  FileCode,
  GripVertical,
  FileText
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';

export function MenuManagement() {
  const [menus, setMenus] = useState<Menu[]>([]);
  const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());
  const [draggedItem, setDraggedItem] = useState<{ menu: Menu; index: number; parentId?: string } | null>(null);
  const [dragOverItem, setDragOverItem] = useState<{ index: number; parentId?: string } | null>(null);

  useEffect(() => {
    loadMenus();
  }, []);

  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 countMenus = (menus: Menu[]): { level1: number; level2: number; level3: number } => {
    let level1 = 0;
    let level2 = 0;
    let level3 = 0;

    menus.forEach(menu => {
      if (!menu.parentId) {
        level1++;
        if (menu.children) {
          menu.children.forEach(child => {
            level2++;
            if (child.children) {
              level3 += child.children.length;
            }
          });
        }
      }
    });

    return { level1, level2, level3 };
  };

  const stats = countMenus(menus);

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

  // 保存菜单到localStorage
  const saveMenus = (updatedMenus: Menu[]) => {
    setMenus(updatedMenus);
    localStorage.setItem('smart_agriculture_menus', JSON.stringify(updatedMenus));
  };

  // 拖动开始
  const handleDragStart = (e: React.DragEvent, menu: Menu, index: number, parentId?: string) => {
    setDraggedItem({ menu, index, parentId });
    e.dataTransfer.effectAllowed = 'move';
    // 设置拖动时的半透明效果
    if (e.currentTarget instanceof HTMLElement) {
      e.currentTarget.style.opacity = '0.5';
    }
  };

  // 拖动结束
  const handleDragEnd = (e: React.DragEvent) => {
    if (e.currentTarget instanceof HTMLElement) {
      e.currentTarget.style.opacity = '1';
    }
    setDraggedItem(null);
    setDragOverItem(null);
  };

  // 拖动经过
  const handleDragOver = (e: React.DragEvent, index: number, parentId?: string) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
    
    // 只在同级菜单之间才显示拖放提示
    if (draggedItem && draggedItem.parentId === parentId) {
      setDragOverItem({ index, parentId });
    }
  };

  // 拖动离开
  const handleDragLeave = () => {
    setDragOverItem(null);
  };

  // 放置
  const handleDrop = (e: React.DragEvent, hoverIndex: number, parentId?: string) => {
    e.preventDefault();
    
    if (!draggedItem) return;
    
    // 只能在同一父级下拖动
    if (draggedItem.parentId !== parentId) {
      toast.error('不能跨级别拖动菜单');
      setDragOverItem(null);
      return;
    }

    const dragIndex = draggedItem.index;
    if (dragIndex === hoverIndex) {
      setDragOverItem(null);
      return;
    }

    // 更新菜单顺序
    let updated: Menu[];

    if (!parentId) {
      // 一级菜单
      const newMenus = [...menus];
      const [removed] = newMenus.splice(dragIndex, 1);
      newMenus.splice(hoverIndex, 0, removed);
      
      // 更新排序号
      updated = newMenus.map((item, index) => ({
        ...item,
        sort: index + 1,
      }));
    } else {
      // 二级或三级菜单
      const updateInTree = (items: Menu[]): Menu[] => {
        return items.map(item => {
          if (item.id === parentId && item.children) {
            const newChildren = [...item.children];
            const [removed] = newChildren.splice(dragIndex, 1);
            newChildren.splice(hoverIndex, 0, removed);
            
            return {
              ...item,
              children: newChildren.map((child, index) => ({
                ...child,
                sort: index + 1,
              })),
            };
          }
          if (item.children) {
            return {
              ...item,
              children: updateInTree(item.children),
            };
          }
          return item;
        });
      };

      updated = updateInTree(menus);
    }

    saveMenus(updated);
    toast.success('菜单顺序已更新');
    setDragOverItem(null);
  };

  const getMenuIcon = (type: MenuType) => {
    switch (type) {
      case 'directory':
        return Folder;
      case 'menu':
        return FileCode;
      case 'button':
        return FileText;
      default:
        return MenuIcon;
    }
  };

  const getTypeBadge = (type: MenuType) => {
    switch (type) {
      case 'directory':
        return <Badge className="bg-blue-100 dark:bg-blue-100 text-blue-700 dark:text-blue-700">目录</Badge>;
      case 'menu':
        return <Badge className="bg-green-100 dark:bg-green-100 text-green-700 dark:text-green-700">菜单</Badge>;
      case 'button':
        return <Badge className="bg-purple-100 dark:bg-purple-100 text-purple-700 dark:text-purple-700">按钮</Badge>;
      default:
        return <Badge>未知</Badge>;
    }
  };

  const getStatusBadge = (status: string) => {
    return status === 'active' ? (
      <Badge className="bg-green-100 dark:bg-green-100 text-green-700 dark:text-green-700">启用</Badge>
    ) : (
      <Badge className="bg-gray-100 dark:bg-gray-100 text-gray-700 dark:text-gray-700">停用</Badge>
    );
  };

  // 渲染菜单树
  const renderMenuTree = (items: Menu[], level: number = 0, parentId?: string) => {
    return items.map((menu, index) => {
      const isExpanded = expandedIds.has(menu.id);
      const hasChildren = menu.children && menu.children.length > 0;
      const Icon = getMenuIcon(menu.type);
      const indent = level * 24;
      
      // 判断是否是拖动目标
      const isDragOver = dragOverItem?.index === index && dragOverItem?.parentId === parentId;
      const isDragging = draggedItem?.menu.id === menu.id;

      return (
        <div key={menu.id}>
          <div
            draggable
            onDragStart={(e) => handleDragStart(e, menu, index, parentId)}
            onDragEnd={handleDragEnd}
            onDragOver={(e) => handleDragOver(e, index, parentId)}
            onDragLeave={handleDragLeave}
            onDrop={(e) => handleDrop(e, index, parentId)}
            className={`flex items-center justify-between p-3 border rounded-lg mb-2 transition-all ${
              isDragging
                ? 'opacity-50 bg-muted'
                : isDragOver
                  ? 'bg-green-50 dark:bg-green-950/30 border-green-300 dark:border-green-700'
                  : 'hover:bg-muted/50'
            }`}
            style={{ marginLeft: `${indent}px`, cursor: 'move' }}
          >
            <div className="flex items-center gap-3 flex-1">
              {/* 拖动手柄 */}
              <div className="cursor-grab active:cursor-grabbing" title="拖动调整顺序">
                <GripVertical className="w-4 h-4 text-muted-foreground hover:text-green-600 dark:hover:text-green-400" />
              </div>

              {/* 展开/收起图标 */}
              <div className="w-5 flex items-center justify-center">
                {hasChildren ? (
                  <button
                    onClick={() => toggleExpand(menu.id)}
                    className="hover:bg-muted rounded p-0.5"
                  >
                    {isExpanded ? (
                      <ChevronDown className="w-4 h-4 text-muted-foreground" />
                    ) : (
                      <ChevronRight className="w-4 h-4 text-muted-foreground" />
                    )}
                  </button>
                ) : (
                  <div className="w-4" />
                )}
              </div>

              {/* 菜单图标 */}
              <Icon className="w-5 h-5 text-green-600 dark:text-green-400" />

              {/* 菜单信息 */}
              <div className="flex-1">
                <div className="flex items-center gap-2">
                  <span>{menu.name}</span>
                  <span className="text-xs text-muted-foreground">({menu.code})</span>
                </div>
                {menu.path && (
                  <div className="text-xs text-muted-foreground mt-0.5">{menu.path}</div>
                )}
              </div>

              {/* 状态标签 */}
              <div className="flex items-center gap-2">
                {getTypeBadge(menu.type)}
                {getStatusBadge(menu.status)}
                {menu.visible ? (
                  <Eye className="w-4 h-4 text-green-500 dark:text-green-400" />
                ) : (
                  <EyeOff className="w-4 h-4 text-gray-400 dark:text-gray-600" />
                )}
                <span className="text-xs text-muted-foreground">排序: {menu.sort}</span>
              </div>
            </div>
          </div>

          {/* 递归渲染子菜单 */}
          {hasChildren && isExpanded && (
            <div className="mt-2">
              {renderMenuTree(menu.children!, level + 1, menu.id)}
            </div>
          )}
        </div>
      );
    });
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800 dark:text-green-400">菜单管理</h2>
          <p className="text-muted-foreground">拖动菜单项调整顺序，支持查看和排序功能</p>
        </div>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-4 gap-4">
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">一级菜单</div>
          <div className="mt-2 text-blue-600 dark:text-blue-400">{stats.level1}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">二级菜单</div>
          <div className="mt-2 text-green-600 dark:text-green-400">{stats.level2}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">三级菜单</div>
          <div className="mt-2 text-purple-600 dark:text-purple-400">{stats.level3}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">菜单总数</div>
          <div className="mt-2 text-orange-600 dark:text-orange-400">{stats.level1 + stats.level2 + stats.level3}</div>
        </Card>
      </div>

      {/* 菜单树 */}
      <Card className="p-6">
        <div className="flex items-center justify-between mb-4">
          <h3>菜单结构</h3>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setExpandedIds(new Set(menus.map(m => m.id)))}
            >
              展开全部
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setExpandedIds(new Set())}
            >
              收起全部
            </Button>
          </div>
        </div>

        <div className="space-y-2">
          {menus.length > 0 ? (
            renderMenuTree(menus)
          ) : (
            <div className="text-center py-8 text-muted-foreground">
              暂无菜单数据
            </div>
          )}
        </div>
      </Card>

      {/* 功能说明 */}
      <Card className="p-4 bg-blue-50 dark:bg-blue-950/30 border-blue-200 dark:border-blue-900">
        <h4 className="text-blue-900 dark:text-blue-400 mb-2">菜单管理说明</h4>
        <ul className="space-y-1 text-sm text-blue-800 dark:text-blue-300">
          <li>• <strong>拖动排序：</strong>按住菜单项左侧的 ⋮⋮ 图标拖动，可调整同级菜单的顺序</li>
          <li>• <strong>只读限制：</strong>不支持新增、编辑、删除菜单，仅支持排序和查看</li>
          <li>• <strong>同级拖动：</strong>只能在相同层级的菜单之间拖动，不能跨级别拖动</li>
          <li>• 系统采用三级菜单树形结构（一级目录 → 二级目录 → 三级菜单）</li>
          <li>• 目录类型：可包含子菜单的分组</li>
          <li>• 菜单类型：具体页面，包含路由路径</li>
          <li>• 按钮类型：页面内的操作权限</li>
          <li>• 菜单编码用于权限控制，格式示例：system:user:add</li>
          <li>• 拖动排序后会自动保存，刷新页面后仍然有效</li>
        </ul>
      </Card>
    </div>
  );
}
