/**
 * @ai-summary React 18 compatible optimistic updates hook for vehicle operations
 * @ai-context Provides optimistic updates for better perceived performance using useState and useTransition
 */

import { useState, useTransition, useEffect } from 'react';
import { Vehicle, CreateVehicleRequest } from '../types/vehicles.types';
import { useQueryClient } from '@tanstack/react-query';
import { vehiclesApi } from '../api/vehicles.api';
import toast from 'react-hot-toast';

type VehicleAction = 
  | { type: 'add'; vehicle: Vehicle }
  | { type: 'delete'; id: string }
  | { type: 'update'; id: string; updates: Partial<Vehicle> };

function vehicleReducer(state: Vehicle[], action: VehicleAction): Vehicle[] {
  switch (action.type) {
    case 'add':
      return [...state, action.vehicle];
    case 'delete':
      return state.filter(v => v.id !== action.id);
    case 'update':
      return state.map(v => 
        v.id === action.id ? { ...v, ...action.updates } : v
      );
    default:
      return state;
  }
}

export function useOptimisticVehicles(vehicles: Vehicle[] = []) {
  const [optimisticVehicles, setOptimisticVehicles] = useState<Vehicle[]>(vehicles);
  const [isPending, startTransition] = useTransition();
  const queryClient = useQueryClient();

  // React 18 compatible optimistic update function
  const addOptimistic = (action: VehicleAction) => {
    setOptimisticVehicles(currentVehicles => vehicleReducer(currentVehicles, action));
  };

  // Sync optimistic state with actual vehicles when they change
  // Guard: Skip if both are empty arrays (prevents infinite loop on reference changes)
  useEffect(() => {
    if (vehicles.length === 0 && optimisticVehicles.length === 0) return;
    setOptimisticVehicles(vehicles);
  }, [vehicles, optimisticVehicles.length]);

  const optimisticCreateVehicle = async (data: CreateVehicleRequest) => {
    // Create optimistic vehicle with temporary ID
    const optimisticVehicle: Vehicle = {
      id: `temp-${Date.now()}`,
      vin: data.vin,
      nickname: data.nickname,
      color: data.color,
      licensePlate: data.licensePlate,
      odometerReading: data.odometerReading || 0,
      make: undefined,
      model: undefined,
      year: undefined,
      engine: undefined,
      transmission: undefined,
      trimLevel: undefined,
      driveType: undefined,
      fuelType: undefined,
      isActive: true,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      userId: 'current-user' // This would come from auth context
    };

    // Show optimistic update immediately
    startTransition(() => {
      addOptimistic({ type: 'add', vehicle: optimisticVehicle });
    });

    try {
      // Perform actual API call
      const createdVehicle = await vehiclesApi.create(data);
      
      // Invalidate and refetch to get real data
      await queryClient.invalidateQueries({ queryKey: ['vehicles'] });
      toast.success('Vehicle added successfully');
      
      return createdVehicle;
    } catch (error: any) {
      // Revert optimistic update on error
      await queryClient.invalidateQueries({ queryKey: ['vehicles'] });
      toast.error(error.response?.data?.error || 'Failed to add vehicle');
      throw error;
    }
  };

  const optimisticDeleteVehicle = async (id: string) => {
    // Show optimistic delete immediately
    startTransition(() => {
      addOptimistic({ type: 'delete', id });
    });

    try {
      // Perform actual API call
      await vehiclesApi.delete(id);
      
      // Invalidate and refetch to ensure consistency
      await queryClient.invalidateQueries({ queryKey: ['vehicles'] });
      toast.success('Vehicle deleted successfully');
    } catch (error: any) {
      // Revert optimistic update on error
      await queryClient.invalidateQueries({ queryKey: ['vehicles'] });
      toast.error(error.response?.data?.error || 'Failed to delete vehicle');
      throw error;
    }
  };

  const optimisticUpdateVehicle = async (id: string, updates: Partial<Vehicle>) => {
    // Show optimistic update immediately
    startTransition(() => {
      addOptimistic({ type: 'update', id, updates });
    });

    try {
      // Perform actual API call
      const updatedVehicle = await vehiclesApi.update(id, updates);
      
      // Invalidate and refetch to get real data
      await queryClient.invalidateQueries({ queryKey: ['vehicles'] });
      toast.success('Vehicle updated successfully');
      
      return updatedVehicle;
    } catch (error: any) {
      // Revert optimistic update on error
      await queryClient.invalidateQueries({ queryKey: ['vehicles'] });
      toast.error(error.response?.data?.error || 'Failed to update vehicle');
      throw error;
    }
  };

  return {
    optimisticVehicles,
    isPending,
    optimisticCreateVehicle,
    optimisticDeleteVehicle,
    optimisticUpdateVehicle
  };
}