// frontend/src/api/hooks/equipment.ts
/**
 * React hooks for Equipment API integration
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { showToast } from '../../utils/toast';
import { equipmentService } from '../services/equipment';
import type { Equipment, EquipmentDeletionSummary } from '../types/equipment';

// Query Keys
export const equipmentKeys = {
  all: ['equipment'] as const,
  lists: () => [...equipmentKeys.all, 'list'] as const,
  list: (tenantId: string, filters?: Record<string, any>) =>
    [...equipmentKeys.lists(), tenantId, filters] as const,
  details: () => [...equipmentKeys.all, 'detail'] as const,
  detail: (tenantId: string, equipmentId: string) =>
    [...equipmentKeys.details(), tenantId, equipmentId] as const,
};

/**
 * Hook to fetch equipment list
 */
export function useEquipment(
  tenantId: string,
  filters?: {
    status?: string;
    type?: string;
    is_active?: boolean;
  },
  options?: { enabled?: boolean }
) {
  return useQuery({
    queryKey: equipmentKeys.list(tenantId, filters),
    queryFn: () => equipmentService.getEquipment(tenantId, filters),
    enabled: !!tenantId && (options?.enabled ?? true),
    staleTime: 5 * 60 * 1000, // 5 minutes
  });
}

/**
 * Hook to fetch a specific equipment item
 */
export function useEquipmentById(
  tenantId: string,
  equipmentId: string,
  options?: { enabled?: boolean }
) {
  return useQuery({
    queryKey: equipmentKeys.detail(tenantId, equipmentId),
    queryFn: () => equipmentService.getEquipmentById(tenantId, equipmentId),
    enabled: !!tenantId && !!equipmentId && (options?.enabled ?? true),
    staleTime: 10 * 60 * 1000, // 10 minutes
  });
}

/**
 * Hook to create equipment
 */
export function useCreateEquipment(tenantId: string) {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (equipmentData: Equipment) =>
      equipmentService.createEquipment(tenantId, equipmentData),
    onSuccess: (newEquipment) => {
      // Invalidate and refetch equipment lists
      queryClient.invalidateQueries({ queryKey: equipmentKeys.lists() });

      // Add to cache
      queryClient.setQueryData(
        equipmentKeys.detail(tenantId, newEquipment.id),
        newEquipment
      );

      showToast.success('Equipment created successfully');
    },
    onError: (error: any) => {
      console.error('Error creating equipment:', error);
      showToast.error(error.response?.data?.detail || 'Error creating equipment');
    },
  });
}

/**
 * Hook to update equipment
 */
export function useUpdateEquipment(tenantId: string) {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ equipmentId, equipmentData }: {
      equipmentId: string;
      equipmentData: Partial<Equipment>;
    }) => equipmentService.updateEquipment(tenantId, equipmentId, equipmentData),
    onSuccess: (updatedEquipment, { equipmentId }) => {
      // Update cached data
      queryClient.setQueryData(
        equipmentKeys.detail(tenantId, equipmentId),
        updatedEquipment
      );

      // Invalidate lists to refresh
      queryClient.invalidateQueries({ queryKey: equipmentKeys.lists() });

      showToast.success('Equipment updated successfully');
    },
    onError: (error: any) => {
      console.error('Error updating equipment:', error);
      showToast.error(error.response?.data?.detail || 'Error updating equipment');
    },
  });
}

/**
 * Hook to delete equipment (soft delete)
 */
export function useDeleteEquipment(tenantId: string) {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (equipmentId: string) =>
      equipmentService.deleteEquipment(tenantId, equipmentId),
    onSuccess: (_, equipmentId) => {
      // Remove from cache
      queryClient.removeQueries({
        queryKey: equipmentKeys.detail(tenantId, equipmentId)
      });

      // Invalidate lists to refresh
      queryClient.invalidateQueries({ queryKey: equipmentKeys.lists() });

      showToast.success('Equipment deleted successfully');
    },
    onError: (error: any) => {
      console.error('Error deleting equipment:', error);
      showToast.error(error.response?.data?.detail || 'Error deleting equipment');
    },
  });
}

/**
 * Hook to hard delete equipment (permanent deletion)
 */
export function useHardDeleteEquipment(tenantId: string) {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (equipmentId: string) =>
      equipmentService.hardDeleteEquipment(tenantId, equipmentId),
    onSuccess: (_, equipmentId) => {
      // Remove from cache
      queryClient.removeQueries({
        queryKey: equipmentKeys.detail(tenantId, equipmentId)
      });

      // Invalidate lists to refresh
      queryClient.invalidateQueries({ queryKey: equipmentKeys.lists() });

      showToast.success('Equipment permanently deleted');
    },
    onError: (error: any) => {
      console.error('Error hard deleting equipment:', error);
      showToast.error(error.response?.data?.detail || 'Error permanently deleting equipment');
    },
  });
}

/**
 * Hook to get equipment deletion summary
 */
export function useEquipmentDeletionSummary(
  tenantId: string,
  equipmentId: string,
  options?: { enabled?: boolean }
) {
  return useQuery({
    queryKey: [...equipmentKeys.detail(tenantId, equipmentId), 'deletion-summary'],
    queryFn: () => equipmentService.getEquipmentDeletionSummary(tenantId, equipmentId),
    enabled: !!tenantId && !!equipmentId && (options?.enabled ?? true),
    staleTime: 0, // Always fetch fresh data for dependency checks
  });
}
