/**
 * filekorolheader: 角色管理页面 - 系统角色访问控制管理
 * 功能：角色列表管理、API数据加载、分页查询、角色搜索、详情查看
 * 路径：/central-config/user/role
 * 规范：遵循crop-x/docs/开发项目规范.md，使用SearchFormPagination公共组件，shadcn语义化样式，支持翻页
 */

'use client';

import { useState, useEffect, useCallback, useMemo } from 'react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';

import { RoleManagementHeader } from './components/RoleManagementHeader';
import { RoleManagementStatsCards } from './components/RoleManagementStatsCards';
import { RoleFormDialog } from './components/RoleFormDialog';
import { RoleDetailDialog } from './components/RoleDetailDialog';
import { RoleManagementInstructions } from './components/RoleManagementInstructions';
import { SearchFormPagination, SearchFieldConfig, TableColumnConfig } from '@/components/common/searchFormPagination';
import { Role, RoleFormData } from './types';
import { Eye, Edit, Trash2, Shield } from 'lucide-react';
import {
  fetchRoles,
  createRole,
  getRoleDetail,
  deleteRole,
  updateRole,
  transformRolesList,
  RolesApiResponse,
  RolesQueryParams,
  PaginationState
} from './components/roleApi';

export default function RoleManagementPage() {
  const [roles, setRoles] = useState<Role[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState<PaginationState>({
    page: 1,
    size: 10,
    total: 0,
    totalPages: 0,
    hasNext: false,
    hasPrev: false,
  });
  const [searchFilters, setSearchFilters] = useState<Record<string, string>>({});

  // 搜索字段配置
  const searchFields: SearchFieldConfig[] = useMemo(() => [
    {
      key: 'search',
      label: '搜索',
      type: 'text',
      placeholder: '搜索角色名称、代码、描述...',
    },
  ], []);

  // 表格列配置
  const columns: TableColumnConfig[] = useMemo(() => [
    {
      key: 'name',
      label: '角色名称',
      sortable: true,
      render: (value: string, role: Role) => (
        <div className="flex items-center gap-2">
          <Shield className="w-4 h-4 text-muted-foreground" />
          <span className="font-medium">{value}</span>
        </div>
      ),
    },
    {
      key: 'code',
      label: '角色代码',
      sortable: true,
      render: (value: string) => (
        <span className="text-muted-foreground">{value}</span>
      ),
    },
    {
      key: 'description',
      label: '角色描述',
      render: (value: string) => (
        <span className="text-muted-foreground max-w-xs truncate block">{value || '-'}</span>
      ),
    },
    {
      key: 'type',
      label: '类型',
      sortable: true,
      render: (value: string) => (
        <div className={`inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium ${
          value === 'system'
            ? 'bg-blue-50 dark:bg-blue-950 text-blue-600 dark:text-blue-400'
            : 'bg-green-50 dark:bg-green-950 text-green-600 dark:text-green-400'
        }`}>
          {value === 'system' ? '系统角色' : '自定义'}
        </div>
      ),
    },
    {
      key: 'status',
      label: '状态',
      sortable: true,
      render: (value: string) => (
        <div className={`inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium ${
          value === 'active'
            ? 'bg-green-50 dark:bg-green-950 text-green-600 dark:text-green-400'
            : 'bg-gray-50 dark:bg-gray-950 text-gray-600 dark:text-gray-400'
        }`}>
          {value === 'active' ? '启用' : '停用'}
        </div>
      ),
    },
    {
      key: 'createdAt',
      label: '创建时间',
      sortable: true,
      render: (value: string) => (
        <span className="text-muted-foreground">
          {new Date(value).toLocaleDateString('zh-CN')}
        </span>
      ),
    },
    {
      key: 'actions',
      label: '操作',
      render: (_, role: Role) => (
        <div className="flex items-center 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>
      ),
    },
  ], []);
  const [showForm, setShowForm] = useState(false);
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [editingRole, setEditingRole] = useState<Role | null>(null);
  const [selectedRole, setSelectedRole] = useState<Role | null>(null);
  const [deletingRoleId, setDeletingRoleId] = useState<string | null>(null);
  const [detailLoading, setDetailLoading] = useState(false);
  const [editFormLoading, setEditFormLoading] = useState(false);
  const [formData, setFormData] = useState<RoleFormData>({
    type: 'custom',
    status: 'active',
    menuIds: [],
    permissionIds: [],
  });

  // 加载角色数据
  const loadRoles = useCallback(async () => {
    setLoading(true);
    try {
      const queryParams: RolesQueryParams = {
        page: pagination.page,
        size: pagination.size,
        sort_order: 'desc'
      };

      // 添加搜索条件
      if (searchFilters.search) {
        queryParams.search = searchFilters.search;
      }

      const response = await fetchRoles(queryParams);

      // 转换数据格式
      const transformedRoles = transformRolesList(response.data);

      setRoles(transformedRoles);
      setPagination({
        page: response.page,
        size: response.size,
        total: response.total,
        totalPages: response.total_pages,
        hasNext: response.has_next,
        hasPrev: response.has_prev,
      });
    } catch (error) {
      console.error('Failed to load roles:', error);
      toast.error('加载角色数据失败');
      setRoles([]);
    } finally {
      setLoading(false);
    }
  }, [pagination.page, pagination.size, searchFilters]);

  // 加载数据
  useEffect(() => {
    loadRoles();
  }, [loadRoles]);

  // 搜索处理
  const handleSearch = useCallback((filters: Record<string, string>) => {
    setSearchFilters(filters);
    setPagination(prev => ({ ...prev, page: 1 }));
  }, []);

  // 分页处理
  const handlePageChange = useCallback((page: number) => {
    if (page < 1) {
      page = 1;
    } else if (page > pagination.totalPages && pagination.totalPages > 0) {
      page = pagination.totalPages;
    }
    setPagination(prev => ({ ...prev, page }));
  }, [pagination.totalPages]);

  // 每页条数变化处理
  const handleSizeChange = useCallback((size: number) => {
    setPagination(prev => ({ ...prev, size, page: 1 }));
  }, []);

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

  // 处理表单弹窗关闭
  const handleFormDialogClose = (open: boolean) => {
    if (!open) {
      // 弹窗关闭时清空所有数据和loading状态
      setEditingRole(null);
      setEditFormLoading(false);
      setFormData({
        type: 'custom',
        status: 'active',
        menuIds: [],
        permissionIds: [],
      });
    }
    setShowForm(open);
  };

  // 处理详情弹窗关闭
  const handleDetailDialogClose = (open: boolean) => {
    if (!open) {
      // 弹窗关闭时清空选中的角色和loading状态
      setSelectedRole(null);
      setDetailLoading(false);
    }
    setShowDetailDialog(open);
  };

  const handleEdit = (role: Role) => {
    // 先打开弹框，设置初始状态
    setEditingRole(role);
    setFormData({
      type: 'custom',
      status: 'active',
      menuIds: [],
      permissionIds: [],
    });
    setShowForm(true);
    setEditFormLoading(true);

    // 在弹框内部异步加载数据
    loadEditFormData(role.id);
  };

  // 加载编辑表单数据的独立函数
  const loadEditFormData = async (roleId: string) => {
    try {
      console.log('编辑角色，使用角色ID:', roleId);

      // 调用API获取角色详情
      const roleDetail = await getRoleDetail(roleId);

      // 将API返回的数据转换为表单格式
      const formData: RoleFormData = {
        name: roleDetail.name,
        code: editingRole?.code || roleDetail.id, // 使用转换后的code（即API返回的ID）
        description: roleDetail.description,
        type: 'custom',
        status: 'active',
        menuIds: [],
        permissionIds: [],
        defaultHomePage: editingRole?.defaultHomePage,
      };

      setFormData(formData);

    } catch (error: any) {
      console.error('获取角色详情失败:', error);

      // 处理API返回的错误信息
      if (error?.data?.message) {
        toast.error(error.data.message);
      } else if (error?.data?.detail?.original_detail) {
        toast.error(error.data.detail.original_detail);
      } else if (error?.message) {
        toast.error(error.message);
      } else {
        toast.error('获取角色详情失败');
      }
      // 加载失败时关闭弹框
      setShowForm(false);
    } finally {
      setEditFormLoading(false);
    }
  };

  const handleSave = async () => {
    if (!formData.name) {
      toast.error('请填写角色名称');
      return;
    }

    if (editingRole) {
      // 编辑角色 - 检查数据是否有变化
      const hasChanges =
        editingRole.name !== formData.name ||
        editingRole.description !== formData.description ||
        JSON.stringify(editingRole.permissionIds) !== JSON.stringify(formData.permissionIds);

      if (hasChanges) {
        // 有数据变化，调用API更新角色
        try {
          setLoading(true);

          // 准备API参数
          const roleData = {
            name: formData.name,
            description: formData.description || '',
            permission_ids: formData.permissionIds || [],
          };

          console.log('开始更新角色:', editingRole.id, roleData);

          // 调用API更新角色
          await updateRole(editingRole.id, roleData);

          // 成功后刷新列表
          await loadRoles();

          toast.success('角色更新成功');
          setShowForm(false);

        } catch (error: any) {
          console.error('更新角色失败:', error);

          // 处理API返回的错误信息
          if (error?.data?.message) {
            toast.error(error.data.message);
          } else if (error?.message) {
            toast.error(error.message);
          } else {
            toast.error('更新操作失败');
          }
          // 更新失败时不关闭表单，不刷新列表
        } finally {
          setLoading(false);
        }
      } else {
        // 数据没有变化，直接关闭表单，不刷新列表
        toast.success('角色信息无变化');
        setShowForm(false);
      }
    } else {
      // 新增角色调用API
      try {
        setLoading(true);

        // 准备API参数
        const roleData = {
          name: formData.name,
          description: formData.description || '',
          permission_ids: formData.permissionIds || [],
        };

        console.log('开始创建角色:', roleData);

        // 调用API创建角色
        await createRole(roleData);

        // 成功后刷新列表
        await loadRoles();

        toast.success('角色添加成功');
        setShowForm(false);

      } catch (error: any) {
        console.error('创建角色失败:', error);

        // 处理API返回的错误信息
        if (error?.data?.message) {
          toast.error(error.data.message);
        } else if (error?.message) {
          toast.error(error.message);
        } else {
          toast.error('新增操作失败');
        }
        // 新增失败时不关闭表单，不刷新列表
      } finally {
        setLoading(false);
      }
    }
  };

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

    setDeletingRoleId(id);
    setShowDeleteDialog(true);
  };

  // 确认删除角色
  const handleConfirmDelete = async () => {
    if (!deletingRoleId) return;

    try {
      setLoading(true);

      console.log('删除角色，使用角色ID:', deletingRoleId);

      // 调用API删除角色
      await deleteRole(deletingRoleId);

      // 成功后刷新列表
      await loadRoles();

      toast.success('角色删除成功');
      setShowDeleteDialog(false);
      setDeletingRoleId(null);

    } catch (error: any) {
      console.error('删除角色失败:', error);

      // 处理API返回的错误信息
      if (error?.data?.message) {
        toast.error(error.data.message);
      } else if (error?.message) {
        toast.error(error.message);
      } else {
        toast.error('删除操作失败');
      }
      // 删除失败时不关闭对话框，不刷新列表
    } finally {
      setLoading(false);
    }
  };

  // 取消删除
  const handleCancelDelete = () => {
    setShowDeleteDialog(false);
    setDeletingRoleId(null);
  };

  const handleViewDetail = (role: Role) => {
    // 先打开弹框，设置初始状态，确保所有必需属性都有默认值
    const roleWithDefaults: Role = {
      ...role,
      menuIds: role.menuIds || [],
      permissionIds: role.permissionIds || [],
    };
    setSelectedRole(roleWithDefaults);
    setShowDetailDialog(true);
    setDetailLoading(true);

    // 在弹框内部异步加载数据
    loadRoleDetail(role.id);
  };

  // 加载角色详情的独立函数
  const loadRoleDetail = async (roleId: string) => {
    try {
      console.log('查看角色详情，使用角色ID:', roleId);

      // 调用API获取角色详情
      const roleDetail = await getRoleDetail(roleId);

      // 将API返回的数据转换为页面格式
      const detailedRole: Role = {
        ...selectedRole,
        name: roleDetail.name,
        description: roleDetail.description,
        id: roleDetail.id, // 使用API返回的真实ID
        code: selectedRole?.code || roleDetail.id, // 保持原有的code
        tenant_id: roleDetail.tenant_id,
        createdAt: roleDetail.created_at,
        updatedAt: roleDetail.updated_at,
        menuIds: selectedRole?.menuIds || [],
        permissionIds: selectedRole?.permissionIds || [],
      };

      setSelectedRole(detailedRole);

    } catch (error: any) {
      console.error('获取角色详情失败:', error);

      // 处理API返回的错误信息
      if (error?.data?.message) {
        toast.error(error.data.message);
      } else if (error?.data?.detail?.original_detail) {
        toast.error(error.data.detail.original_detail);
      } else if (error?.message) {
        toast.error(error.message);
      } else {
        toast.error('获取角色详情失败');
      }
    } finally {
      setDetailLoading(false);
    }
  };

  return (
    <div className="space-y-6">
      <RoleManagementHeader
        onAddRole={handleAddRole}
      />

      {/* 统计卡片 */}
      <RoleManagementStatsCards roles={roles} />

      {/* 搜索表单、数据表格和分页 */}
      <SearchFormPagination
        formTitle="角色列表"
        searchFields={searchFields}
        columns={columns}
        data={roles}
        loading={loading}
        error={null}
        pagination={pagination}
        onPageChange={handlePageChange}
        onSizeChange={handleSizeChange}
        onSearch={handleSearch}
        emptyText="暂无角色数据"
        sizeOptions={[10, 20, 50, 100]}
      />

      {/* 添加/编辑表单 */}
      <RoleFormDialog
        open={showForm}
        onOpenChange={handleFormDialogClose}
        editingRole={editingRole}
        formData={formData}
        onFormDataChange={setFormData}
        onSave={handleSave}
        editFormLoading={editFormLoading}
      />

      {/* 详情对话框 */}
      <RoleDetailDialog
        open={showDetailDialog}
        onOpenChange={handleDetailDialogClose}
        selectedRole={selectedRole}
        detailLoading={detailLoading}
      />

      {/* 删除确认对话框 */}
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除角色</AlertDialogTitle>
            <AlertDialogDescription>
              您确定要删除这个角色吗？此操作不可撤销，删除后相关的权限配置也将被清除。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={handleCancelDelete}>取消</AlertDialogCancel>
            <AlertDialogAction onClick={handleConfirmDelete} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
              确认删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 使用说明 */}
      <RoleManagementInstructions />
    </div>
  );
}