/**
 * @ai-summary React 19 useTransition hooks for vehicle operations
 * @ai-context Non-blocking updates for better UI responsiveness
 */

import { useTransition, useState, useCallback, useEffect } from 'react';
import { Vehicle } from '../types/vehicles.types';

export function useVehicleSearch(vehicles: Vehicle[]) {
  const [isPending, startTransition] = useTransition();
  const [searchQuery, setSearchQuery] = useState('');
  const [filteredVehicles, setFilteredVehicles] = useState<Vehicle[]>(vehicles);

  const handleSearch = useCallback((query: string) => {
    // High priority: Update search input immediately
    setSearchQuery(query);
    
    // Low priority: Update filtered results (non-blocking)
    startTransition(() => {
      if (!query.trim()) {
        setFilteredVehicles(vehicles);
      } else {
        const filtered = vehicles.filter(vehicle => {
          const searchTerm = query.toLowerCase();
          return (
            vehicle.nickname?.toLowerCase().includes(searchTerm) ||
            vehicle.make?.toLowerCase().includes(searchTerm) ||
            vehicle.model?.toLowerCase().includes(searchTerm) ||
            vehicle.vin.toLowerCase().includes(searchTerm) ||
            vehicle.year?.toString().includes(searchTerm)
          );
        });
        setFilteredVehicles(filtered);
      }
    });
  }, [vehicles]);

  const clearSearch = useCallback(() => {
    setSearchQuery('');
    startTransition(() => {
      setFilteredVehicles(vehicles);
    });
  }, [vehicles]);

  // Auto-sync filtered vehicles when source vehicles change
  // Note: Direct state update (no startTransition) to avoid deferred render cascades
  useEffect(() => {
    if (!searchQuery.trim()) {
      setFilteredVehicles(vehicles);
    } else {
      const filtered = vehicles.filter(vehicle => {
        const searchTerm = searchQuery.toLowerCase();
        return (
          vehicle.nickname?.toLowerCase().includes(searchTerm) ||
          vehicle.make?.toLowerCase().includes(searchTerm) ||
          vehicle.model?.toLowerCase().includes(searchTerm) ||
          vehicle.vin.toLowerCase().includes(searchTerm) ||
          vehicle.year?.toString().includes(searchTerm)
        );
      });
      setFilteredVehicles(filtered);
    }
  }, [vehicles, searchQuery]);

  return {
    searchQuery,
    filteredVehicles,
    isPending,
    handleSearch,
    clearSearch
  };
}

export function useVehicleSort(vehicles: Vehicle[]) {
  const [isPending, startTransition] = useTransition();
  const [sortBy, setSortBy] = useState<'name' | 'make' | 'year' | 'created'>('created');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
  const [sortedVehicles, setSortedVehicles] = useState<Vehicle[]>(vehicles);

  const handleSort = useCallback((newSortBy: typeof sortBy, newSortOrder: typeof sortOrder = 'asc') => {
    // High priority: Update sort state immediately
    setSortBy(newSortBy);
    setSortOrder(newSortOrder);
    
    // Low priority: Update sorted results (non-blocking)
    startTransition(() => {
      const sorted = [...vehicles].sort((a, b) => {
        let aValue: string | number | null;
        let bValue: string | number | null;
        
        switch (newSortBy) {
          case 'name':
            aValue = a.nickname || `${a.make || ''} ${a.model || ''}`.trim() || 'Unknown';
            bValue = b.nickname || `${b.make || ''} ${b.model || ''}`.trim() || 'Unknown';
            break;
          case 'make':
            aValue = a.make || 'Unknown';
            bValue = b.make || 'Unknown';
            break;
          case 'year':
            aValue = a.year || 0;
            bValue = b.year || 0;
            break;
          case 'created':
            aValue = a.createdAt;
            bValue = b.createdAt;
            break;
          default:
            return 0;
        }
        
        if (typeof aValue === 'string' && typeof bValue === 'string') {
          const result = aValue.localeCompare(bValue);
          return newSortOrder === 'asc' ? result : -result;
        } else {
          const result = (aValue as number) - (bValue as number);
          return newSortOrder === 'asc' ? result : -result;
        }
      });
      setSortedVehicles(sorted);
    });
  }, [vehicles]);

  // Update sorted vehicles when vehicles data changes
  const updateVehicles = useCallback((_newVehicles: Vehicle[]) => {
    startTransition(() => {
      handleSort(sortBy, sortOrder);
    });
  }, [sortBy, sortOrder, handleSort]);

  return {
    sortBy,
    sortOrder,
    sortedVehicles,
    isPending,
    handleSort,
    updateVehicles
  };
}

export function useVehicleFilter(vehicles: Vehicle[]) {
  const [isPending, startTransition] = useTransition();
  const [activeFilters, setActiveFilters] = useState<{
    make?: string;
    year?: number;
    isActive?: boolean;
  }>({});
  const [filteredVehicles, setFilteredVehicles] = useState<Vehicle[]>(vehicles);

  const applyFilters = useCallback((filters: typeof activeFilters) => {
    // High priority: Update filter state immediately
    setActiveFilters(filters);
    
    // Low priority: Apply filters (non-blocking)
    startTransition(() => {
      let filtered = vehicles;
      
      if (filters.make) {
        filtered = filtered.filter(v => v.make === filters.make);
      }
      
      if (filters.year) {
        filtered = filtered.filter(v => v.year === filters.year);
      }
      
      if (filters.isActive !== undefined) {
        filtered = filtered.filter(v => v.isActive === filters.isActive);
      }
      
      setFilteredVehicles(filtered);
    });
  }, [vehicles]);

  const clearFilters = useCallback(() => {
    setActiveFilters({});
    startTransition(() => {
      setFilteredVehicles(vehicles);
    });
  }, [vehicles]);

  return {
    activeFilters,
    filteredVehicles,
    isPending,
    applyFilters,
    clearFilters
  };
}