import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Badge } from '../ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../ui/dialog';
import { Label } from '../ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Switch } from '../ui/switch';
import { Menu, MenuType } from '../../types/user-management';
import { 
  Menu as MenuIcon, 
  FolderTree, 
  FileText, 
  Plus, 
  Edit, 
  Trash2, 
  ChevronRight,
  ChevronDown,
  Eye,
  EyeOff,
  LayoutDashboard,
  Folder,
  FileCode
} 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 [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();
  }, []);

  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);
  };

  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('菜单删除成功');
  };

  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 text-blue-700">目录</Badge>;
      case 'menu':
        return <Badge className="bg-green-100 text-green-700">菜单</Badge>;
      case 'button':
        return <Badge className="bg-purple-100 text-purple-700">按钮</Badge>;
      default:
        return <Badge>未知</Badge>;
    }
  };

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

  // 渲染菜单树
  const renderMenuTree = (items: Menu[], level: number = 0) => {
    return items.map((menu) => {
      const isExpanded = expandedIds.has(menu.id);
      const hasChildren = menu.children && menu.children.length > 0;
      const Icon = getMenuIcon(menu.type);
      const indent = level * 24;

      return (
        <div key={menu.id}>
          <div
            className="flex items-center justify-between p-3 border rounded-lg hover:bg-gray-50 mb-2"
            style={{ marginLeft: `${indent}px` }}
          >
            <div className="flex items-center gap-3 flex-1">
              {/* 展开/收起图标 */}
              <div className="w-5 flex items-center justify-center">
                {hasChildren ? (
                  <button
                    onClick={() => toggleExpand(menu.id)}
                    className="hover:bg-gray-200 rounded p-0.5"
                  >
                    {isExpanded ? (
                      <ChevronDown className="w-4 h-4 text-gray-600" />
                    ) : (
                      <ChevronRight className="w-4 h-4 text-gray-600" />
                    )}
                  </button>
                ) : (
                  <div className="w-4" />
                )}
              </div>

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

              {/* 菜单信息 */}
              <div className="flex-1">
                <div className="flex items-center gap-2">
                  <span>{menu.name}</span>
                  <span className="text-xs text-gray-500">({menu.code})</span>
                </div>
                {menu.path && (
                  <div className="text-xs text-gray-500 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" />
                ) : (
                  <EyeOff className="w-4 h-4 text-gray-400" />
                )}
                <span className="text-xs text-gray-500">排序: {menu.sort}</span>
              </div>
            </div>

            {/* 操作按钮 */}
            <div className="flex items-center gap-1 ml-4">
              {/* 只有目录类型可以添加子菜单，且限制最多三级 */}
              {menu.type === 'directory' && level < 2 && (
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => handleAdd(menu)}
                  title="添加子菜单"
                >
                  <Plus className="w-4 h-4 text-green-600" />
                </Button>
              )}
              <Button
                variant="ghost"
                size="sm"
                onClick={() => handleEdit(menu)}
                title="编辑"
              >
                <Edit className="w-4 h-4 text-blue-600" />
              </Button>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => handleDelete(menu)}
                title="删除"
              >
                <Trash2 className="w-4 h-4 text-red-600" />
              </Button>
            </div>
          </div>

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

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">菜单管理</h2>
          <p className="text-muted-foreground">树形结构管理系统菜单体系（最多支持三级菜单）</p>
        </div>
        <Button onClick={() => handleAdd()} className="bg-green-600 hover:bg-green-700">
          <Plus className="w-4 h-4 mr-2" />
          添加一级菜单
        </Button>
      </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">{stats.level1}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">二级菜单</div>
          <div className="mt-2 text-green-600">{stats.level2}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">三级菜单</div>
          <div className="mt-2 text-purple-600">{stats.level3}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">菜单总数</div>
          <div className="mt-2 text-orange-600">{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-gray-500">
              暂无菜单数据，点击上方按钮添加一级菜单
            </div>
          )}
        </div>
      </Card>

      {/* 添加/编辑表单 */}
      <Dialog open={showForm} onOpenChange={setShowForm}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>
              {editingMenu ? '编辑菜单' : parentMenu ? `添加子菜单（父级：${parentMenu.name}）` : '添加一级菜单'}
            </DialogTitle>
            <DialogDescription className="sr-only">
              {editingMenu ? '编辑菜单信息' : '添加新菜单'}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label htmlFor="name">菜单名称 *</Label>
                <Input
                  id="name"
                  value={formData.name || ''}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="请输入菜单名称"
                />
              </div>
              <div>
                <Label htmlFor="code">菜单编码 *</Label>
                <Input
                  id="code"
                  value={formData.code || ''}
                  onChange={(e) => setFormData({ ...formData, code: e.target.value })}
                  placeholder="请输入菜单编码，如：system:menu:add"
                />
              </div>
              <div>
                <Label htmlFor="type">菜单类型 *</Label>
                <Select
                  value={formData.type}
                  onValueChange={(value: MenuType) => setFormData({ ...formData, type: value })}
                >
                  <SelectTrigger id="type">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="directory">目录</SelectItem>
                    <SelectItem value="menu">菜单</SelectItem>
                    <SelectItem value="button">按钮</SelectItem>
                  </SelectContent>
                </Select>
                <p className="text-xs text-gray-500 mt-1">
                  目录：可包含子菜单的分组 / 菜单：具体页面 / 按钮：页面内的操作权限
                </p>
              </div>
              <div>
                <Label htmlFor="icon">图标名称</Label>
                <Input
                  id="icon"
                  value={formData.icon || ''}
                  onChange={(e) => setFormData({ ...formData, icon: e.target.value })}
                  placeholder="如：Settings, Users"
                />
              </div>
              <div>
                <Label htmlFor="path">路由路径 {formData.type === 'menu' ? '*' : ''}</Label>
                <Input
                  id="path"
                  value={formData.path || ''}
                  onChange={(e) => setFormData({ ...formData, path: e.target.value })}
                  placeholder="/config/user/menu"
                />
                {formData.type === 'menu' && (
                  <p className="text-xs text-red-500 mt-1">菜单类型必须填写路由路径</p>
                )}
              </div>
              <div>
                <Label htmlFor="component">组件路径</Label>
                <Input
                  id="component"
                  value={formData.component || ''}
                  onChange={(e) => setFormData({ ...formData, component: e.target.value })}
                  placeholder="@/views/config/MenuManagement"
                />
              </div>
              <div>
                <Label htmlFor="sort">排序号 *</Label>
                <Input
                  id="sort"
                  type="number"
                  value={formData.sort || 0}
                  onChange={(e) => setFormData({ ...formData, sort: parseInt(e.target.value) || 0 })}
                  placeholder="数字越小越靠前"
                />
              </div>
              <div>
                <Label htmlFor="status">状态 *</Label>
                <Select
                  value={formData.status}
                  onValueChange={(value: 'active' | 'inactive') => setFormData({ ...formData, status: value })}
                >
                  <SelectTrigger id="status">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="active">启用</SelectItem>
                    <SelectItem value="inactive">停用</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="flex items-center justify-between p-3 border rounded-lg bg-gray-50">
              <div>
                <Label>是否可见</Label>
                <p className="text-xs text-gray-500 mt-1">控制菜单是否在导航中显示</p>
              </div>
              <Switch
                checked={formData.visible}
                onCheckedChange={(checked) => setFormData({ ...formData, visible: checked })}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowForm(false)}>
              取消
            </Button>
            <Button onClick={handleSave} className="bg-green-600 hover:bg-green-700">
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 功能说明 */}
      <Card className="p-4 bg-blue-50 border-blue-200">
        <h4 className="text-blue-900 mb-2">菜单管理功能说明</h4>
        <ul className="space-y-1 text-sm text-blue-800">
          <li>• 支持三级菜单树形结构管理（一级目录 → 二级目录 → 三级菜单）</li>
          <li>• 目录类型可以包含子菜单，菜单类型为具体页面，按钮类型为页面内的操作权限</li>
          <li>• 菜单编码用于权限控制，建议使用冒号分隔的层级结构，如：system:user:add</li>
          <li>• 路由路径对应前端路由配置，菜单类型必须填写路径</li>
          <li>• 排序号越小越靠前，可以通过调整排序号改变菜单顺序</li>
          <li>• 菜单与角色权限关联，实现灵活的访问控制</li>
          <li>• 删除菜单前请先删除其所有子菜单</li>
        </ul>
      </Card>
    </div>
  );
}
