import { readAuthSession } from '@/lib/auth-storage';
import { otsApi } from '@/lib/api';
import { syncRemoteClientesCache } from '@/lib/offline-clientes';
import { cacheRemoteOtList } from '@/lib/offline-ots';
import { cacheRemoteVehiculos } from '@/lib/offline-vehiculos';
import { useEffect, useState } from 'react';

const CLIENT_SYNC_INTERVAL = 30 * 60 * 1000;
const OT_SYNC_INTERVAL = 5 * 60 * 1000;
const VEHICULO_SYNC_INTERVAL = 10 * 60 * 1000;

export function useClientSync() {
  const [isSyncing, setIsSyncing] = useState(false);

  useEffect(() => {
    const syncData = async () => {
      if (!navigator.onLine) return;
      if (!readAuthSession().accessToken) return;

      const now = Date.now();
      const lastClientSync = Number(localStorage.getItem('lastClientSync') || '0');
      const lastOtSync = Number(localStorage.getItem('lastOtSync') || '0');
      const lastVehiculoSync = Number(localStorage.getItem('lastVehiculoSync') || '0');

      const shouldSyncClients = now - lastClientSync > CLIENT_SYNC_INTERVAL;
      const shouldSyncOts = now - lastOtSync > OT_SYNC_INTERVAL;
      const shouldSyncVehiculos = now - lastVehiculoSync > VEHICULO_SYNC_INTERVAL;

      if (!shouldSyncClients && !shouldSyncOts && !shouldSyncVehiculos) {
        return;
      }

      try {
        setIsSyncing(true);

        if (shouldSyncClients) {
          await syncRemoteClientesCache();
          localStorage.setItem('lastClientSync', now.toString());
        }

        if (shouldSyncOts) {
          const response = await otsApi.list({ page: 1, limit: 1000 });
          const ots = response?.data || [];

          if (Array.isArray(ots) && ots.length > 0) {
            await cacheRemoteOtList(ots);
          }

          localStorage.setItem('lastOtSync', now.toString());
        }

        if (shouldSyncVehiculos) {
          const { vehiculosApi } = await import('@/lib/api');
          const vehiculos = await vehiculosApi.list();

          if (Array.isArray(vehiculos) && vehiculos.length > 0) {
            await cacheRemoteVehiculos(vehiculos);
          }

          localStorage.setItem('lastVehiculoSync', now.toString());
        }
      } catch (error) {
        console.error('Failed to sync local cache:', error);
      } finally {
        setIsSyncing(false);
      }
    };

    void syncData();

    const handleOnline = () => {
      void syncData();
    };

    window.addEventListener('online', handleOnline);
    return () => {
      window.removeEventListener('online', handleOnline);
    };
  }, []);

  return { isSyncing };
}
