/**
 * @ai-summary React Query hooks for platform catalog management
 * @ai-context CRUD operations for makes, models, years, trims, engines
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useAuth0 } from '@auth0/auth0-react';
import { adminApi } from '../api/admin.api';
import {
  CreateCatalogMakeRequest,
  UpdateCatalogMakeRequest,
  CreateCatalogModelRequest,
  UpdateCatalogModelRequest,
  CreateCatalogYearRequest,
  CreateCatalogTrimRequest,
  UpdateCatalogTrimRequest,
  CreateCatalogEngineRequest,
  UpdateCatalogEngineRequest,
} from '../types/admin.types';
import toast from 'react-hot-toast';

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

// Makes
export const useMakes = () => {
  const { isAuthenticated, isLoading } = useAuth0();

  return useQuery({
    queryKey: ['catalogMakes'],
    queryFn: () => adminApi.listMakes(),
    enabled: isAuthenticated && !isLoading,
    staleTime: 10 * 60 * 1000, // 10 minutes - catalog data changes infrequently
    gcTime: 30 * 60 * 1000,
    retry: 1,
    refetchOnWindowFocus: false,
  });
};

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

  return useMutation({
    mutationFn: (data: CreateCatalogMakeRequest) => adminApi.createMake(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['catalogMakes'] });
      toast.success('Make created successfully');
    },
    onError: (error: ApiError) => {
      toast.error(error.response?.data?.error || 'Failed to create make');
    },
  });
};

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

  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: UpdateCatalogMakeRequest }) =>
      adminApi.updateMake(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['catalogMakes'] });
      toast.success('Make updated successfully');
    },
    onError: (error: ApiError) => {
      toast.error(error.response?.data?.error || 'Failed to update make');
    },
  });
};

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

  return useMutation({
    mutationFn: (id: string) => adminApi.deleteMake(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['catalogMakes'] });
      toast.success('Make deleted successfully');
    },
    onError: (error: ApiError) => {
      toast.error(error.response?.data?.error || 'Failed to delete make');
    },
  });
};

// Models
export const useModels = (makeId?: string) => {
  const { isAuthenticated, isLoading } = useAuth0();

  return useQuery({
    queryKey: ['catalogModels', makeId],
    queryFn: () => adminApi.listModels(makeId as string),
    enabled: Boolean(makeId) && isAuthenticated && !isLoading,
    staleTime: 10 * 60 * 1000,
    gcTime: 30 * 60 * 1000,
    retry: 1,
    refetchOnWindowFocus: false,
  });
};

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

  return useMutation({
    mutationFn: (data: CreateCatalogModelRequest) => adminApi.createModel(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['catalogModels'] });
      toast.success('Model created successfully');
    },
    onError: (error: ApiError) => {
      toast.error(error.response?.data?.error || 'Failed to create model');
    },
  });
};

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

  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: UpdateCatalogModelRequest }) =>
      adminApi.updateModel(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['catalogModels'] });
      toast.success('Model updated successfully');
    },
    onError: (error: ApiError) => {
      toast.error(error.response?.data?.error || 'Failed to update model');
    },
  });
};

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

  return useMutation({
    mutationFn: (id: string) => adminApi.deleteModel(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['catalogModels'] });
      toast.success('Model deleted successfully');
    },
    onError: (error: ApiError) => {
      toast.error(error.response?.data?.error || 'Failed to delete model');
    },
  });
};

// Years
export const useYears = (modelId?: string) => {
  const { isAuthenticated, isLoading } = useAuth0();

  return useQuery({
    queryKey: ['catalogYears', modelId],
    queryFn: () => adminApi.listYears(modelId as string),
    enabled: Boolean(modelId) && isAuthenticated && !isLoading,
    staleTime: 10 * 60 * 1000,
    gcTime: 30 * 60 * 1000,
    retry: 1,
    refetchOnWindowFocus: false,
  });
};

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

  return useMutation({
    mutationFn: (data: CreateCatalogYearRequest) => adminApi.createYear(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['catalogYears'] });
      toast.success('Year created successfully');
    },
    onError: (error: ApiError) => {
      toast.error(error.response?.data?.error || 'Failed to create year');
    },
  });
};

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

  return useMutation({
    mutationFn: (id: string) => adminApi.deleteYear(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['catalogYears'] });
      toast.success('Year deleted successfully');
    },
    onError: (error: ApiError) => {
      toast.error(error.response?.data?.error || 'Failed to delete year');
    },
  });
};

// Trims
export const useTrims = (yearId?: string) => {
  const { isAuthenticated, isLoading } = useAuth0();

  return useQuery({
    queryKey: ['catalogTrims', yearId],
    queryFn: () => adminApi.listTrims(yearId as string),
    enabled: Boolean(yearId) && isAuthenticated && !isLoading,
    staleTime: 10 * 60 * 1000,
    gcTime: 30 * 60 * 1000,
    retry: 1,
    refetchOnWindowFocus: false,
  });
};

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

  return useMutation({
    mutationFn: (data: CreateCatalogTrimRequest) => adminApi.createTrim(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['catalogTrims'] });
      toast.success('Trim created successfully');
    },
    onError: (error: ApiError) => {
      toast.error(error.response?.data?.error || 'Failed to create trim');
    },
  });
};

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

  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: UpdateCatalogTrimRequest }) =>
      adminApi.updateTrim(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['catalogTrims'] });
      toast.success('Trim updated successfully');
    },
    onError: (error: ApiError) => {
      toast.error(error.response?.data?.error || 'Failed to update trim');
    },
  });
};

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

  return useMutation({
    mutationFn: (id: string) => adminApi.deleteTrim(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['catalogTrims'] });
      toast.success('Trim deleted successfully');
    },
    onError: (error: ApiError) => {
      toast.error(error.response?.data?.error || 'Failed to delete trim');
    },
  });
};

// Engines
export const useEngines = (trimId?: string) => {
  const { isAuthenticated, isLoading } = useAuth0();

  return useQuery({
    queryKey: ['catalogEngines', trimId],
    queryFn: () => adminApi.listEngines(trimId as string),
    enabled: Boolean(trimId) && isAuthenticated && !isLoading,
    staleTime: 10 * 60 * 1000,
    gcTime: 30 * 60 * 1000,
    retry: 1,
    refetchOnWindowFocus: false,
  });
};

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

  return useMutation({
    mutationFn: (data: CreateCatalogEngineRequest) => adminApi.createEngine(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['catalogEngines'] });
      toast.success('Engine created successfully');
    },
    onError: (error: ApiError) => {
      toast.error(error.response?.data?.error || 'Failed to create engine');
    },
  });
};

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

  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: UpdateCatalogEngineRequest }) =>
      adminApi.updateEngine(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['catalogEngines'] });
      toast.success('Engine updated successfully');
    },
    onError: (error: ApiError) => {
      toast.error(error.response?.data?.error || 'Failed to update engine');
    },
  });
};

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

  return useMutation({
    mutationFn: (id: string) => adminApi.deleteEngine(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['catalogEngines'] });
      toast.success('Engine deleted successfully');
    },
    onError: (error: ApiError) => {
      toast.error(error.response?.data?.error || 'Failed to delete engine');
    },
  });
};

// Catalog Search
export const useCatalogSearch = (query: string, page: number = 1, pageSize: number = 50) => {
  const { isAuthenticated, isLoading } = useAuth0();

  return useQuery({
    queryKey: ['catalogSearch', query, page, pageSize],
    queryFn: () => adminApi.searchCatalog(query, page, pageSize),
    enabled: isAuthenticated && !isLoading && query.length > 0,
    staleTime: 30 * 1000, // 30 seconds - search results can change
    gcTime: 5 * 60 * 1000,
    retry: 1,
    refetchOnWindowFocus: false,
  });
};

// Import/Export
export const useImportPreview = () => {
  return useMutation({
    mutationFn: (file: File) => adminApi.importPreview(file),
    onError: (error: ApiError) => {
      toast.error(error.response?.data?.error || 'Failed to preview import');
    },
  });
};

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

  return useMutation({
    mutationFn: (previewId: string) => adminApi.importApply(previewId),
    onSuccess: () => {
      // Invalidate cache to refresh catalog data
      queryClient.invalidateQueries({ queryKey: ['catalogSearch'] });
      // Note: Toast and dialog behavior now handled by parent components
    },
    onError: (error: ApiError) => {
      toast.error(error.response?.data?.error || 'Failed to apply import');
    },
  });
};

export const useExportCatalog = () => {
  return useMutation({
    mutationFn: () => adminApi.exportCatalog(),
    onSuccess: (blob) => {
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = 'vehicle-catalog.csv';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      toast.success('Catalog exported successfully');
    },
    onError: (error: ApiError) => {
      toast.error(error.response?.data?.error || 'Failed to export catalog');
    },
  });
};

// Cascade Delete
export const useDeleteMakeCascade = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: string) => adminApi.deleteMakeCascade(id),
    onSuccess: (result) => {
      queryClient.invalidateQueries({ queryKey: ['catalogMakes'] });
      queryClient.invalidateQueries({ queryKey: ['catalogSearch'] });
      toast.success(`Deleted ${result.totalDeleted} items (cascade)`);
    },
    onError: (error: ApiError) => {
      toast.error(error.response?.data?.error || 'Failed to cascade delete make');
    },
  });
};

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

  return useMutation({
    mutationFn: (id: string) => adminApi.deleteModelCascade(id),
    onSuccess: (result) => {
      queryClient.invalidateQueries({ queryKey: ['catalogModels'] });
      queryClient.invalidateQueries({ queryKey: ['catalogSearch'] });
      toast.success(`Deleted ${result.totalDeleted} items (cascade)`);
    },
    onError: (error: ApiError) => {
      toast.error(error.response?.data?.error || 'Failed to cascade delete model');
    },
  });
};

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

  return useMutation({
    mutationFn: (id: string) => adminApi.deleteYearCascade(id),
    onSuccess: (result) => {
      queryClient.invalidateQueries({ queryKey: ['catalogYears'] });
      queryClient.invalidateQueries({ queryKey: ['catalogSearch'] });
      toast.success(`Deleted ${result.totalDeleted} items (cascade)`);
    },
    onError: (error: ApiError) => {
      toast.error(error.response?.data?.error || 'Failed to cascade delete year');
    },
  });
};

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

  return useMutation({
    mutationFn: (id: string) => adminApi.deleteTrimCascade(id),
    onSuccess: (result) => {
      queryClient.invalidateQueries({ queryKey: ['catalogTrims'] });
      queryClient.invalidateQueries({ queryKey: ['catalogSearch'] });
      toast.success(`Deleted ${result.totalDeleted} items (cascade)`);
    },
    onError: (error: ApiError) => {
      toast.error(error.response?.data?.error || 'Failed to cascade delete trim');
    },
  });
};
