/**
 * @ai-summary React Query hook for maintenance records
 * @ai-context Provides queries and mutations with proper cache invalidation
 */

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useAuth0 } from '@auth0/auth0-react';
import { maintenanceApi } from '../api/maintenance.api';
import type {
  CreateMaintenanceRecordRequest,
  UpdateMaintenanceRecordRequest,
  MaintenanceRecordResponse,
  CreateScheduleRequest,
  UpdateScheduleRequest,
  MaintenanceScheduleResponse
} from '../types/maintenance.types';

export const useMaintenanceRecords = (vehicleId?: string) => {
  const { isAuthenticated, isLoading } = useAuth0();
  const queryClient = useQueryClient();

  // Query for maintenance records
  const recordsQuery = useQuery<MaintenanceRecordResponse[]>({
    queryKey: ['maintenanceRecords', vehicleId || 'all'],
    queryFn: () => (vehicleId ? maintenanceApi.getRecordsByVehicle(vehicleId) : maintenanceApi.getRecords()),
    enabled: isAuthenticated && !isLoading,
    staleTime: 2 * 60 * 1000, // 2 minutes
    gcTime: 5 * 60 * 1000, // 5 minutes cache time
    retry: (failureCount, error: any) => {
      // Retry 401 errors up to 3 times for mobile auth timing issues
      if (error?.response?.status === 401 && failureCount < 3) {
        console.log(`[Mobile Auth] Maintenance records API retry ${failureCount + 1}/3 for 401 error`);
        return true;
      }
      return false;
    },
    retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
    refetchOnWindowFocus: false,
    refetchOnMount: false,
  });

  // Query for maintenance schedules
  const schedulesQuery = useQuery<MaintenanceScheduleResponse[]>({
    queryKey: ['maintenanceSchedules', vehicleId],
    queryFn: () => maintenanceApi.getSchedulesByVehicle(vehicleId!),
    enabled: !!vehicleId && isAuthenticated && !isLoading,
    staleTime: 5 * 60 * 1000, // 5 minutes - schedules change less frequently
    gcTime: 10 * 60 * 1000, // 10 minutes cache time
    retry: (failureCount, error: any) => {
      if (error?.response?.status === 401 && failureCount < 3) {
        console.log(`[Mobile Auth] Maintenance schedules API retry ${failureCount + 1}/3 for 401 error`);
        return true;
      }
      return false;
    },
    retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
    refetchOnWindowFocus: false,
    refetchOnMount: false,
  });

  // Query for upcoming maintenance
  const upcomingQuery = useQuery<MaintenanceScheduleResponse[]>({
    queryKey: ['maintenanceUpcoming', vehicleId],
    queryFn: () => maintenanceApi.getUpcoming(vehicleId!),
    enabled: !!vehicleId && isAuthenticated && !isLoading,
    staleTime: 5 * 60 * 1000,
    gcTime: 10 * 60 * 1000,
    retry: (failureCount, error: any) => {
      if (error?.response?.status === 401 && failureCount < 3) {
        console.log(`[Mobile Auth] Maintenance upcoming API retry ${failureCount + 1}/3 for 401 error`);
        return true;
      }
      return false;
    },
    retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
    refetchOnWindowFocus: false,
    refetchOnMount: false,
  });

  // Mutations for records
  const createRecordMutation = useMutation({
    mutationFn: (data: CreateMaintenanceRecordRequest) => maintenanceApi.createRecord(data),
    onSuccess: (_res, variables) => {
      queryClient.invalidateQueries({ queryKey: ['maintenanceRecords', variables.vehicleId] });
      queryClient.invalidateQueries({ queryKey: ['maintenanceRecords', 'all'] });
      queryClient.invalidateQueries({ queryKey: ['maintenanceUpcoming', variables.vehicleId] });
    },
  });

  const updateRecordMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: UpdateMaintenanceRecordRequest }) =>
      maintenanceApi.updateRecord(id, data),
    onSuccess: () => {
      // Invalidate all record queries since we don't know the vehicle_id from the response
      queryClient.invalidateQueries({ queryKey: ['maintenanceRecords'] });
      queryClient.invalidateQueries({ queryKey: ['maintenanceUpcoming'] });
    },
  });

  const deleteRecordMutation = useMutation({
    mutationFn: (id: string) => maintenanceApi.deleteRecord(id),
    onSuccess: () => {
      // Invalidate all record queries
      queryClient.invalidateQueries({ queryKey: ['maintenanceRecords'] });
      queryClient.invalidateQueries({ queryKey: ['maintenanceUpcoming'] });
    },
  });

  // Mutations for schedules
  const createScheduleMutation = useMutation({
    mutationFn: (data: CreateScheduleRequest) => maintenanceApi.createSchedule(data),
    onSuccess: (_res, variables) => {
      queryClient.invalidateQueries({ queryKey: ['maintenanceSchedules', variables.vehicleId] });
      queryClient.invalidateQueries({ queryKey: ['maintenanceUpcoming', variables.vehicleId] });
    },
  });

  const updateScheduleMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: UpdateScheduleRequest }) =>
      maintenanceApi.updateSchedule(id, data),
    onSuccess: () => {
      // Invalidate all schedule queries
      queryClient.invalidateQueries({ queryKey: ['maintenanceSchedules'] });
      queryClient.invalidateQueries({ queryKey: ['maintenanceUpcoming'] });
    },
  });

  const deleteScheduleMutation = useMutation({
    mutationFn: (id: string) => maintenanceApi.deleteSchedule(id),
    onSuccess: () => {
      // Invalidate all schedule queries
      queryClient.invalidateQueries({ queryKey: ['maintenanceSchedules'] });
      queryClient.invalidateQueries({ queryKey: ['maintenanceUpcoming'] });
    },
  });

  return {
    // Records
    records: recordsQuery.data,
    isRecordsLoading: recordsQuery.isLoading,
    recordsError: recordsQuery.error,
    createRecord: createRecordMutation.mutateAsync,
    updateRecord: updateRecordMutation.mutateAsync,
    deleteRecord: deleteRecordMutation.mutateAsync,
    isRecordMutating: createRecordMutation.isPending || updateRecordMutation.isPending || deleteRecordMutation.isPending,

    // Schedules
    schedules: schedulesQuery.data,
    isSchedulesLoading: schedulesQuery.isLoading,
    schedulesError: schedulesQuery.error,
    createSchedule: createScheduleMutation.mutateAsync,
    updateSchedule: updateScheduleMutation.mutateAsync,
    deleteSchedule: deleteScheduleMutation.mutateAsync,
    isScheduleMutating: createScheduleMutation.isPending || updateScheduleMutation.isPending || deleteScheduleMutation.isPending,

    // Upcoming
    upcoming: upcomingQuery.data,
    isUpcomingLoading: upcomingQuery.isLoading,
    upcomingError: upcomingQuery.error,
  };
};
