/**
 * @ai-summary React Query hooks for admin user management
 * @ai-context List users, change tiers, deactivate/reactivate
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useAuth0 } from '@auth0/auth0-react';
import { adminApi } from '../api/admin.api';
import {
  ListUsersParams,
  UpdateUserTierRequest,
  DeactivateUserRequest,
  UpdateUserProfileRequest,
  PromoteToAdminRequest,
} from '../types/admin.types';
import toast from 'react-hot-toast';

interface ApiError {
  response?: {
    data?: {
      error?: string;
      message?: string;
    };
  };
  message?: string;
}

// Query keys for user management
export const userQueryKeys = {
  all: ['admin-users'] as const,
  list: (params: ListUsersParams) => [...userQueryKeys.all, 'list', params] as const,
  detail: (auth0Sub: string) => [...userQueryKeys.all, 'detail', auth0Sub] as const,
  vehicles: (auth0Sub: string) => [...userQueryKeys.all, 'vehicles', auth0Sub] as const,
};

// Query keys for admin stats
export const adminStatsQueryKeys = {
  all: ['admin-stats'] as const,
};

/**
 * Hook to list users with pagination and filters
 */
export const useUsers = (params: ListUsersParams = {}) => {
  const { isAuthenticated, isLoading } = useAuth0();

  return useQuery({
    queryKey: userQueryKeys.list(params),
    queryFn: () => adminApi.users.list(params),
    enabled: isAuthenticated && !isLoading,
    staleTime: 2 * 60 * 1000, // 2 minutes
    gcTime: 5 * 60 * 1000, // 5 minutes cache time
    retry: 1,
    refetchOnWindowFocus: false,
  });
};

/**
 * Hook to get a single user's details
 */
export const useUser = (auth0Sub: string) => {
  const { isAuthenticated, isLoading } = useAuth0();

  return useQuery({
    queryKey: userQueryKeys.detail(auth0Sub),
    queryFn: () => adminApi.users.get(auth0Sub),
    enabled: isAuthenticated && !isLoading && !!auth0Sub,
    staleTime: 2 * 60 * 1000,
    gcTime: 5 * 60 * 1000,
    retry: 1,
  });
};

/**
 * Hook to update a user's subscription tier
 */
export const useUpdateUserTier = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ auth0Sub, data }: { auth0Sub: string; data: UpdateUserTierRequest }) =>
      adminApi.users.updateTier(auth0Sub, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: userQueryKeys.all });
      toast.success('Subscription tier updated');
    },
    onError: (error: ApiError) => {
      toast.error(
        error.response?.data?.message ||
          error.response?.data?.error ||
          'Failed to update tier'
      );
    },
  });
};

/**
 * Hook to deactivate a user (soft delete)
 */
export const useDeactivateUser = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ auth0Sub, data }: { auth0Sub: string; data?: DeactivateUserRequest }) =>
      adminApi.users.deactivate(auth0Sub, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: userQueryKeys.all });
      toast.success('User deactivated');
    },
    onError: (error: ApiError) => {
      toast.error(
        error.response?.data?.message ||
          error.response?.data?.error ||
          'Failed to deactivate user'
      );
    },
  });
};

/**
 * Hook to reactivate a deactivated user
 */
export const useReactivateUser = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (auth0Sub: string) => adminApi.users.reactivate(auth0Sub),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: userQueryKeys.all });
      toast.success('User reactivated');
    },
    onError: (error: ApiError) => {
      toast.error(
        error.response?.data?.message ||
          error.response?.data?.error ||
          'Failed to reactivate user'
      );
    },
  });
};

/**
 * Hook to update a user's profile (email, displayName)
 */
export const useUpdateUserProfile = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ auth0Sub, data }: { auth0Sub: string; data: UpdateUserProfileRequest }) =>
      adminApi.users.updateProfile(auth0Sub, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: userQueryKeys.all });
      toast.success('User profile updated');
    },
    onError: (error: ApiError) => {
      toast.error(
        error.response?.data?.message ||
          error.response?.data?.error ||
          'Failed to update user profile'
      );
    },
  });
};

/**
 * Hook to promote a user to admin
 */
export const usePromoteToAdmin = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ auth0Sub, data }: { auth0Sub: string; data?: PromoteToAdminRequest }) =>
      adminApi.users.promoteToAdmin(auth0Sub, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: userQueryKeys.all });
      toast.success('User promoted to admin');
    },
    onError: (error: ApiError) => {
      toast.error(
        error.response?.data?.message ||
          error.response?.data?.error ||
          'Failed to promote user to admin'
      );
    },
  });
};

/**
 * Hook to hard delete a user (GDPR permanent deletion)
 */
export const useHardDeleteUser = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ auth0Sub, reason }: { auth0Sub: string; reason?: string }) =>
      adminApi.users.hardDelete(auth0Sub, reason),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: userQueryKeys.all });
      toast.success('User permanently deleted');
    },
    onError: (error: ApiError) => {
      toast.error(
        error.response?.data?.message ||
          error.response?.data?.error ||
          'Failed to delete user'
      );
    },
  });
};

/**
 * Hook to get admin dashboard stats (total vehicles, total users)
 */
export const useAdminStats = () => {
  const { isAuthenticated, isLoading } = useAuth0();

  return useQuery({
    queryKey: adminStatsQueryKeys.all,
    queryFn: () => adminApi.getStats(),
    enabled: isAuthenticated && !isLoading,
    staleTime: 2 * 60 * 1000, // 2 minutes
    gcTime: 5 * 60 * 1000, // 5 minutes cache time
    retry: 1,
    refetchOnWindowFocus: false,
  });
};

/**
 * Hook to get a user's vehicles (admin view - year, make, model only)
 */
export const useUserVehicles = (auth0Sub: string) => {
  const { isAuthenticated, isLoading } = useAuth0();

  return useQuery({
    queryKey: userQueryKeys.vehicles(auth0Sub),
    queryFn: () => adminApi.users.getVehicles(auth0Sub),
    enabled: isAuthenticated && !isLoading && !!auth0Sub,
    staleTime: 2 * 60 * 1000,
    gcTime: 5 * 60 * 1000,
    retry: 1,
  });
};
