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 { Textarea } from '../ui/textarea';
import { Checkbox } from '../ui/checkbox';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { ScrollArea } from '../ui/scroll-area';
import { Role } from '../../types/user-management';
import { 
  machineryMenus, 
  fieldMenus, 
  operationMenus, 
  assetMenus, 
  aiMenus, 
  irrigationMenus, 
  configMenus, 
  MenuItem 
} from '../../types/navigation';
import { Search, Plus, Edit, Trash2, Eye, Shield, ChevronRight } from 'lucide-react';
import { toast } from 'sonner@2.0.3';

// 定义菜单权限结构（菜单与操作权限关联）
interface MenuWithPermissions {
  id: string;
  label: string;
  children?: {
    id: string;
    label: string;
    operations: {
      id: string;
      label: string;
      key: string;
    }[];
  }[];
}

// 所有系统菜单及其操作权限
const allSystemMenus: { id: string; label: string; menus: MenuWithPermissions[] }[] = [
  {
    id: 'machinery',
    label: '智能农机管理系统',
    menus: [
      {
        id: 'machinery-archive',
        label: '农机档案',
        children: [
          {
            id: 'machinery-entry',
            label: '农机档案录入与维护',
            operations: [
              { id: 'machinery-entry:view', label: '查看', key: 'view' },
              { id: 'machinery-entry:add', label: '新增', key: 'add' },
              { id: 'machinery-entry:edit', label: '编辑', key: 'edit' },
              { id: 'machinery-entry:delete', label: '删除', key: 'delete' },
              { id: 'machinery-entry:export', label: '导出', key: 'export' },
            ],
          },
          {
            id: 'machinery-classification',
            label: '农机分类与标签管理',
            operations: [
              { id: 'machinery-classification:view', label: '查看', key: 'view' },
              { id: 'machinery-classification:edit', label: '编辑', key: 'edit' },
            ],
          },
          {
            id: 'machinery-qrcode',
            label: '农机二维码管理',
            operations: [
              { id: 'machinery-qrcode:view', label: '查看', key: 'view' },
              { id: 'machinery-qrcode:generate', label: '生成', key: 'generate' },
              { id: 'machinery-qrcode:print', label: '打印', key: 'print' },
            ],
          },
        ],
      },
      {
        id: 'driver-archive',
        label: '驾驶员档案',
        children: [
          {
            id: 'driver-info',
            label: '驾驶员信息管理',
            operations: [
              { id: 'driver-info:view', label: '查看', key: 'view' },
              { id: 'driver-info:add', label: '新增', key: 'add' },
              { id: 'driver-info:edit', label: '编辑', key: 'edit' },
              { id: 'driver-info:delete', label: '删除', key: 'delete' },
            ],
          },
          {
            id: 'driver-task',
            label: '驾驶员任务管理',
            operations: [
              { id: 'driver-task:view', label: '查看', key: 'view' },
              { id: 'driver-task:assign', label: '分配任务', key: 'assign' },
              { id: 'driver-task:cancel', label: '取消任务', key: 'cancel' },
            ],
          },
        ],
      },
      {
        id: 'monitoring',
        label: '设备实时监控与定位',
        children: [
          {
            id: 'realtime-location',
            label: '实时位置追踪',
            operations: [
              { id: 'realtime-location:view', label: '查看', key: 'view' },
              { id: 'realtime-location:track', label: '追踪', key: 'track' },
            ],
          },
          {
            id: 'work-status',
            label: '工作状态监控',
            operations: [
              { id: 'work-status:view', label: '查看', key: 'view' },
              { id: 'work-status:control', label: '远程控制', key: 'control' },
            ],
          },
        ],
      },
      {
        id: 'fault-diagnosis',
        label: '远程诊断与故障预警',
        children: [
          {
            id: 'fault-warning',
            label: '故障诊断与预警',
            operations: [
              { id: 'fault-warning:view', label: '查看', key: 'view' },
              { id: 'fault-warning:handle', label: '处理', key: 'handle' },
              { id: 'fault-warning:export', label: '导出', key: 'export' },
            ],
          },
        ],
      },
    ],
  },
  {
    id: 'field',
    label: '地块信息管理系统',
    menus: [
      {
        id: 'field-info',
        label: '地块信息',
        children: [
          {
            id: 'field-list',
            label: '地块列表',
            operations: [
              { id: 'field-list:view', label: '查看', key: 'view' },
              { id: 'field-list:add', label: '新增', key: 'add' },
              { id: 'field-list:edit', label: '编辑', key: 'edit' },
              { id: 'field-list:delete', label: '删除', key: 'delete' },
            ],
          },
          {
            id: 'field-map',
            label: '地块地图',
            operations: [
              { id: 'field-map:view', label: '查看', key: 'view' },
              { id: 'field-map:draw', label: '绘制', key: 'draw' },
            ],
          },
        ],
      },
    ],
  },
  {
    id: 'operation',
    label: '农事操作管理系统',
    menus: [
      {
        id: 'operation-plan',
        label: '作业计划',
        children: [
          {
            id: 'plan-list',
            label: '计划列表',
            operations: [
              { id: 'plan-list:view', label: '查看', key: 'view' },
              { id: 'plan-list:add', label: '新增', key: 'add' },
              { id: 'plan-list:edit', label: '编辑', key: 'edit' },
              { id: 'plan-list:delete', label: '删除', key: 'delete' },
            ],
          },
        ],
      },
    ],
  },
  {
    id: 'asset',
    label: '农业资产管理系统',
    menus: [
      {
        id: 'asset-inventory',
        label: '资产清单',
        children: [
          {
            id: 'inventory-list',
            label: '清单列表',
            operations: [
              { id: 'inventory-list:view', label: '查看', key: 'view' },
              { id: 'inventory-list:manage', label: '管理', key: 'manage' },
            ],
          },
        ],
      },
    ],
  },
  {
    id: 'ai-model',
    label: 'AI作物模型精准决策系统',
    menus: [
      {
        id: 'ai-models',
        label: 'AI模型',
        children: [
          {
            id: 'model-list',
            label: '模型列表',
            operations: [
              { id: 'model-list:view', label: '查看', key: 'view' },
              { id: 'model-list:run', label: '运行', key: 'run' },
            ],
          },
        ],
      },
    ],
  },
  {
    id: 'irrigation',
    label: '水肥一体化控制系统',
    menus: [
      {
        id: 'irrigation-control',
        label: '灌溉控制',
        children: [
          {
            id: 'zone-control',
            label: '区域控制',
            operations: [
              { id: 'zone-control:view', label: '查看', key: 'view' },
              { id: 'zone-control:control', label: '控制', key: 'control' },
            ],
          },
        ],
      },
    ],
  },
  {
    id: 'config',
    label: '中心配置管理系统',
    menus: [
      {
        id: 'tenant-management',
        label: '租户管理',
        children: [
          {
            id: 'enterprise-audit',
            label: '企业审核',
            operations: [
              { id: 'enterprise-audit:view', label: '查看', key: 'view' },
              { id: 'enterprise-audit:audit', label: '审核', key: 'audit' },
            ],
          },
          {
            id: 'enterprise-info',
            label: '企业信息',
            operations: [
              { id: 'enterprise-info:view', label: '查看', key: 'view' },
              { id: 'enterprise-info:edit', label: '编辑', key: 'edit' },
            ],
          },
        ],
      },
      {
        id: 'user-management',
        label: '用户管理',
        children: [
          {
            id: 'employee-management',
            label: '员工管理',
            operations: [
              { id: 'employee-management:view', label: '查看', key: 'view' },
              { id: 'employee-management:add', label: '新增', key: 'add' },
              { id: 'employee-management:edit', label: '编辑', key: 'edit' },
              { id: 'employee-management:delete', label: '删除', key: 'delete' },
            ],
          },
          {
            id: 'role-management',
            label: '角色管理',
            operations: [
              { id: 'role-management:view', label: '查看', key: 'view' },
              { id: 'role-management:manage', label: '管理', key: 'manage' },
            ],
          },
        ],
      },
      {
        id: 'system-params',
        label: '系统参数',
        children: [
          {
            id: 'system-settings',
            label: '系统设置',
            operations: [
              { id: 'system-settings:view', label: '查看', key: 'view' },
              { id: 'system-settings:edit', label: '编辑', key: 'edit' },
            ],
          },
        ],
      },
      {
        id: 'system-monitor',
        label: '系统监控',
        children: [
          {
            id: 'login-log',
            label: '登录日志',
            operations: [
              { id: 'login-log:view', label: '查看', key: 'view' },
              { id: 'login-log:export', label: '导出', key: 'export' },
            ],
          },
          {
            id: 'operation-log',
            label: '操作日志',
            operations: [
              { id: 'operation-log:view', label: '查看', key: 'view' },
              { id: 'operation-log:export', label: '导出', key: 'export' },
            ],
          },
        ],
      },
    ],
  },
];

export function RoleManagement() {
  const [roles, setRoles] = useState<Role[]>([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [showForm, setShowForm] = useState(false);
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [editingRole, setEditingRole] = useState<Role | null>(null);
  const [selectedRole, setSelectedRole] = useState<Role | null>(null);
  const [formData, setFormData] = useState<Partial<Role>>({
    type: 'custom',
    status: 'active',
    menuIds: [],
    permissionIds: [],
  });

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

  const loadRoles = () => {
    const data = localStorage.getItem('smart_agriculture_roles');
    if (data) {
      setRoles(JSON.parse(data));
    } else {
      const mockRoles: Role[] = [
        {
          id: 'role-1',
          name: '超级管理员',
          code: 'super_admin',
          description: '系统最高权限，可管理所有功能和数据',
          type: 'system',
          menuIds: ['*'],
          permissionIds: ['*'],
          status: 'active',
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'role-2',
          name: '企业管理员',
          code: 'enterprise_admin',
          description: '企业管理员，可管理本企业的员工和数据',
          type: 'system',
          menuIds: ['config-user', 'machinery', 'field'],
          permissionIds: ['user:view', 'user:add', 'user:edit', 'machinery:*'],
          defaultHomePage: '/machinery/archive/entry',
          status: 'active',
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'role-3',
          name: '操作员',
          code: 'operator',
          description: '一般操作员，可查看和操作农机设备',
          type: 'system',
          menuIds: ['machinery', 'field'],
          permissionIds: ['machinery:view', 'machinery:control', 'field:view'],
          defaultHomePage: '/machinery/monitoring/location',
          status: 'active',
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'role-4',
          name: '维修员',
          code: 'maintenance',
          description: '农机维修人员，负责设备维护和故障诊断',
          type: 'custom',
          menuIds: ['machinery-fault', 'machinery-archive'],
          permissionIds: ['machinery:view', 'fault:view', 'fault:handle'],
          status: 'active',
          createdAt: '2024-10-01T00:00:00',
          updatedAt: '2024-10-01T00:00:00',
        },
      ];
      localStorage.setItem('smart_agriculture_roles', JSON.stringify(mockRoles));
      setRoles(mockRoles);
    }
  };

  const filteredRoles = roles.filter(role => {
    const matchKeyword = !searchKeyword ||
      role.name.includes(searchKeyword) ||
      role.code.includes(searchKeyword) ||
      (role.description && role.description.includes(searchKeyword));
    return matchKeyword;
  });

  const handleAdd = () => {
    setEditingRole(null);
    setFormData({
      type: 'custom',
      status: 'active',
      menuIds: [],
      permissionIds: [],
    });
    setShowForm(true);
  };

  const handleEdit = (role: Role) => {
    setEditingRole(role);
    setFormData(role);
    setShowForm(true);
  };

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

    if (editingRole) {
      const updated = roles.map(role =>
        role.id === editingRole.id
          ? {
              ...role,
              ...formData,
              updatedAt: new Date().toISOString(),
            }
          : role
      );
      setRoles(updated);
      localStorage.setItem('smart_agriculture_roles', JSON.stringify(updated));
      toast.success('角色更新成功');
    } else {
      const newRole: Role = {
        id: `role-${Date.now()}`,
        ...formData as Role,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };
      const updated = [...roles, newRole];
      setRoles(updated);
      localStorage.setItem('smart_agriculture_roles', JSON.stringify(updated));
      toast.success('角色添加成功');
    }

    setShowForm(false);
  };

  const handleDelete = (id: string) => {
    const role = roles.find(r => r.id === id);
    if (role && role.type === 'system') {
      toast.error('系统角色不能删除');
      return;
    }

    if (!confirm('确定要删除该角色吗？')) return;

    const updated = roles.filter(role => role.id !== id);
    setRoles(updated);
    localStorage.setItem('smart_agriculture_roles', JSON.stringify(updated));
    toast.success('角色删除成功');
  };

  const handleViewDetail = (role: Role) => {
    setSelectedRole(role);
    setShowDetailDialog(true);
  };

  const getRoleTypeBadge = (type: string) => {
    return type === 'system' ? (
      <Badge className="bg-blue-100 text-blue-700">系统角色</Badge>
    ) : (
      <Badge className="bg-green-100 text-green-700">自定义</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 stats = [
    {
      label: '总角色数',
      value: roles.length,
      color: 'text-blue-600',
      bg: 'bg-blue-100',
    },
    {
      label: '系统角色',
      value: roles.filter(r => r.type === 'system').length,
      color: 'text-purple-600',
      bg: 'bg-purple-100',
    },
    {
      label: '自定义角色',
      value: roles.filter(r => r.type === 'custom').length,
      color: 'text-green-600',
      bg: 'bg-green-100',
    },
  ];

  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">基于RBAC的角色访问控制管理</p>
        </div>
        <Button onClick={handleAdd}>
          <Plus className="w-4 h-4 mr-2" />
          添加角色
        </Button>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-3 gap-4">
        {stats.map((stat, index) => (
          <Card key={index} className="p-4">
            <div className="text-sm text-muted-foreground">{stat.label}</div>
            <div className={`mt-2 ${stat.color}`}>{stat.value}</div>
          </Card>
        ))}
      </div>

      {/* 搜索 */}
      <Card className="p-4">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
          <Input
            placeholder="搜索角色名称、代码、描述..."
            value={searchKeyword}
            onChange={(e) => setSearchKeyword(e.target.value)}
            className="pl-10"
          />
        </div>
      </Card>

      {/* 角色列表 */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>角色名称</TableHead>
              <TableHead>角色代码</TableHead>
              <TableHead>角色描述</TableHead>
              <TableHead>类型</TableHead>
              <TableHead>状态</TableHead>
              <TableHead>创建时间</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredRoles.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="text-center text-muted-foreground py-8">
                  暂无数据
                </TableCell>
              </TableRow>
            ) : (
              filteredRoles.map((role) => (
                <TableRow key={role.id}>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <Shield className="w-4 h-4 text-muted-foreground" />
                      {role.name}
                    </div>
                  </TableCell>
                  <TableCell className="text-muted-foreground">{role.code}</TableCell>
                  <TableCell className="text-muted-foreground max-w-xs truncate">
                    {role.description}
                  </TableCell>
                  <TableCell>{getRoleTypeBadge(role.type)}</TableCell>
                  <TableCell>{getStatusBadge(role.status)}</TableCell>
                  <TableCell className="text-muted-foreground">
                    {new Date(role.createdAt).toLocaleDateString('zh-CN')}
                  </TableCell>
                  <TableCell>
                    <div className="flex gap-1">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleViewDetail(role)}
                      >
                        <Eye className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleEdit(role)}
                      >
                        <Edit className="w-4 h-4" />
                      </Button>
                      {role.type === 'custom' && (
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleDelete(role.id)}
                        >
                          <Trash2 className="w-4 h-4 text-destructive" />
                        </Button>
                      )}
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </Card>

      {/* 添加/编辑表单 */}
      <Dialog open={showForm} onOpenChange={setShowForm}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>{editingRole ? '编辑角色' : '添加角色'}</DialogTitle>
            <DialogDescription className="sr-only">
              {editingRole ? '编辑角色信息' : '添加新角色'}
            </DialogDescription>
          </DialogHeader>
          <ScrollArea className="max-h-[calc(90vh-180px)]">
            <div className="space-y-6 pr-4">
              {/* 基本信息 */}
              <div className="space-y-4">
                <h4 className="text-green-800">基本信息</h4>
                <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="如：data_analyst"
                    />
                  </div>
                </div>
                <div>
                  <Label htmlFor="description">角色描述</Label>
                  <Textarea
                    id="description"
                    value={formData.description || ''}
                    onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                    rows={3}
                    placeholder="描述角色的职责和权限范围..."
                  />
                </div>
                <div>
                  <Label htmlFor="defaultHomePage">默认首页</Label>
                  <Input
                    id="defaultHomePage"
                    value={formData.defaultHomePage || ''}
                    onChange={(e) => setFormData({ ...formData, defaultHomePage: e.target.value })}
                    placeholder="/machinery/monitoring/location"
                  />
                </div>
              </div>

              {/* 菜单与操作权限 */}
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <h4 className="text-green-800">菜单与操作权限</h4>
                  <p className="text-xs text-muted-foreground">选择菜单后可配置该菜单下的操作权限</p>
                </div>
                <Card className="p-4 bg-gray-50">
                  <div className="space-y-6">
                    {allSystemMenus.map((system) => (
                      <div key={system.id} className="space-y-3">
                        {/* 系统级别 */}
                        <div className="flex items-center gap-2 pb-2 border-b border-green-200">
                          <Checkbox
                            id={`system-${system.id}`}
                            checked={
                              formData.menuIds?.includes('*') ||
                              (system.menus.every(menu => 
                                formData.menuIds?.includes(menu.id)
                              ) && system.menus.length > 0)
                            }
                            onCheckedChange={(checked) => {
                              if (checked) {
                                // 选中所有一级菜单
                                const allMenuIds = system.menus.map(m => m.id);
                                setFormData({
                                  ...formData,
                                  menuIds: Array.from(new Set([...(formData.menuIds || []), ...allMenuIds])),
                                });
                              } else {
                                // 取消选中所有一级菜单
                                const menuIdsToRemove = system.menus.map(m => m.id);
                                setFormData({
                                  ...formData,
                                  menuIds: (formData.menuIds || []).filter(id => !menuIdsToRemove.includes(id)),
                                });
                              }
                            }}
                            disabled={formData.menuIds?.includes('*')}
                          />
                          <Label htmlFor={`system-${system.id}`} className="cursor-pointer text-green-700">
                            {system.label}
                          </Label>
                        </div>

                        {/* 一级菜单 */}
                        <div className="ml-6 space-y-4">
                          {system.menus.map((menu) => (
                            <div key={menu.id} className="space-y-2">
                              <div className="flex items-center gap-2">
                                <Checkbox
                                  id={`menu-${menu.id}`}
                                  checked={formData.menuIds?.includes(menu.id) || formData.menuIds?.includes('*')}
                                  onCheckedChange={(checked) => {
                                    if (checked) {
                                      setFormData({
                                        ...formData,
                                        menuIds: [...(formData.menuIds || []), menu.id],
                                      });
                                    } else {
                                      // 取消菜单时，同时取消该菜单下的所有权限
                                      const childrenIds = menu.children?.map(c => c.id) || [];
                                      const permissionsToRemove = menu.children?.flatMap(c => 
                                        c.operations.map(op => op.id)
                                      ) || [];
                                      
                                      setFormData({
                                        ...formData,
                                        menuIds: (formData.menuIds || []).filter(id => 
                                          id !== menu.id && !childrenIds.includes(id)
                                        ),
                                        permissionIds: (formData.permissionIds || []).filter(id =>
                                          !permissionsToRemove.includes(id)
                                        ),
                                      });
                                    }
                                  }}
                                  disabled={formData.menuIds?.includes('*')}
                                />
                                <Label htmlFor={`menu-${menu.id}`} className="cursor-pointer">
                                  {menu.label}
                                </Label>
                              </div>

                              {/* 二级菜单及其操作权限 */}
                              {menu.children && (formData.menuIds?.includes(menu.id) || formData.menuIds?.includes('*')) && (
                                <div className="ml-6 space-y-3 pl-4 border-l-2 border-green-100">
                                  {menu.children.map((child) => (
                                    <div key={child.id} className="space-y-2">
                                      <div className="flex items-center gap-2">
                                        <ChevronRight className="w-3 h-3 text-green-600" />
                                        <span className="text-sm text-muted-foreground">{child.label}</span>
                                      </div>
                                      <div className="ml-5 flex flex-wrap gap-3">
                                        {child.operations.map((operation) => (
                                          <div key={operation.id} className="flex items-center gap-1.5">
                                            <Checkbox
                                              id={`permission-${operation.id}`}
                                              checked={
                                                formData.permissionIds?.includes(operation.id) || 
                                                formData.permissionIds?.includes('*')
                                              }
                                              onCheckedChange={(checked) => {
                                                if (checked) {
                                                  setFormData({
                                                    ...formData,
                                                    permissionIds: [...(formData.permissionIds || []), operation.id],
                                                  });
                                                } else {
                                                  setFormData({
                                                    ...formData,
                                                    permissionIds: (formData.permissionIds || []).filter(id => id !== operation.id),
                                                  });
                                                }
                                              }}
                                              disabled={formData.permissionIds?.includes('*')}
                                            />
                                            <Label 
                                              htmlFor={`permission-${operation.id}`} 
                                              className="text-xs cursor-pointer text-foreground"
                                            >
                                              {operation.label}
                                            </Label>
                                          </div>
                                        ))}
                                      </div>
                                    </div>
                                  ))}
                                </div>
                              )}
                            </div>
                          ))}
                        </div>
                      </div>
                    ))}
                  </div>
                </Card>
              </div>
            </div>
          </ScrollArea>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowForm(false)}>
              取消
            </Button>
            <Button onClick={handleSave}>保存</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 详情对话框 */}
      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>角色详情</DialogTitle>
            <DialogDescription className="sr-only">
              查看角色的详细信息和权限
            </DialogDescription>
          </DialogHeader>
          {selectedRole && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>角色名称</Label>
                  <div className="mt-1">{selectedRole.name}</div>
                </div>
                <div>
                  <Label>角色代码</Label>
                  <div className="mt-1">{selectedRole.code}</div>
                </div>
                <div className="col-span-2">
                  <Label>角色描述</Label>
                  <div className="mt-1">{selectedRole.description || '-'}</div>
                </div>
                <div>
                  <Label>角色类型</Label>
                  <div className="mt-1">{getRoleTypeBadge(selectedRole.type)}</div>
                </div>
                <div>
                  <Label>状态</Label>
                  <div className="mt-1">{getStatusBadge(selectedRole.status)}</div>
                </div>
                {selectedRole.defaultHomePage && (
                  <div className="col-span-2">
                    <Label>默认首页</Label>
                    <div className="mt-1">{selectedRole.defaultHomePage}</div>
                  </div>
                )}
                <div>
                  <Label>菜单数量</Label>
                  <div className="mt-1">
                    {selectedRole.menuIds.includes('*') ? '全部' : selectedRole.menuIds.length}
                  </div>
                </div>
                <div>
                  <Label>权限数量</Label>
                  <div className="mt-1">
                    {selectedRole.permissionIds.includes('*') ? '全部' : selectedRole.permissionIds.length}
                  </div>
                </div>
                <div>
                  <Label>创建时间</Label>
                  <div className="mt-1">
                    {new Date(selectedRole.createdAt).toLocaleString('zh-CN')}
                  </div>
                </div>
                <div>
                  <Label>更新时间</Label>
                  <div className="mt-1">
                    {new Date(selectedRole.updatedAt).toLocaleString('zh-CN')}
                  </div>
                </div>
              </div>
            </div>
          )}
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDetailDialog(false)}>
              关闭
            </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>• 每个角色可配置可访问的菜单和功能权限</li>
          <li>• 用户通过分配角色获得相应的系统访问权限</li>
          <li>• 建议按照职能划分角色，便于权限管理</li>
        </ul>
      </Card>
    </div>
  );
}
