'use client';

import { useState, useEffect } from 'react';
import { toast } from 'sonner';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Search,
  Plus,
  Edit,
  Trash2,
  Shield,
  ChevronRight,
} from 'lucide-react';

import { PermissionManagementHeader } from './components/PermissionManagementHeader';
import { Permission, PermissionType, Menu } from './types';

export default function PermissionConfigPage() {
  const [permissions, setPermissions] = useState<Permission[]>([]);
  const [menus, setMenus] = useState<Menu[]>([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [typeFilter, setTypeFilter] = useState<string>('all');
  const [showForm, setShowForm] = useState(false);
  const [editingPermission, setEditingPermission] = useState<Permission | null>(null);
  const [formData, setFormData] = useState<Partial<Permission>>({
    type: 'view',
    status: 'active',
  });

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

  const loadMenus = () => {
    const data = localStorage.getItem('smart_agriculture_menus');
    if (data) {
      setMenus(JSON.parse(data));
    }
  };

  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',
        },
      ];
      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',
    },
    {
      label: '查看权限',
      value: permissions.filter((p) => p.type === 'view').length,
      color: 'text-green-600',
    },
    {
      label: '操作权限',
      value: permissions.filter((p) => ['add', 'edit', 'delete'].includes(p.type)).length,
      color: 'text-orange-600',
    },
    {
      label: '特殊权限',
      value: permissions.filter((p) => ['control', 'approve', 'export', 'import'].includes(p.type)).length,
      color: 'text-purple-600',
    },
  ];

  const handleAdd = () => {
    setEditingPermission(null);
    setFormData({
      type: 'view',
      status: 'active',
    });
    setShowForm(true);
  };

  const handleEdit = (permission: Permission) => {
    setEditingPermission(permission);
    setFormData(permission);
    setShowForm(true);
  };

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

    if (editingPermission) {
      const updated = permissions.map((perm) =>
        perm.id === editingPermission.id
          ? {
              ...perm,
              ...formData,
              updatedAt: new Date().toISOString(),
            }
          : perm,
      );
      setPermissions(updated);
      localStorage.setItem('smart_agriculture_permissions', JSON.stringify(updated));
      toast.success('权限更新成功');
    } else {
      const newPermission: Permission = {
        id: `perm-${Date.now()}`,
        ...formData as Permission,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };
      const updated = [...permissions, newPermission];
      setPermissions(updated);
      localStorage.setItem('smart_agriculture_permissions', JSON.stringify(updated));
      toast.success('权限添加成功');
    }

    setShowForm(false);
  };

  const handleDelete = (id: string) => {
    if (!confirm('确定要删除该权限吗？')) return;

    const updated = permissions.filter((perm) => perm.id !== id);
    setPermissions(updated);
    localStorage.setItem('smart_agriculture_permissions', JSON.stringify(updated));
    toast.success('权限删除成功');
  };

  return (
    <div className="space-y-6">
      <PermissionManagementHeader onAddPermission={handleAdd} />

      {/* 统计卡片 */}
      <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>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredPermissions.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} 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>
                  <TableCell>
                    <div className="flex gap-1">
                      <Button variant="ghost" size="sm" onClick={() => handleEdit(permission)}>
                        <Edit className="w-4 h-4" />
                      </Button>
                      <Button variant="ghost" size="sm" onClick={() => handleDelete(permission.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>{editingPermission ? '编辑权限' : '添加权限'}</DialogTitle>
            <DialogDescription className="sr-only">
              {editingPermission ? '编辑权限信息' : '添加新权限'}
            </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="如：machinery:view"
                />
              </div>
              <div className="col-span-2">
                <Label htmlFor="type">权限类型 *</Label>
                <Select value={formData.type || 'view'} onValueChange={(value: PermissionType) => setFormData({ ...formData, type: value })}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <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>
            </div>
            <div>
              <Label htmlFor="description">权限描述</Label>
              <Input
                id="description"
                value={formData.description || ''}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                placeholder="描述该权限的作用..."
              />
            </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>• 权限代码格式建议：模块:操作，如 machinery:view</li>
          <li>• 每个权限可以关联到具体的菜单（支持一级、二级、三级菜单）</li>
          <li>• 权限通过角色分配给用户，实现灵活的访问控制</li>
          <li>• 支持8种权限类型：查看、新增、编辑、删除、导出、导入、审核、控制</li>
          <li>• 合理规划权限体系，确保系统安全性和易用性</li>
        </ul>
      </Card>
    </div>
  );
}