import React, { useState, useMemo, useRef } from 'react';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { PaginatedTable, type ColumnDef, type SearchFieldDef, type PaginatedTableRef } from '@/components/ui/paginated-table';
import {
  Plus, Edit, Trash2, KeyRound, Tag as TagIcon,
  ShieldCheck, Settings, Shield
} from 'lucide-react';
import { useToast } from '@/components/ui/use-toast';
import { getRoleList, deleteRole, getRoleMenusAndPermissions, assignMenusAndPermissions } from './service';
import type { RoleResponse, RoleQuery } from './types';
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 tableRef = useRef<PaginatedTableRef<RoleResponse>>(null);
  const [stats, setStats] = useState({ total: 0 });
  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 [defaultMenuIds, setDefaultMenuIds] = useState<number[]>([]);
  const [defaultPermissionIds, setDefaultPermissionIds] = useState<number[]>([]);

  // 包装 fetchFn，同时更新统计数据
  const fetchData = async (query: RoleQuery) => {
    const result = await getRoleList(query);
    setStats({ total: result.totalElements || 0 });
    return result;
  };

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

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

  const handleSuccess = () => {
    setEditDialogOpen(false);
    setEditRecord(undefined);
    tableRef.current?.refresh();
  };

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

  const confirmDelete = async () => {
    if (!deleteRecord) return;
    try {
      await deleteRole(deleteRecord.id);
      toast({
        title: '删除成功',
        description: `角色 "${deleteRecord.name}" 已删除`,
      });
      tableRef.current?.refresh();
      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 data = await getRoleMenusAndPermissions(record.id);
      setSelectedRole(record);
      setPermissionDialogOpen(true);
      setDefaultMenuIds(data.menuIds || []);
      setDefaultPermissionIds(data.permissionIds || []);
    } catch (error) {
      console.error('获取角色权限失败:', error);
      toast({
        title: '获取权限失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      });
    }
  };

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

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

  // 搜索字段定义
  const searchFields: SearchFieldDef[] = useMemo(() => [
    { key: 'code', type: 'input', placeholder: '搜索角色编码', width: 'w-[180px]' },
    { key: 'name', type: 'input', placeholder: '搜索角色名称', width: 'w-[180px]' },
  ], []);

  // 列定义
  const columns: ColumnDef<RoleResponse>[] = useMemo(() => [
    { key: 'id', title: 'ID', dataIndex: 'id', width: '80px' },
    { 
      key: 'code', 
      title: '角色编码', 
      width: '150px',
      render: (_, record) => <code className="text-sm">{record.code}</code>,
    },
    { key: 'name', title: '角色名称', dataIndex: 'name', width: '150px' },
    {
      key: 'isAdmin',
      title: '类型',
      width: '120px',
      render: (_, record) => record.isAdmin ? (
        <Badge variant="default" className="bg-amber-500 hover:bg-amber-600">
          <Shield className="h-3 w-3 mr-1" />
          管理员
        </Badge>
      ) : (
        <Badge variant="outline">普通角色</Badge>
      ),
    },
    {
      key: 'tags',
      title: '标签',
      width: '200px',
      render: (_, record) => (
        <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>
      ),
    },
    { key: 'sort', title: '排序', dataIndex: 'sort', width: '80px' },
    { 
      key: 'description', 
      title: '描述', 
      width: '200px',
      render: (_, record) => (
        <div className="truncate max-w-[200px]" title={record.description || ''}>
          {record.description || '-'}
        </div>
      ),
    },
    { 
      key: 'createTime', 
      title: '创建时间', 
      width: '180px',
      render: (_, record) => record.createTime ? dayjs(record.createTime).format('YYYY-MM-DD HH:mm') : '-',
    },
    {
      key: 'actions',
      title: '操作',
      width: '200px',
      sticky: true,
      render: (_, record) => (
        <div className="flex 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>
          {!record.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>
      ),
    },
  ], []);

  // 工具栏
  const toolbar = (
    <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>
  );

  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>
          <CardTitle>角色列表</CardTitle>
        </CardHeader>
        <Separator />
        <CardContent className="pt-6">
          <PaginatedTable<RoleResponse, RoleQuery>
            ref={tableRef}
            fetchFn={fetchData}
            columns={columns}
            searchFields={searchFields}
            toolbar={toolbar}
            rowKey="id"
            minWidth="1280px"
          />
        </CardContent>
      </Card>

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

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

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

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

export default RolePage;
