/**
 * @ai-summary React Query hooks for ownership-costs feature
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { ownershipCostsApi } from '../api/ownership-costs.api';
import type { CreateOwnershipCostRequest, UpdateOwnershipCostRequest, OwnershipCost } from '../types/ownership-costs.types';

export function useOwnershipCostsList(filters?: { vehicleId?: string }) {
  const queryKey = ['ownership-costs', filters];
  const query = useQuery({
    queryKey,
    queryFn: () => ownershipCostsApi.list(filters),
    networkMode: 'offlineFirst',
  });
  return query;
}

export function useOwnershipCost(id?: string) {
  const query = useQuery({
    queryKey: ['ownership-cost', id],
    queryFn: () => ownershipCostsApi.get(id!),
    enabled: !!id,
    networkMode: 'offlineFirst',
  });
  return query;
}

export function useCreateOwnershipCost() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (payload: CreateOwnershipCostRequest) => ownershipCostsApi.create(payload),
    onMutate: async (newCost) => {
      await qc.cancelQueries({ queryKey: ['ownership-costs'] });

      const previousCosts = qc.getQueryData(['ownership-costs']);

      const optimisticCost: OwnershipCost = {
        id: `temp-${Date.now()}`,
        vehicleId: newCost.vehicleId,
        documentId: newCost.documentId || null,
        costType: newCost.costType,
        amount: newCost.amount,
        description: newCost.description || null,
        periodStart: newCost.periodStart || null,
        periodEnd: newCost.periodEnd || null,
        notes: newCost.notes || null,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };

      qc.setQueryData(['ownership-costs'], (old: OwnershipCost[] | undefined) => {
        return old ? [optimisticCost, ...old] : [optimisticCost];
      });

      return { previousCosts };
    },
    onError: (_err, _newCost, context) => {
      if (context?.previousCosts) {
        qc.setQueryData(['ownership-costs'], context.previousCosts);
      }
    },
    onSettled: () => {
      qc.invalidateQueries({ queryKey: ['ownership-costs'] });
    },
    networkMode: 'offlineFirst',
  });
}

export function useUpdateOwnershipCost(id: string) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (payload: UpdateOwnershipCostRequest) => ownershipCostsApi.update(id, payload),
    onMutate: async (updateData) => {
      await qc.cancelQueries({ queryKey: ['ownership-cost', id] });
      await qc.cancelQueries({ queryKey: ['ownership-costs'] });

      const previousCost = qc.getQueryData(['ownership-cost', id]);
      const previousCosts = qc.getQueryData(['ownership-costs']);

      qc.setQueryData(['ownership-cost', id], (old: OwnershipCost | undefined) => {
        if (!old) return old;
        return {
          ...old,
          ...updateData,
          updatedAt: new Date().toISOString(),
        };
      });

      qc.setQueryData(['ownership-costs'], (old: OwnershipCost[] | undefined) => {
        if (!old) return old;
        return old.map(cost =>
          cost.id === id
            ? { ...cost, ...updateData, updatedAt: new Date().toISOString() }
            : cost
        );
      });

      return { previousCost, previousCosts };
    },
    onError: (_err, _updateData, context) => {
      if (context?.previousCost) {
        qc.setQueryData(['ownership-cost', id], context.previousCost);
      }
      if (context?.previousCosts) {
        qc.setQueryData(['ownership-costs'], context.previousCosts);
      }
    },
    onSettled: () => {
      qc.invalidateQueries({ queryKey: ['ownership-cost', id] });
      qc.invalidateQueries({ queryKey: ['ownership-costs'] });
    },
    networkMode: 'offlineFirst',
  });
}

export function useDeleteOwnershipCost() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => ownershipCostsApi.remove(id),
    onMutate: async (id) => {
      await qc.cancelQueries({ queryKey: ['ownership-costs'] });
      await qc.cancelQueries({ queryKey: ['ownership-cost', id] });

      const previousCosts = qc.getQueryData(['ownership-costs']);
      const previousCost = qc.getQueryData(['ownership-cost', id]);

      qc.setQueryData(['ownership-costs'], (old: OwnershipCost[] | undefined) => {
        if (!old) return old;
        return old.filter(cost => cost.id !== id);
      });

      qc.removeQueries({ queryKey: ['ownership-cost', id] });

      return { previousCosts, previousCost, deletedId: id };
    },
    onError: (_err, _id, context) => {
      if (context?.previousCosts) {
        qc.setQueryData(['ownership-costs'], context.previousCosts);
      }
      if (context?.previousCost && context.deletedId) {
        qc.setQueryData(['ownership-cost', context.deletedId], context.previousCost);
      }
    },
    onSettled: () => {
      qc.invalidateQueries({ queryKey: ['ownership-costs'] });
    },
    networkMode: 'offlineFirst',
  });
}
