import { useState, useEffect } from "react";
import { Card } from "../ui/card";
import { Input } from "../ui/input";
import { Badge } from "../ui/badge";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "../ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "../ui/table";
import {
  Permission,
  PermissionType,
} from "../../types/user-management";
import {
  Search,
  Shield,
  ChevronRight,
} from "lucide-react";

export function PermissionManagement() {
  const [permissions, setPermissions] = useState<Permission[]>(
    [],
  );
  const [searchKeyword, setSearchKeyword] = useState("");
  const [typeFilter, setTypeFilter] = useState<string>("all");

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

  const loadPermissions = () => {
    const data = localStorage.getItem(
      "smart_agriculture_permissions",
    );
    if (data) {
      setPermissions(JSON.parse(data));
    } else {
      const mockPermissions: Permission[] = [
        {
          id: "perm-1",
          name: "查看农机",
          code: "machinery:view",
          type: "view",
          description: "查看农机档案和基本信息",
          menuId: "menu-1-1-1",
          menuPath: "智能农机管理系统 > 农机档案 > 农机录入",
          status: "active",
          createdAt: "2024-01-01T00:00:00",
          updatedAt: "2024-01-01T00:00:00",
        },
        {
          id: "perm-2",
          name: "添加农机",
          code: "machinery:add",
          type: "add",
          description: "添加新的农机设备",
          menuId: "menu-1-1-1",
          menuPath: "智能农机管理系统 > 农机档案 > 农机录入",
          status: "active",
          createdAt: "2024-01-01T00:00:00",
          updatedAt: "2024-01-01T00:00:00",
        },
        {
          id: "perm-3",
          name: "编辑农机",
          code: "machinery:edit",
          type: "edit",
          description: "编辑农机信息",
          menuId: "menu-1-1-1",
          menuPath: "智能农机管理系统 > 农机档案 > 农机录入",
          status: "active",
          createdAt: "2024-01-01T00:00:00",
          updatedAt: "2024-01-01T00:00:00",
        },
        {
          id: "perm-4",
          name: "删除农机",
          code: "machinery:delete",
          type: "delete",
          description: "删除农机设备",
          menuId: "menu-1-1-1",
          menuPath: "智能农机管理系统 > 农机档案 > 农机录入",
          status: "active",
          createdAt: "2024-01-01T00:00:00",
          updatedAt: "2024-01-01T00:00:00",
        },
        {
          id: "perm-5",
          name: "控制农机",
          code: "machinery:control",
          type: "control",
          description: "远程控制农机设备",
          menuId: "menu-1-2-1",
          menuPath: "智能农机管理系统 > 驾驶员管理 > 驾驶员信息",
          status: "active",
          createdAt: "2024-01-01T00:00:00",
          updatedAt: "2024-01-01T00:00:00",
        },
        {
          id: "perm-6",
          name: "导出数据",
          code: "data:export",
          type: "export",
          description: "导出系统数据",
          menuId: "menu-2-2-1",
          menuPath: "中心配置管理系统 > 用户管理 > 员工管理",
          status: "active",
          createdAt: "2024-01-01T00:00:00",
          updatedAt: "2024-01-01T00:00:00",
        },
        {
          id: "perm-7",
          name: "审核企业",
          code: "enterprise:approve",
          type: "approve",
          description: "审核企业注册申请",
          menuId: "menu-2-1-2",
          menuPath: "中心配置管理系统 > 租户管理 > 企业审核",
          status: "active",
          createdAt: "2024-01-01T00:00:00",
          updatedAt: "2024-01-01T00:00:00",
        },
      ];
      localStorage.setItem(
        "smart_agriculture_permissions",
        JSON.stringify(mockPermissions),
      );
      setPermissions(mockPermissions);
    }
  };

  const filteredPermissions = permissions.filter((perm) => {
    const matchKeyword =
      !searchKeyword ||
      perm.name.includes(searchKeyword) ||
      perm.code.includes(searchKeyword) ||
      (perm.menuPath && perm.menuPath.includes(searchKeyword));

    const matchType =
      typeFilter === "all" || perm.type === typeFilter;

    return matchKeyword && matchType;
  });

  const getPermissionTypeBadge = (type: PermissionType) => {
    const config: Record<
      PermissionType,
      { label: string; className: string }
    > = {
      view: {
        label: "查看",
        className: "bg-blue-100 text-blue-700",
      },
      add: {
        label: "新增",
        className: "bg-green-100 text-green-700",
      },
      edit: {
        label: "编辑",
        className: "bg-yellow-100 text-yellow-700",
      },
      delete: {
        label: "删除",
        className: "bg-red-100 text-red-700",
      },
      export: {
        label: "导出",
        className: "bg-purple-100 text-purple-700",
      },
      import: {
        label: "导入",
        className: "bg-indigo-100 text-indigo-700",
      },
      approve: {
        label: "审核",
        className: "bg-orange-100 text-orange-700",
      },
      control: {
        label: "控制",
        className: "bg-pink-100 text-pink-700",
      },
    };

    const { label, className } = config[type] || {
      label: type,
      className: "",
    };
    return <Badge className={className}>{label}</Badge>;
  };

  const stats = [
    {
      label: "总权限数",
      value: permissions.length,
      color: "text-blue-600",
      bg: "bg-blue-100",
    },
    {
      label: "查看权限",
      value: permissions.filter((p) => p.type === "view")
        .length,
      color: "text-green-600",
      bg: "bg-green-100",
    },
    {
      label: "操作权限",
      value: permissions.filter((p) =>
        ["add", "edit", "delete"].includes(p.type),
      ).length,
      color: "text-orange-600",
      bg: "bg-orange-100",
    },
    {
      label: "特殊权限",
      value: permissions.filter((p) =>
        ["control", "approve", "export", "import"].includes(
          p.type,
        ),
      ).length,
      color: "text-purple-600",
      bg: "bg-purple-100",
    },
  ];

  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-2 md:grid-cols-4 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="flex gap-4">
          <div className="flex-1">
            <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>
          </div>
          <Select
            value={typeFilter}
            onValueChange={setTypeFilter}
          >
            <SelectTrigger className="w-40">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部类型</SelectItem>
              <SelectItem value="view">查看</SelectItem>
              <SelectItem value="add">新增</SelectItem>
              <SelectItem value="edit">编辑</SelectItem>
              <SelectItem value="delete">删除</SelectItem>
              <SelectItem value="export">导出</SelectItem>
              <SelectItem value="import">导入</SelectItem>
              <SelectItem value="approve">审核</SelectItem>
              <SelectItem value="control">控制</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </Card>

      {/* 权限列表 */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>权限名称</TableHead>
              <TableHead>权限代码</TableHead>
              <TableHead>类型</TableHead>
              <TableHead>关联菜单</TableHead>
              <TableHead>描述</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredPermissions.length === 0 ? (
              <TableRow>
                <TableCell
                  colSpan={5}
                  className="text-center text-muted-foreground py-8"
                >
                  暂无数据
                </TableCell>
              </TableRow>
            ) : (
              filteredPermissions.map((permission) => (
                <TableRow key={permission.id}>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <Shield className="w-4 h-4 text-muted-foreground" />
                      {permission.name}
                    </div>
                  </TableCell>
                  <TableCell className="text-muted-foreground">
                    {permission.code}
                  </TableCell>
                  <TableCell>
                    {getPermissionTypeBadge(permission.type)}
                  </TableCell>
                  <TableCell className="text-muted-foreground max-w-xs">
                    {permission.menuPath ? (
                      <div className="flex items-center gap-1 text-xs">
                        {permission.menuPath.split(' > ').map((part, index, arr) => (
                          <span key={index} className="flex items-center gap-1">
                            <span className={index === arr.length - 1 ? 'text-green-600' : ''}>
                              {part}
                            </span>
                            {index < arr.length - 1 && (
                              <ChevronRight className="w-3 h-3 text-gray-400" />
                            )}
                          </span>
                        ))}
                      </div>
                    ) : (
                      "-"
                    )}
                  </TableCell>
                  <TableCell className="text-muted-foreground max-w-xs truncate">
                    {permission.description || "-"}
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </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>
            • 权限是系统功能的最小控制单元，精确到按钮级别
          </li>
          <li>
            • 权限代码格式：模块:操作，如 machinery:view
          </li>
          <li>
            • 每个权限可以关联到具体的菜单（支持一级、二级、三级菜单）
          </li>
          <li>• 权限通过角色分配给用户，实现灵活的访问控制</li>
          <li>
            • 支持8种权限类型：查看、新增、编辑、删除、导出、导入、审核、控制
          </li>
        </ul>
      </Card>
    </div>
  );
}
