/**
 * @ai-summary React hook for ownership costs management
 */

import { useState, useEffect, useCallback } from 'react';
import { ownershipCostsApi } from '../api/ownership-costs.api';
import {
  OwnershipCost,
  CreateOwnershipCostRequest,
  UpdateOwnershipCostRequest
} from '../types/ownership-costs.types';

interface UseOwnershipCostsResult {
  costs: OwnershipCost[];
  isLoading: boolean;
  error: string | null;
  refresh: () => Promise<void>;
  createCost: (data: CreateOwnershipCostRequest) => Promise<OwnershipCost>;
  updateCost: (id: string, data: UpdateOwnershipCostRequest) => Promise<OwnershipCost>;
  deleteCost: (id: string) => Promise<void>;
}

export function useOwnershipCosts(vehicleId: string): UseOwnershipCostsResult {
  const [costs, setCosts] = useState<OwnershipCost[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchCosts = useCallback(async () => {
    if (!vehicleId) return;

    setIsLoading(true);
    setError(null);
    try {
      const data = await ownershipCostsApi.getByVehicle(vehicleId);
      setCosts(data);
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : 'Failed to load ownership costs';
      setError(message);
      console.error('Failed to fetch ownership costs:', err);
    } finally {
      setIsLoading(false);
    }
  }, [vehicleId]);

  useEffect(() => {
    fetchCosts();
  }, [fetchCosts]);

  const createCost = useCallback(async (data: CreateOwnershipCostRequest): Promise<OwnershipCost> => {
    const newCost = await ownershipCostsApi.create(data);
    setCosts(prev => [newCost, ...prev]);
    return newCost;
  }, []);

  const updateCost = useCallback(async (id: string, data: UpdateOwnershipCostRequest): Promise<OwnershipCost> => {
    const updated = await ownershipCostsApi.update(id, data);
    setCosts(prev => prev.map(cost => cost.id === id ? updated : cost));
    return updated;
  }, []);

  const deleteCost = useCallback(async (id: string): Promise<void> => {
    await ownershipCostsApi.delete(id);
    setCosts(prev => prev.filter(cost => cost.id !== id));
  }, []);

  return {
    costs,
    isLoading,
    error,
    refresh: fetchCosts,
    createCost,
    updateCost,
    deleteCost,
  };
}
