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 { Input } from '@/components/ui/input';
import { DataTablePagination } from '@/components/ui/pagination';
import {
  Loader2, Plus, Search, Edit, Trash2, KeyRound, Tag as TagIcon,
  ShieldCheck, Settings
} from 'lucide-react';
import { useToast } from '@/components/ui/use-toast';
import { getRoleList, deleteRole, getRolePermissions, assignPermissions } from './service';
import type { RoleResponse, RoleQuery } from './types';
import type { Page } from '@/types/base';
import { DEFAULT_PAGE_SIZE, DEFAULT_CURRENT } from '@/utils/page';
import EditDialog from './components/EditDialog';
import DeleteDialog from './components/DeleteDialog';
import PermissionDialog from './components/PermissionDialog';
import TagDialog from './components/TagDialog';
import AssignTagDialog from './components/AssignTagDialog';
import dayjs from 'dayjs';

/**
 * 角色管理页面
 */
const RolePage: React.FC = () => {
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<Page<RoleResponse> | null>(null);
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [editRecord, setEditRecord] = useState<RoleResponse>();
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [deleteRecord, setDeleteRecord] = useState<RoleResponse | null>(null);
  const [permissionDialogOpen, setPermissionDialogOpen] = useState(false);
  const [tagDialogOpen, setTagDialogOpen] = useState(false);
  const [assignTagDialogOpen, setAssignTagDialogOpen] = useState(false);
  const [selectedRole, setSelectedRole] = useState<RoleResponse | null>(null);
  const [defaultCheckedKeys, setDefaultCheckedKeys] = useState<number[]>([]);
  const [query, setQuery] = useState<RoleQuery>({
    pageNum: DEFAULT_CURRENT - 1,
    pageSize: DEFAULT_PAGE_SIZE,
    code: '',
    name: '',
  });

  // 加载数据
  const loadData = async () => {
    setLoading(true);
    try {
      const result = await getRoleList(query);
      setData(result);
    } catch (error) {
      console.error('加载角色列表失败:', error);
      toast({
        title: '加载失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, [query]);

  // 搜索
  const handleSearch = () => {
    setQuery(prev => ({ ...prev, pageNum: 0 }));
  };

  // 重置
  const handleReset = () => {
    setQuery({
      pageNum: 0,
      pageSize: DEFAULT_PAGE_SIZE,
      code: '',
      name: '',
    });
  };

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

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

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

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

  // 分配权限
  const handleAssignPermissions = async (record: RoleResponse) => {
    try {
      const permissions = await getRolePermissions(record.id);
      setSelectedRole(record);
      setPermissionDialogOpen(true);
      setDefaultCheckedKeys(
        Array.isArray(permissions)
          ? typeof permissions[0] === 'number'
            ? permissions
            : permissions.map((p: any) => p.id)
          : []
      );
    } catch (error) {
      console.error('获取角色权限失败:', error);
      toast({
        title: '获取权限失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      });
    }
  };

  const confirmAssignPermissions = async (permissionIds: number[]) => {
    if (!selectedRole) return;
    try {
      await assignPermissions(selectedRole.id, permissionIds);
      toast({
        title: '分配成功',
        description: `已为角色 "${selectedRole.name}" 分配权限`,
      });
      setPermissionDialogOpen(false);
      loadData();
    } catch (error) {
      console.error('分配权限失败:', error);
      toast({
        title: '分配失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      });
    }
  };

  // 分配标签
  const handleAssignTags = (record: RoleResponse) => {
    setSelectedRole(record);
    setAssignTagDialogOpen(true);
  };

  // 统计数据
  const stats = useMemo(() => {
    const total = data?.totalElements || 0;
    return { total };
  }, [data]);

  const pageCount = data?.totalElements ? Math.ceil(data.totalElements / (query.pageSize || DEFAULT_PAGE_SIZE)) : 0;

  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-3 gap-4 mb-6">
        <Card className="bg-gradient-to-br from-purple-500/10 to-purple-500/5 border-purple-500/20">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium text-purple-700">总角色数</CardTitle>
            <ShieldCheck className="h-4 w-4 text-purple-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.total}</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>
          <div className="flex gap-2">
            <Button variant="outline" onClick={() => setTagDialogOpen(true)}>
              <Settings className="h-4 w-4 mr-2" />
              标签管理
            </Button>
            <Button onClick={handleCreate}>
              <Plus className="h-4 w-4 mr-2" />
              新建角色
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          {/* 搜索栏 */}
          <div className="flex flex-wrap items-center gap-4 mb-4">
            <div className="flex-1 max-w-xs">
              <Input
                placeholder="搜索角色编码"
                value={query.code}
                onChange={(e) => setQuery(prev => ({ ...prev, code: e.target.value }))}
                onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                className="h-9"
              />
            </div>
            <div className="flex-1 max-w-xs">
              <Input
                placeholder="搜索角色名称"
                value={query.name}
                onChange={(e) => setQuery(prev => ({ ...prev, name: e.target.value }))}
                onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                className="h-9"
              />
            </div>
            <Button onClick={handleSearch} className="h-9">
              <Search className="h-4 w-4 mr-2" />
              搜索
            </Button>
            <Button variant="outline" onClick={handleReset} className="h-9">
              重置
            </Button>
          </div>

          {/* 表格 */}
          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-[150px]">角色编码</TableHead>
                  <TableHead className="w-[150px]">角色名称</TableHead>
                  <TableHead className="w-[200px]">标签</TableHead>
                  <TableHead className="w-[100px]">排序</TableHead>
                  <TableHead className="w-[200px]">描述</TableHead>
                  <TableHead className="w-[180px]">创建时间</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>
                ) : data?.content && data.content.length > 0 ? (
                  data.content.map((record) => {
                    const isAdmin = record.code === 'admin';
                    return (
                      <TableRow key={record.id} className="hover:bg-muted/50">
                        <TableCell className="font-medium">
                          <code className="text-sm">{record.code}</code>
                        </TableCell>
                        <TableCell>{record.name}</TableCell>
                        <TableCell>
                          <div className="flex flex-wrap gap-1">
                            {record.tags && record.tags.length > 0 ? (
                              record.tags.map(tag => (
                                <Badge
                                  key={tag.id}
                                  variant="outline"
                                  style={{ backgroundColor: tag.color, color: '#fff' }}
                                  className="text-xs"
                                >
                                  {tag.name}
                                </Badge>
                              ))
                            ) : (
                              <span className="text-muted-foreground">-</span>
                            )}
                          </div>
                        </TableCell>
                        <TableCell>{record.sort}</TableCell>
                        <TableCell className="text-sm max-w-[200px] truncate" title={record.description}>
                          {record.description || '-'}
                        </TableCell>
                        <TableCell className="text-sm">
                          {record.createTime ? dayjs(record.createTime).format('YYYY-MM-DD HH:mm') : '-'}
                        </TableCell>
                        <TableCell className="text-right">
                          <div className="flex justify-end gap-2">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleEdit(record)}
                              title="编辑"
                            >
                              <Edit className="h-4 w-4" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleAssignPermissions(record)}
                              title="分配权限"
                              className="text-blue-600 hover:text-blue-700 hover:bg-blue-50"
                            >
                              <KeyRound className="h-4 w-4" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleAssignTags(record)}
                              title="分配标签"
                              className="text-purple-600 hover:text-purple-700 hover:bg-purple-50"
                            >
                              <TagIcon className="h-4 w-4" />
                            </Button>
                            {!isAdmin && (
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => handleDelete(record)}
                                className="text-red-600 hover:text-red-700 hover:bg-red-50"
                                title="删除"
                              >
                                <Trash2 className="h-4 w-4" />
                              </Button>
                            )}
                          </div>
                        </TableCell>
                      </TableRow>
                    );
                  })
                ) : (
                  <TableRow>
                    <TableCell colSpan={7} className="h-24 text-center">
                      <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
                        <ShieldCheck 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>

          {/* 分页 */}
          {pageCount > 1 && (
            <DataTablePagination
              pageIndex={(query.pageNum || 0) + 1}
              pageSize={query.pageSize || DEFAULT_PAGE_SIZE}
              pageCount={pageCount}
              onPageChange={(page) => setQuery(prev => ({
                ...prev,
                pageNum: page - 1
              }))}
            />
          )}
        </CardContent>
      </Card>

      {/* 编辑对话框 */}
      <EditDialog
        open={editDialogOpen}
        record={editRecord}
        onOpenChange={setEditDialogOpen}
        onSuccess={loadData}
      />

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

      {/* 权限分配对话框 */}
      {selectedRole && (
        <>
          <PermissionDialog
            open={permissionDialogOpen}
            onOpenChange={setPermissionDialogOpen}
            onConfirm={confirmAssignPermissions}
            defaultCheckedKeys={defaultCheckedKeys}
          />
          <AssignTagDialog
            open={assignTagDialogOpen}
            roleId={selectedRole.id}
            onOpenChange={setAssignTagDialogOpen}
            onSuccess={() => {
              setAssignTagDialogOpen(false);
              loadData();
            }}
            selectedTags={selectedRole.tags}
          />
        </>
      )}

      {/* 标签管理对话框 */}
      <TagDialog
        open={tagDialogOpen}
        onOpenChange={setTagDialogOpen}
        onSuccess={() => {
          setTagDialogOpen(false);
          loadData();
        }}
      />
    </div>
  );
};

export default RolePage;
