import React, { useState, useEffect, useMemo } from 'react';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { useToast } from '@/components/ui/use-toast';
import {
  Loader2, Plus, Edit, Trash2, ChevronRight, ChevronDown,
  FolderTree, Menu as MenuIcon
} from 'lucide-react';
import { useDispatch } from 'react-redux';
import { setMenus } from '@/store/userSlice';
import { getMenuTree, deleteMenu, getCurrentUserMenus } from './service';
import type { MenuResponse } from './types';
import { getIconComponent } from '@/config/icons.tsx';
import EditDialog from './components/EditDialog';
import DeleteDialog from './components/DeleteDialog';

/**
 * 菜单管理页面
 */
const MenuPage: React.FC = () => {
  const dispatch = useDispatch();
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [menuTree, setMenuTree] = useState<MenuResponse[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<Set<number>>(new Set());
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [editRecord, setEditRecord] = useState<MenuResponse>();
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [deleteRecord, setDeleteRecord] = useState<MenuResponse | null>(null);

  // 加载菜单树
  const loadMenuTree = async () => {
    try {
      setLoading(true);
      const data = await getMenuTree();
      setMenuTree(data);
      // 默认展开所有节点
      const allIds = new Set<number>();
      const collectIds = (menus: MenuResponse[]) => {
        menus.forEach(menu => {
          if (menu.children && menu.children.length > 0) {
            allIds.add(menu.id);
            collectIds(menu.children);
          }
        });
      };
      collectIds(data);
      setExpandedKeys(allIds);
    } catch (error) {
      console.error('加载菜单数据失败:', error);
      toast({
        title: '加载失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      });
    } finally {
      setLoading(false);
    }
  };

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

  // 更新 Redux 中的菜单数据
  const updateReduxMenus = async () => {
    try {
      const menus = await getCurrentUserMenus();
      dispatch(setMenus(menus));
    } catch (error) {
      console.error('更新菜单数据失败:', error);
    }
  };

  // 新增
  const handleCreate = () => {
    setEditRecord(undefined);
    setEditDialogOpen(true);
  };

  // 编辑
  const handleEdit = (record: MenuResponse) => {
    setEditRecord(record);
    setEditDialogOpen(true);
  };

  // 删除
  const handleDelete = (record: MenuResponse) => {
    setDeleteRecord(record);
    setDeleteDialogOpen(true);
  };

  const confirmDelete = async () => {
    if (!deleteRecord) return;
    try {
      await deleteMenu(deleteRecord.id);
      toast({
        title: '删除成功',
        description: `菜单 "${deleteRecord.name}" 已删除`,
      });
      loadMenuTree();
      updateReduxMenus();
      setDeleteDialogOpen(false);
      setDeleteRecord(null);
    } catch (error) {
      console.error('删除失败:', error);
      toast({
        title: '删除失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      });
    }
  };

  // 切换展开/收起
  const toggleExpand = (id: number) => {
    setExpandedKeys(prev => {
      const newSet = new Set(prev);
      if (newSet.has(id)) {
        newSet.delete(id);
      } else {
        newSet.add(id);
      }
      return newSet;
    });
  };

  // 获取类型徽章
  const getTypeBadge = (type: number) => {
    const typeMap: Record<number, { text: string; variant: 'default' | 'secondary' | 'outline' }> = {
      1: { text: '目录', variant: 'default' },
      2: { text: '菜单', variant: 'secondary' },
      3: { text: '按钮', variant: 'outline' },
    };
    const info = typeMap[type] || { text: '未知', variant: 'outline' };
    return <Badge variant={info.variant}>{info.text}</Badge>;
  };

  // 递归渲染菜单行
  const renderMenuRow = (menu: MenuResponse, level: number = 0): React.ReactNode[] => {
    const hasChildren = menu.children && menu.children.length > 0;
    const isExpanded = expandedKeys.has(menu.id);
    const rows: React.ReactNode[] = [];

    // 当前菜单行
    rows.push(
      <TableRow key={menu.id} className="hover:bg-muted/50">
        <TableCell>
          <div className="flex items-center gap-2" style={{ paddingLeft: `${level * 24}px` }}>
            {hasChildren ? (
              <button
                onClick={() => toggleExpand(menu.id)}
                className="p-0.5 hover:bg-muted rounded"
              >
                {isExpanded ? (
                  <ChevronDown className="h-4 w-4" />
                ) : (
                  <ChevronRight className="h-4 w-4" />
                )}
              </button>
            ) : (
              <span className="w-5" />
            )}
            <span className="font-medium">{menu.name}</span>
          </div>
        </TableCell>
        <TableCell>
          {menu.icon && (
            <div className="flex items-center">
              {getIconComponent(menu.icon)}
            </div>
          )}
        </TableCell>
        <TableCell className="text-sm">{menu.path || '-'}</TableCell>
        <TableCell className="text-sm max-w-[200px] truncate" title={menu.component}>
          {menu.component || '-'}
        </TableCell>
        <TableCell>{getTypeBadge(menu.type)}</TableCell>
        <TableCell className="text-center">{menu.sort}</TableCell>
        <TableCell className="text-right">
          <div className="flex justify-end gap-2">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => handleEdit(menu)}
              title="编辑"
            >
              <Edit className="h-4 w-4" />
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => handleDelete(menu)}
              className="text-red-600 hover:text-red-700 hover:bg-red-50"
              title="删除"
              disabled={hasChildren}
            >
              <Trash2 className="h-4 w-4" />
            </Button>
          </div>
        </TableCell>
      </TableRow>
    );

    // 递归渲染子菜单
    if (hasChildren && isExpanded) {
      menu.children!.forEach(child => {
        rows.push(...renderMenuRow(child, level + 1));
      });
    }

    return rows;
  };

  // 统计数据
  const stats = useMemo(() => {
    const countMenus = (menus: MenuResponse[]): { total: number; directories: number; menuItems: number; buttons: number } => {
      let total = 0;
      let directories = 0;
      let menuItems = 0;
      let buttons = 0;

      const traverse = (menu: MenuResponse) => {
        total++;
        if (menu.type === 1) directories++;
        else if (menu.type === 2) menuItems++;
        else if (menu.type === 3) buttons++;
        
        if (menu.children) {
          menu.children.forEach(traverse);
        }
      };

      menus.forEach(traverse);
      return { total, directories, menuItems, buttons };
    };

    return countMenus(menuTree);
  }, [menuTree]);

  return (
    <div className="p-6">
      <div className="mb-6">
        <h1 className="text-3xl font-bold text-foreground">菜单管理</h1>
        <p className="text-muted-foreground mt-2">
          管理系统菜单结构，配置路由和权限。
        </p>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 sm:grid-cols-4 gap-4 mb-6">
        <Card className="bg-gradient-to-br from-indigo-500/10 to-indigo-500/5 border-indigo-500/20">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium text-indigo-700">总菜单数</CardTitle>
            <FolderTree className="h-4 w-4 text-indigo-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.total}</div>
            <p className="text-xs text-muted-foreground mt-1">所有菜单项</p>
          </CardContent>
        </Card>
        <Card className="bg-gradient-to-br from-blue-500/10 to-blue-500/5 border-blue-500/20">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium text-blue-700">目录</CardTitle>
            <FolderTree className="h-4 w-4 text-blue-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.directories}</div>
            <p className="text-xs text-muted-foreground mt-1">一级分类</p>
          </CardContent>
        </Card>
        <Card className="bg-gradient-to-br from-cyan-500/10 to-cyan-500/5 border-cyan-500/20">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium text-cyan-700">菜单</CardTitle>
            <MenuIcon className="h-4 w-4 text-cyan-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.menuItems}</div>
            <p className="text-xs text-muted-foreground mt-1">可访问页面</p>
          </CardContent>
        </Card>
        <Card className="bg-gradient-to-br from-teal-500/10 to-teal-500/5 border-teal-500/20">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium text-teal-700">按钮</CardTitle>
            <MenuIcon className="h-4 w-4 text-teal-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.buttons}</div>
            <p className="text-xs text-muted-foreground mt-1">操作权限</p>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle>菜单列表</CardTitle>
          <Button onClick={handleCreate}>
            <Plus className="h-4 w-4 mr-2" />
            新增菜单
          </Button>
        </CardHeader>
        <CardContent>
          {/* 表格 */}
          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-[250px]">菜单名称</TableHead>
                  <TableHead className="w-[80px]">图标</TableHead>
                  <TableHead className="w-[200px]">路由地址</TableHead>
                  <TableHead className="w-[200px]">组件路径</TableHead>
                  <TableHead className="w-[100px]">菜单类型</TableHead>
                  <TableHead className="w-[100px] text-center">显示排序</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {loading ? (
                  <TableRow>
                    <TableCell colSpan={7} className="h-24 text-center">
                      <div className="flex items-center justify-center">
                        <Loader2 className="h-6 w-6 animate-spin mr-2" />
                        <span className="text-sm text-muted-foreground">加载中...</span>
                      </div>
                    </TableCell>
                  </TableRow>
                ) : menuTree.length > 0 ? (
                  menuTree.map(menu => renderMenuRow(menu))
                ) : (
                  <TableRow>
                    <TableCell colSpan={7} className="h-24 text-center">
                      <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
                        <FolderTree className="w-16 h-16 mb-4 text-muted-foreground/50" />
                        <div className="text-lg font-semibold mb-2">暂无菜单数据</div>
                        <div className="text-sm">点击右上角"新增菜单"开始创建菜单。</div>
                      </div>
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      {/* 编辑对话框 */}
      <EditDialog
        open={editDialogOpen}
        record={editRecord}
        menuTree={menuTree}
        onOpenChange={setEditDialogOpen}
        onSuccess={() => {
          loadMenuTree();
          updateReduxMenus();
        }}
      />

      {/* 删除确认对话框 */}
      <DeleteDialog
        open={deleteDialogOpen}
        record={deleteRecord}
        onOpenChange={setDeleteDialogOpen}
        onConfirm={confirmDelete}
      />
    </div>
  );
};

export default MenuPage;
