import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { adminService } from "./service";
import type {
  AddLeagueTierDto,
  AdminPaginationParams,
  UpdateLeagueTierDto,
  UpdateSettingDto,
  UpdateUserRoleDto,
  UpdateUserSubscriptionDto,
} from "./types";

export const AdminQueryKeys = {
  all: ["admin"] as const,
  analytics: () => [...AdminQueryKeys.all, "analytics"] as const,
  modelPerformance: (days?: number) =>
    [...AdminQueryKeys.all, "modelPerformance", days] as const,
  settings: () => [...AdminQueryKeys.all, "settings"] as const,
  usageLimits: (params?: AdminPaginationParams) =>
    [...AdminQueryKeys.all, "usageLimits", params] as const,
  usersList: () => [...AdminQueryKeys.all, "users"] as const,
  users: (params?: AdminPaginationParams) =>
    [...AdminQueryKeys.usersList(), params] as const,
  user: (id: string) => [...AdminQueryKeys.all, "user", id] as const,
  leagueTiers: () => [...AdminQueryKeys.all, "leagueTiers"] as const,
  leagueTierStats: () => [...AdminQueryKeys.all, "leagueTierStats"] as const,
};

// Analytics
export const useAdminAnalytics = (enabled = true) => {
  return useQuery({
    queryKey: AdminQueryKeys.analytics(),
    queryFn: () => adminService.getAnalyticsOverview(),
    enabled,
  });
};

// Model Performance (forward-test)
export const useModelPerformance = (days = 90, enabled = true) => {
  return useQuery({
    queryKey: AdminQueryKeys.modelPerformance(days),
    queryFn: () => adminService.getModelPerformance(days),
    enabled,
  });
};

// Settings
export const useAdminSettings = () => {
  return useQuery({
    queryKey: AdminQueryKeys.settings(),
    queryFn: () => adminService.getAllSettings(),
  });
};

export const useUpdateSetting = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ key, dto }: { key: string; dto: UpdateSettingDto }) =>
      adminService.updateSetting(key, dto),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: AdminQueryKeys.settings() });
    },
  });
};

// Usage Limits
export const useAdminUsageLimits = (params?: AdminPaginationParams) => {
  return useQuery({
    queryKey: AdminQueryKeys.usageLimits(params),
    queryFn: () => adminService.getAllUsageLimits(params),
  });
};

export const useResetAllUsageLimits = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: () => adminService.resetAllUsageLimits(),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: AdminQueryKeys.usageLimits() });
    },
  });
};

export const useResetUserUsageLimits = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (userId: string) => adminService.resetUserUsageLimits(userId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: AdminQueryKeys.usageLimits() });
      queryClient.invalidateQueries({ queryKey: AdminQueryKeys.users() });
    },
  });
};

// Users
export const useAdminUsers = (
  params?: AdminPaginationParams,
  enabled = true,
) => {
  return useQuery({
    queryKey: AdminQueryKeys.users(params),
    queryFn: () => adminService.getAllUsers(params),
    enabled,
  });
};

export const useAdminUserById = (id: string) => {
  return useQuery({
    queryKey: AdminQueryKeys.user(id),
    queryFn: () => adminService.getUserById(id),
    enabled: !!id,
  });
};

export const useDeleteUser = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: string) => adminService.deleteUser(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: AdminQueryKeys.usersList() });
    },
  });
};

export const useUpdateUserRole = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ id, dto }: { id: string; dto: UpdateUserRoleDto }) =>
      adminService.updateUserRole(id, dto),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: AdminQueryKeys.usersList() });
    },
  });
};

export const useUpdateUserSubscription = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ id, dto }: { id: string; dto: UpdateUserSubscriptionDto }) =>
      adminService.updateUserSubscription(id, dto),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: AdminQueryKeys.usersList() });
    },
  });
};

export const useToggleUserActive = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: string) => adminService.toggleUserActive(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: AdminQueryKeys.usersList() });
    },
  });
};

// ========================
// League Tiers
// ========================

export const useLeagueTiers = (enabled = true) => {
  return useQuery({
    queryKey: AdminQueryKeys.leagueTiers(),
    queryFn: () => adminService.getLeagueTiers(),
    enabled,
  });
};

export const useLeagueTierStats = (enabled = true) => {
  return useQuery({
    queryKey: AdminQueryKeys.leagueTierStats(),
    queryFn: () => adminService.getLeagueTierStats(),
    enabled,
  });
};

export const useAddLeagueTier = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (dto: AddLeagueTierDto) => adminService.addLeagueTier(dto),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: AdminQueryKeys.leagueTiers() });
      queryClient.invalidateQueries({
        queryKey: AdminQueryKeys.leagueTierStats(),
      });
    },
  });
};

export const useUpdateLeagueTier = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({
      leagueId,
      dto,
    }: {
      leagueId: string;
      dto: UpdateLeagueTierDto;
    }) => adminService.updateLeagueTier(leagueId, dto),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: AdminQueryKeys.leagueTiers() });
      queryClient.invalidateQueries({
        queryKey: AdminQueryKeys.leagueTierStats(),
      });
    },
  });
};

export const useDeactivateLeagueTier = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (leagueId: string) =>
      adminService.deactivateLeagueTier(leagueId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: AdminQueryKeys.leagueTiers() });
      queryClient.invalidateQueries({
        queryKey: AdminQueryKeys.leagueTierStats(),
      });
    },
  });
};

export const useDeleteLeagueTier = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (leagueId: string) =>
      adminService.deleteLeagueTier(leagueId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: AdminQueryKeys.leagueTiers() });
      queryClient.invalidateQueries({
        queryKey: AdminQueryKeys.leagueTierStats(),
      });
    },
  });
};

export const useSyncLeagueTiers = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: () => adminService.syncLeagueTiers(),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: AdminQueryKeys.leagueTiers() });
    },
  });
};

export const useTriggerRetrain = () => {
  return useMutation({
    mutationFn: () => adminService.triggerRetrain(),
  });
};
