// @ts-nocheck
/**
 * filekorolheader: 用户管理页面 - 用户查询和管理页面
 * 功能：用户列表查询、搜索筛选、详情查看、用户管理
 * 路径：/central-config/tenant/user-management
 * 规范：遵循crop-x/docs/开发项目规范.md，使用SearchFormPagination公共组件，shadcn语义化样式
 */
'use client';

import { useReducer, useEffect, useState, useCallback, useMemo,useRef } 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 { Eye, Edit, Lock, UserX, UserCheck, Trash2 } from 'lucide-react';
import { UserDetailDialog } from './components/UserDetailDialog';
import { AddUserModal } from './components/AddUserModal';
import { EditUserModal } from './components/EditUserModal';
import { SearchFormPagination, SearchFieldConfig, TableColumnConfig } from '@/components/common/searchFormPagination';

import { fetchUsers, transformUserData, UsersQueryParams, User, UsersApiResponse, PaginationState, activateUser, deactivateUser, deleteUser } from './components/userManagementApi';
import { UserManagementHeader } from './components/UserManagementHeader';
import { UserManagementStatsCards } from './components/UserManagementStatsCards';
import { UserFilters } from './types';

// 移除了Enterprise的引用，因为新实现中不再需要

// 用户管理状态管理
interface UserManagementState {
  users: User[];
  loading: boolean;
  error: string | null;
  pagination: PaginationState;
  filters: UserFilters;
  sortBy?: string;
  sortOrder: 'asc' | 'desc';
  selectedUser: User | null;
  showDetailDialog: boolean;
  showAddDialog: boolean;
  showEditDialog: boolean;
  showDeactivateDialog: boolean;
  showDeleteDialog: boolean;
}

type UserManagementAction =
  | { type: 'SET_USERS'; payload: { data: User[]; pagination: PaginationState } }
  | { type: 'SET_LOADING'; payload: boolean }
  | { type: 'SET_ERROR'; payload: string | null }
  | { type: 'SET_FILTERS'; payload: Partial<UserFilters> }
  | { type: 'SET_SORT'; payload: { sortBy?: string; sortOrder: 'asc' | 'desc' } }
  | { type: 'SET_PAGINATION'; payload: Partial<PaginationState> }
  | { type: 'SET_SELECTED_USER'; payload: User | null }
  | { type: 'TOGGLE_DETAIL_DIALOG'; payload: boolean }
  | { type: 'TOGGLE_ADD_DIALOG'; payload: boolean }
  | { type: 'TOGGLE_EDIT_DIALOG'; payload: boolean }
  | { type: 'TOGGLE_DEACTIVATE_DIALOG'; payload: boolean }
  | { type: 'TOGGLE_DELETE_DIALOG'; payload: boolean }
  | { type: 'REFRESH_DATA' };

const userManagementReducer = (state: UserManagementState, action: UserManagementAction): UserManagementState => {
  switch (action.type) {
    case 'SET_USERS':
      return {
        ...state,
        users: action.payload.data,
        pagination: action.payload.pagination,
        loading: false,
        error: null,
      };
    case 'SET_LOADING':
      return { ...state, loading: action.payload };
    case 'SET_ERROR':
      return { ...state, error: action.payload, loading: false };
    case 'SET_FILTERS':
      return { ...state, filters: { ...state.filters, ...action.payload } };
    case 'SET_SORT':
      return { ...state, sortBy: action.payload.sortBy, sortOrder: action.payload.sortOrder };
    case 'SET_PAGINATION':
      return { ...state, pagination: { ...state.pagination, ...action.payload } };
    case 'SET_SELECTED_USER':
      return { ...state, selectedUser: action.payload };
    case 'TOGGLE_DETAIL_DIALOG':
      return { ...state, showDetailDialog: !state.showDetailDialog };
    case 'TOGGLE_ADD_DIALOG':
      return { ...state, showAddDialog: !state.showAddDialog };
    case 'TOGGLE_EDIT_DIALOG':
      return { ...state, showEditDialog: !state.showEditDialog };
    case 'TOGGLE_DEACTIVATE_DIALOG':
      return { ...state, showDeactivateDialog: !state.showDeactivateDialog };
    case 'TOGGLE_DELETE_DIALOG':
      return { ...state, showDeleteDialog: !state.showDeleteDialog };
    case 'REFRESH_DATA':
      return { ...state, error: null };
    default:
      return state;
  }
};

const initialState: UserManagementState = {
  users: [],
  loading: false,
  error: null,
  pagination: {
    page: 1,
    size: 10,
    total: 0,
    totalPages: 0,
    hasNext: false,
    hasPrev: false,
  },
  filters: {
    searchKeyword: '',
    statusFilter: 'all',
    typeFilter: 'all'
  },
  sortBy: 'created_at',
  sortOrder: 'desc',
  selectedUser: null,
  showDetailDialog: false,
  showAddDialog: false,
  showEditDialog: false,
  showDeactivateDialog: false,
  showDeleteDialog: false,
};

export default function TenantUserManagementPage() {
  const [state, dispatch] = useReducer(userManagementReducer, initialState);

  // 搜索字段配置
  const searchFields: SearchFieldConfig[] = useMemo(() => [
    {
      key: 'search',
      label: '搜索',
      type: 'text',
      placeholder: '搜索用户名、姓名、邮箱...',
    },
    {
      key: 'status',
      label: '用户状态',
      type: 'select',
      defaultValue: 'all',
      options: [
        { value: 'all', label: '全部状态' },
        { value: 'active', label: '活跃' },
        { value: 'inactive', label: '未激活' },
      ],
    },
    {
      key: 'type',
      label: '用户类型',
      type: 'select',
      defaultValue: 'all',
      options: [
        { value: 'all', label: '全部类型' },
        { value: 'admin', label: '管理员' },
        { value: 'user', label: '普通用户' },
        { value: 'staff', label: '员工' },
      ],
    },
  ], []);

  // 表格列配置
  const columns: TableColumnConfig[] = useMemo(() => [
    {
      key: 'username',
      label: '用户名',
      sortable: true,
      render: (value: string, user: User) => (
        <div className="font-medium">{value}</div>
      ),
    },
    {
      key: 'fullName',
      label: '姓名',
      sortable: true,
      render: (value: string) => value || '-',
    },
    {
      key: 'email',
      label: '邮箱',
      sortable: true,
      render: (value: string) => value || '-',
    },
    {
      key: 'isActive',
      label: '状态',
      sortable: true,
      render: (value: boolean) => (
        <div className={`inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium ${
          value
            ? 'bg-green-50 dark:bg-green-950 text-green-600 dark:text-green-400'
            : 'bg-red-50 dark:bg-red-950 text-red-600 dark:text-red-400'
        }`}>
          <div className={`w-2 h-2 rounded-full ${value ? 'bg-green-500' : 'bg-red-500'}`} />
          {value ? '活跃' : '未激活'}
        </div>
      ),
    },
    {
      key: 'isSuperuser',
      label: '角色',
      sortable: true,
      render: (value: boolean, user: User) => {
        if (value) {
          return (
            <div className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium bg-purple-50 dark:bg-purple-950 text-purple-600 dark:text-purple-400">
              <div className="w-2 h-2 rounded-full bg-purple-500" />
              超级管理员
            </div>
          );
        }
        return (
          <div className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium bg-blue-50 dark:bg-blue-950 text-blue-600 dark:text-blue-400">
            <div className="w-2 h-2 rounded-full bg-blue-500" />
            普通用户
          </div>
        );
      },
    },
    {
      key: 'isVerified',
      label: '验证',
      sortable: true,
      render: (value: boolean) => (
        <div className={`inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium ${
          value
            ? 'bg-orange-50 dark:bg-orange-950 text-orange-600 dark:text-orange-400'
            : 'bg-gray-50 dark:bg-gray-950 text-gray-600 dark:text-gray-400'
        }`}>
          {value ? '已验证' : '未验证'}
        </div>
      ),
    },
    {
      key: 'lastLoginAt',
      label: '最后登录',
      sortable: true,
      render: (value: string) => {
        if (!value) return '-';
        try {
          const date = new Date(value);
          return date.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
          });
        } catch {
          return value;
        }
      },
    },
    {
      key: 'actions',
      label: '操作',
      render: (_, user: User) => (
        <div className="flex items-center gap-2">
          <Button
            variant="ghost"
            size="sm"
            onClick={() => handleViewDetail(user)}
            title="查看"
          >
            <Eye className="w-4 h-4" />
          </Button>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => handleEdit(user)}
            title="编辑"
          >
            <Edit className="w-4 h-4" />
          </Button>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => handleToggleStatus(user)}
            title={user.isActive ? "停用用户" : "激活用户"}
          >
            {user.isActive ? (
              <UserX className="w-4 h-4 text-orange-600" />
            ) : (
              <UserCheck className="w-4 h-4 text-green-600" />
            )}
          </Button>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => handleDelete(user)}
            title="删除用户"
            className="text-red-600 hover:text-red-700 hover:bg-red-50"
          >
            <Trash2 className="w-4 h-4" />
          </Button>
        </div>
      ),
    },
  ], []);

  // 加载用户数据
  const loadUsers = useCallback(async (options: {
    resetPage?: boolean;
    filters?: UserFilters;
    sortBy?: string;
    sortOrder?: 'asc' | 'desc';
    page?: number;
    size?: number;
  } = {}) => {
    try {
      // 优先从URL读取参数
      let urlParams = {};
      if (typeof window !== 'undefined') {
        const params = new URLSearchParams(window.location.search);
        urlParams = {
          search: params.get('search') || undefined,
          status: params.get('status') || undefined,
          type: params.get('type') || undefined,
          page: params.get('page') ? parseInt(params.get('page')!, 10) : undefined,
          size: params.get('size') ? parseInt(params.get('size')!, 10) : undefined
        };
        console.log('从URL读取的参数:', urlParams);
      }

      dispatch({ type: 'SET_LOADING', payload: true });

      // 解构选项参数，提供默认值
      const {
        resetPage = false,
        filters,
        sortBy,
        sortOrder,
        page,
        size
      } = options;

      // 优先级：URL参数 > 传入参数 > 父组件状态
      const finalPage = resetPage ? 1 : (urlParams.page || page || state.pagination.page);
      const finalSize = urlParams.size || size || state.pagination.size;

      const params: UsersQueryParams = {
        page: finalPage,
        size: finalSize,
        is_active: true,
      };

      // 使用正确的优先级：URL参数 > 传入参数 > 父组件状态
      const currentFilters = {
        searchKeyword: urlParams.search || (filters?.searchKeyword) || state.filters.searchKeyword,
        statusFilter: urlParams.status || (filters?.statusFilter) || state.filters.statusFilter,
        typeFilter: urlParams.type || (filters?.typeFilter) || state.filters.typeFilter
      };
      const currentSortBy = sortBy || state.sortBy;
      const currentSortOrder = sortOrder || state.sortOrder;

      // 添加搜索条件
      if (currentFilters.searchKeyword) {
        params.search = currentFilters.searchKeyword;
      }

      if (currentFilters.statusFilter && currentFilters.statusFilter !== 'all') {
        params.is_active = currentFilters.statusFilter === 'active';
      }

      if (currentFilters.typeFilter && currentFilters.typeFilter !== 'all') {
        // For user type filtering, we'll need to handle this differently based on the API
        // For now, we'll filter on the client side if needed
      }

      if (currentSortBy) {
        params.order_by = currentSortBy;
        params.sort_order = currentSortOrder;
      }

      const response: UsersApiResponse = await fetchUsers(params);
      const transformedUsers = response.data.map(transformUserData);

      dispatch({
        type: 'SET_USERS',
        payload: {
          data: transformedUsers,
          pagination: {
            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 users:', error);
      dispatch({
        type: 'SET_ERROR',
        payload: error instanceof Error ? error.message : '加载用户数据失败'
      });
    }
  }, []);

  // 搜索处理 - 保持传统的简洁方式
  const handleSearch = useCallback((filters: Record<string, string>) => {
    console.log('用户管理页面 - 收到搜索条件:', filters);

    const mappedFilters = {
      searchKeyword: filters.search || '',
      statusFilter: filters.status || 'all',
      typeFilter: filters.type || 'all'
    };

    // 更新过滤器状态
    dispatch({ type: 'SET_FILTERS', payload: mappedFilters });

    // 搜索时重置到第1页
    dispatch({ type: 'SET_PAGINATION', payload: { page: 1, size: state.pagination.size } });

    // 执行查询
    loadUsers({
      resetPage: true,
      page: 1,
      filters: mappedFilters,
      sortBy: state.sortBy,
      sortOrder: state.sortOrder,
      size: state.pagination.size
    });

    console.log('触发用户查询 - 参数:', {
      resetPage: true,
      page: 1,
      filters: mappedFilters,
      sortBy: state.sortBy,
      sortOrder: state.sortOrder,
      size: state.pagination.size
    });
  }, [state.sortBy, state.sortOrder, state.pagination.size, loadUsers]);

  // 排序处理
  const handleSort = useCallback((sortBy: string, sortOrder: 'asc' | 'desc') => {
    dispatch({ type: 'SET_SORT', payload: { sortBy, sortOrder } });
    // 传入所有当前参数，避免覆盖其他参数
    loadUsers({
      resetPage: true,
      filters: state.filters,
      sortBy,
      sortOrder,
      size: state.pagination.size
    });
  }, [state.filters, state.pagination.size]);

  // 分页处理
  const handlePageChange = useCallback((page: number) => {
    if (page < 1) {
      page = 1;
    } else if (page > state.pagination.totalPages && state.pagination.totalPages > 0) {
      page = state.pagination.totalPages;
    }
    dispatch({ type: 'SET_PAGINATION', payload: { page } });
    // 传入所有当前参数，避免覆盖其他参数
    loadUsers({
      page,
      filters: state.filters,
      sortBy: state.sortBy,
      sortOrder: state.sortOrder,
      size: state.pagination.size
    });
  }, [state.filters, state.sortBy, state.sortOrder, state.pagination.size, state.pagination.totalPages]);

  // 每页条数变化处理
  const handleSizeChange = useCallback((size: number) => {
    dispatch({ type: 'SET_PAGINATION', payload: { size, page: 1 } });
    // 传入所有当前参数，避免覆盖其他参数
    loadUsers({
      resetPage: true,
      page: 1,
      size,
      filters: state.filters,
      sortBy: state.sortBy,
      sortOrder: state.sortOrder
    });
  }, [state.filters, state.sortBy, state.sortOrder]);

  // 查看详情
  const handleViewDetail = (user: User) => {
    dispatch({ type: 'SET_SELECTED_USER', payload: user });
    dispatch({ type: 'TOGGLE_DETAIL_DIALOG', payload: true });
  };

  // 编辑用户
  const handleEdit = (user: User) => {
    dispatch({ type: 'SET_SELECTED_USER', payload: user });
    dispatch({ type: 'TOGGLE_EDIT_DIALOG', payload: true });
  };

  // 新增用户
  const handleAdd = () => {
    dispatch({ type: 'TOGGLE_ADD_DIALOG', payload: true });
  };

  // 刷新数据（用于新增/编辑成功后重新加载数据）
  const refreshData = useCallback(() => {
    loadUsers({});
  }, [loadUsers]);

  // 切换用户状态
  const handleToggleStatus = (user: User) => {
    dispatch({ type: 'SET_SELECTED_USER', payload: user });
    dispatch({ type: 'TOGGLE_DEACTIVATE_DIALOG', payload: true });
  };

  // 删除用户
  const handleDelete = (user: User) => {
    dispatch({ type: 'SET_SELECTED_USER', payload: user });
    dispatch({ type: 'TOGGLE_DELETE_DIALOG', payload: true });
  };

  // 确认切换用户状态
  const confirmToggleStatus = async () => {
    if (!state.selectedUser) return;

    try {
      const user = state.selectedUser;
      if (user.isActive) {
        await deactivateUser(user.id);
        toast.success(`用户 ${user.fullName || user.username} 已停用`);
      } else {
        await activateUser(user.id);
        toast.success(`用户 ${user.fullName || user.username} 已激活`);
      }

      // 关闭对话框并刷新列表
      dispatch({ type: 'TOGGLE_DEACTIVATE_DIALOG', payload: false });
      dispatch({ type: 'SET_SELECTED_USER', payload: null });
      refreshData();
    } catch (error) {
      console.error('切换用户状态失败:', error);
      const errorMessage = error instanceof Error ? error.message : '操作失败，请重试';
      toast.error(errorMessage);
    }
  };

  // 确认删除用户
  const confirmDelete = async () => {
    if (!state.selectedUser) return;

    try {
      const user = state.selectedUser;
      await deleteUser(user.id);
      toast.success(`用户 ${user.fullName || user.username} 已删除`);

      // 关闭对话框并刷新列表
      dispatch({ type: 'TOGGLE_DELETE_DIALOG', payload: false });
      dispatch({ type: 'SET_SELECTED_USER', payload: null });
      refreshData();
    } catch (error) {
      console.error('删除用户失败:', error);
      const errorMessage = error instanceof Error ? error.message : '删除失败，请重试';
      toast.error(errorMessage);
    }
  };

  // 统计数据计算
  const stats = useMemo(() => [
    {
      label: '总用户数',
      value: state.pagination.total,
      color: 'text-blue-600 dark:text-blue-400',
      bg: 'bg-blue-50 dark:bg-blue-950',
    },
    {
      label: '活跃用户',
      value: state.users.filter(u => u.isActive).length,
      color: 'text-green-600 dark:text-green-400',
      bg: 'bg-green-50 dark:bg-green-950',
    },
    {
      label: '管理员',
      value: state.users.filter(u => u.isSuperuser).length,
      color: 'text-purple-600 dark:text-purple-400',
      bg: 'bg-purple-50 dark:bg-purple-950',
    },
    {
      label: '已验证',
      value: state.users.filter(u => u.isVerified).length,
      color: 'text-orange-600 dark:text-orange-400',
      bg: 'bg-orange-50 dark:bg-orange-950',
    },
  ], [state.users, state.pagination.total]);

  const didFetchRef = useRef(false)
  useEffect(() => {
    if (didFetchRef.current) return
    didFetchRef.current = true
    loadUsers({})
  }, [])

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <UserManagementHeader stats={stats} />

      {/* 统计卡片 */}
      <UserManagementStatsCards stats={stats} />

      {/* 搜索表单、数据表格和分页 */}
      <SearchFormPagination
        formTitle="用户列表"
        formRightContent={
          <Button onClick={handleAdd}>
            新建用户
          </Button>
        }
        searchFields={searchFields}
        columns={columns}
        data={state.users}
        loading={state.loading}
        error={state.error}
        pagination={state.pagination}
        onPageChange={handlePageChange}
        onSizeChange={handleSizeChange}
        onSearch={handleSearch}
        emptyText="暂无用户数据"
        sizeOptions={[10, 20, 50, 100]}
          />

      {/* 用户详情对话框 */}
      <UserDetailDialog
        open={state.showDetailDialog}
        onOpenChange={(open) => dispatch({ type: 'TOGGLE_DETAIL_DIALOG', payload: open })}
        user={state.selectedUser}
      />

      {/* 新增用户对话框 */}
      <AddUserModal
        open={state.showAddDialog}
        onOpenChange={(open) => dispatch({ type: 'TOGGLE_ADD_DIALOG', payload: open })}
        onSuccess={refreshData}
      />

      {/* 编辑用户对话框 */}
      <EditUserModal
        open={state.showEditDialog}
        onOpenChange={(open) => dispatch({ type: 'TOGGLE_EDIT_DIALOG', payload: open })}
        user={state.selectedUser}
        onSuccess={refreshData}
      />

      {/* 停用/激活用户确认对话框 */}
      <AlertDialog open={state.showDeactivateDialog} onOpenChange={(open) => dispatch({ type: 'TOGGLE_DEACTIVATE_DIALOG', payload: open })}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              {state.selectedUser?.isActive ? '停用用户' : '激活用户'}
            </AlertDialogTitle>
            <AlertDialogDescription>
              确定要{state.selectedUser?.isActive ? '停用' : '激活'}用户 <strong>{state.selectedUser?.fullName || state.selectedUser?.username}</strong> 吗？
              {state.selectedUser?.isActive && (
                <span className="block mt-2 text-amber-600 dark:text-amber-400">
                  停用后，该用户将无法登录系统。
                </span>
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <Button
              onClick={confirmToggleStatus}
              className={state.selectedUser?.isActive ? 'bg-orange-600 hover:bg-orange-700' : 'bg-green-600 hover:bg-green-700'}
            >
              {state.selectedUser?.isActive ? '停用' : '激活'}
            </Button>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 删除用户确认对话框 */}
      <AlertDialog open={state.showDeleteDialog} onOpenChange={(open) => dispatch({ type: 'TOGGLE_DELETE_DIALOG', payload: open })}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="text-red-600">删除用户</AlertDialogTitle>
            <AlertDialogDescription>
              确定要删除用户 <strong>{state.selectedUser?.fullName || state.selectedUser?.username}</strong> 吗？
              <span className="block mt-2 text-red-600 dark:text-red-400">
                ⚠️ 此操作不可恢复，用户的所有数据将被永久删除！
              </span>
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <Button
              onClick={confirmDelete}
              className="bg-red-600 hover:bg-red-700"
              variant="destructive"
            >
              确认删除
            </Button>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}