/**
 * useSync Hook
 * Provides React hook interface for synchronization operations
 */

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

export const useSync = () => {
  const [syncStatus, setSyncStatus] = useState({
    isSyncing: false,
    lastSync: null,
    pendingRecords: 0,
    pendingOperations: 0,
    error: null,
    progress: null
  });

  // Sync event handler
  const handleSyncEvent = useCallback((event, data) => {
    switch (event) {
      case 'sync_started':
        setSyncStatus(prev => ({
          ...prev,
          isSyncing: true,
          error: null,
          progress: { stage: 'starting', message: 'Iniciando sincronización...' }
        }));
        break;

      case 'sync_progress':
        setSyncStatus(prev => ({
          ...prev,
          progress: data
        }));
        break;

      case 'sync_completed':
        setSyncStatus(prev => ({
          ...prev,
          isSyncing: false,
          lastSync: data.timestamp,
          error: null,
          progress: null
        }));
        break;

      case 'sync_failed':
        setSyncStatus(prev => ({
          ...prev,
          isSyncing: false,
          error: data.error,
          progress: null
        }));
        break;

      default:
        break;
    }
  }, []);

  // Register sync listener
  useEffect(() => {
    syncService.addSyncListener(handleSyncEvent);
    
    // Load initial sync status
    const loadSyncStatus = async () => {
      try {
        const status = await syncService.getSyncStatus();
        setSyncStatus(prev => ({
          ...prev,
          isSyncing: status.isSyncing,
          lastSync: status.lastSync,
          pendingRecords: status.pendingRecords,
          pendingOperations: status.pendingOperations
        }));
      } catch (error) {
        console.error('Error loading sync status:', error);
      }
    };

    loadSyncStatus();

    return () => {
      syncService.removeSyncListener(handleSyncEvent);
    };
  }, [handleSyncEvent]);

  // Perform full synchronization
  const performFullSync = useCallback(async () => {
    try {
      const result = await syncService.performFullSync();
      
      // Update status after sync
      const status = await syncService.getSyncStatus();
      setSyncStatus(prev => ({
        ...prev,
        pendingRecords: status.pendingRecords,
        pendingOperations: status.pendingOperations
      }));

      return result;
    } catch (error) {
      throw error;
    }
  }, []);

  // Sync only field records
  const syncFieldRecords = useCallback(async () => {
    try {
      const result = await syncService.syncFieldRecords();
      
      // Update status after sync
      const status = await syncService.getSyncStatus();
      setSyncStatus(prev => ({
        ...prev,
        pendingRecords: status.pendingRecords
      }));

      return result;
    } catch (error) {
      throw error;
    }
  }, []);

  // Get current sync status
  const refreshSyncStatus = useCallback(async () => {
    try {
      const status = await syncService.getSyncStatus();
      setSyncStatus(prev => ({
        ...prev,
        isSyncing: status.isSyncing,
        lastSync: status.lastSync,
        pendingRecords: status.pendingRecords,
        pendingOperations: status.pendingOperations
      }));
      return status;
    } catch (error) {
      console.error('Error refreshing sync status:', error);
      return null;
    }
  }, []);

  // Clear sync error
  const clearSyncError = useCallback(() => {
    setSyncStatus(prev => ({
      ...prev,
      error: null
    }));
  }, []);

  return {
    // Status
    isSyncing: syncStatus.isSyncing,
    lastSync: syncStatus.lastSync,
    pendingRecords: syncStatus.pendingRecords,
    pendingOperations: syncStatus.pendingOperations,
    error: syncStatus.error,
    progress: syncStatus.progress,

    // Actions
    performFullSync,
    syncFieldRecords,
    refreshSyncStatus,
    clearSyncError
  };
};