// useChecklist Hook - Lógica de negócio para checklist e manutenção

import { useState, useEffect, useCallback } from 'react';
import { checklistService } from '../services/checklistService';

export const useChecklist = (filters = {}) => {
  const [vehicles, setVehicles] = useState([]);
  const [maintenanceOrders, setMaintenanceOrders] = useState([]);
  const [stats, setStats] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const fetchVehicles = useCallback(async () => {
    try {
      setLoading(true);
      const data = await checklistService.getVehicles(filters);
      setVehicles(data);
      
      const statsData = await checklistService.getStats();
      setStats(statsData);
      
      setError(null);
    } catch (err) {
      setError(err.message);
      console.error('Erro ao buscar veículos:', err);
    } finally {
      setLoading(false);
    }
  }, [JSON.stringify(filters)]);

  const fetchMaintenanceOrders = useCallback(async (orderFilters = {}) => {
    try {
      const data = await checklistService.getMaintenanceOrders(orderFilters);
      setMaintenanceOrders(data);
    } catch (err) {
      console.error('Erro ao buscar OS:', err);
    }
  }, []);

  const renewChecklist = useCallback(async (id) => {
    try {
      const result = await checklistService.renewChecklist(id);
      await fetchVehicles(); // Refresh
      return result;
    } catch (err) {
      console.error('Erro ao renovar:', err);
      throw new Error(`Erro ao renovar: ${err.message}`);
    }
  }, [fetchVehicles]);

  const createMaintenanceOrder = useCallback(async (data) => {
    try {
      const result = await checklistService.createMaintenanceOrder(data);
      await fetchMaintenanceOrders(); // Refresh
      return result;
    } catch (err) {
      console.error('Erro ao criar OS:', err);
      throw new Error(`Erro ao criar OS: ${err.message}`);
    }
  }, [fetchMaintenanceOrders]);

  const updateOrderStatus = useCallback(async (id, status) => {
    try {
      const result = await checklistService.updateOrderStatus(id, status);
      await fetchMaintenanceOrders(); // Refresh
      return result;
    } catch (err) {
      console.error('Erro ao atualizar OS:', err);
      throw new Error(`Erro ao atualizar OS: ${err.message}`);
    }
  }, [fetchMaintenanceOrders]);

  useEffect(() => {
    fetchVehicles();
    fetchMaintenanceOrders();
  }, [fetchVehicles, fetchMaintenanceOrders]);

  return {
    vehicles,
    maintenanceOrders,
    stats,
    loading,
    error,
    refresh: fetchVehicles,
    renewChecklist,
    createMaintenanceOrder,
    updateOrderStatus,
    fetchMaintenanceOrders
  };
};
