/**
 * useOfflineStorage Hook
 * Provides React hook interface for offline storage operations
 */

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

export const useOfflineStorage = () => {
  const [isInitialized, setIsInitialized] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  const [storageStats, setStorageStats] = useState({});

  // Initialize storage service
  useEffect(() => {
    const initStorage = async () => {
      try {
        setIsLoading(true);
        await storageService.init();
        setIsInitialized(true);
        setError(null);
      } catch (err) {
        setError(err.message);
        console.error('Error initializing storage:', err);
      } finally {
        setIsLoading(false);
      }
    };

    initStorage();
  }, []);

  // Update storage statistics
  const updateStats = useCallback(async () => {
    if (!isInitialized) return;
    
    try {
      const stats = await storageService.getStorageStats();
      setStorageStats(stats);
    } catch (err) {
      console.error('Error getting storage stats:', err);
    }
  }, [isInitialized]);

  // Update stats when initialized
  useEffect(() => {
    if (isInitialized) {
      updateStats();
    }
  }, [isInitialized, updateStats]);

  // ==================== AUTH OPERATIONS ====================

  const saveAuth = useCallback(async (authData) => {
    try {
      setError(null);
      const result = await storageService.setAuth(authData);
      return result;
    } catch (err) {
      setError(err.message);
      throw err;
    }
  }, []);

  const getAuth = useCallback(async () => {
    try {
      setError(null);
      return await storageService.getAuth();
    } catch (err) {
      setError(err.message);
      return null;
    }
  }, []);

  const clearAuth = useCallback(async () => {
    try {
      setError(null);
      await storageService.clearAuth();
    } catch (err) {
      setError(err.message);
      throw err;
    }
  }, []);

  // ==================== PROJECT OPERATIONS ====================

  const saveProject = useCallback(async (project) => {
    try {
      setError(null);
      const result = await storageService.saveProject(project);
      await updateStats();
      return result;
    } catch (err) {
      setError(err.message);
      throw err;
    }
  }, [updateStats]);

  const getProjects = useCallback(async () => {
    try {
      setError(null);
      return await storageService.getProjects();
    } catch (err) {
      setError(err.message);
      return [];
    }
  }, []);

  const getProject = useCallback(async (id) => {
    try {
      setError(null);
      return await storageService.getProject(id);
    } catch (err) {
      setError(err.message);
      return null;
    }
  }, []);

  const deleteProject = useCallback(async (id) => {
    try {
      setError(null);
      await storageService.deleteProject(id);
      await updateStats();
    } catch (err) {
      setError(err.message);
      throw err;
    }
  }, [updateStats]);

  // ==================== RODAL OPERATIONS ====================

  const saveRodal = useCallback(async (rodal) => {
    try {
      setError(null);
      const result = await storageService.saveRodal(rodal);
      await updateStats();
      return result;
    } catch (err) {
      setError(err.message);
      throw err;
    }
  }, [updateStats]);

  const getRodalesByProject = useCallback(async (projectId) => {
    try {
      setError(null);
      return await storageService.getRodalesByProject(projectId);
    } catch (err) {
      setError(err.message);
      return [];
    }
  }, []);

  const getRodal = useCallback(async (id) => {
    try {
      setError(null);
      return await storageService.getRodal(id);
    } catch (err) {
      setError(err.message);
      return null;
    }
  }, []);

  const deleteRodal = useCallback(async (id) => {
    try {
      setError(null);
      await storageService.deleteRodal(id);
      await updateStats();
    } catch (err) {
      setError(err.message);
      throw err;
    }
  }, [updateStats]);

  // ==================== SPECIES OPERATIONS ====================

  const saveSpecies = useCallback(async (species) => {
    try {
      setError(null);
      const result = await storageService.saveSpecies(species);
      await updateStats();
      return result;
    } catch (err) {
      setError(err.message);
      throw err;
    }
  }, [updateStats]);

  const saveSpeciesBulk = useCallback(async (speciesArray) => {
    try {
      setError(null);
      const result = await storageService.saveSpeciesBulk(speciesArray);
      await updateStats();
      return result;
    } catch (err) {
      setError(err.message);
      throw err;
    }
  }, [updateStats]);

  const getSpecies = useCallback(async () => {
    try {
      setError(null);
      return await storageService.getSpecies();
    } catch (err) {
      setError(err.message);
      return [];
    }
  }, []);

  // ==================== FIELD RECORD OPERATIONS ====================

  const saveFieldRecord = useCallback(async (record) => {
    try {
      setError(null);
      const result = await storageService.saveFieldRecord(record);
      await updateStats();
      return result;
    } catch (err) {
      setError(err.message);
      throw err;
    }
  }, [updateStats]);

  const getFieldRecordsByRodal = useCallback(async (rodalId) => {
    try {
      setError(null);
      return await storageService.getFieldRecordsByRodal(rodalId);
    } catch (err) {
      setError(err.message);
      return [];
    }
  }, []);

  const getPendingSyncRecords = useCallback(async () => {
    try {
      setError(null);
      return await storageService.getPendingSyncRecords();
    } catch (err) {
      setError(err.message);
      return [];
    }
  }, []);

  const updateSyncStatus = useCallback(async (recordIds, status) => {
    try {
      setError(null);
      const result = await storageService.updateSyncStatus(recordIds, status);
      await updateStats();
      return result;
    } catch (err) {
      setError(err.message);
      throw err;
    }
  }, [updateStats]);

  // ==================== SYNC QUEUE OPERATIONS ====================

  const addToSyncQueue = useCallback(async (operation) => {
    try {
      setError(null);
      return await storageService.addToSyncQueue(operation);
    } catch (err) {
      setError(err.message);
      throw err;
    }
  }, []);

  const getPendingSyncOperations = useCallback(async () => {
    try {
      setError(null);
      return await storageService.getPendingSyncOperations();
    } catch (err) {
      setError(err.message);
      return [];
    }
  }, []);

  const removeSyncOperation = useCallback(async (id) => {
    try {
      setError(null);
      await storageService.removeSyncOperation(id);
    } catch (err) {
      setError(err.message);
      throw err;
    }
  }, []);

  // ==================== UTILITY OPERATIONS ====================

  const clearAllData = useCallback(async () => {
    try {
      setError(null);
      await storageService.clearAllData();
      await updateStats();
    } catch (err) {
      setError(err.message);
      throw err;
    }
  }, [updateStats]);

  const refreshStats = useCallback(async () => {
    await updateStats();
  }, [updateStats]);

  // ==================== OFFLINE STATUS ====================

  const [isOnline, setIsOnline] = useState(navigator.onLine);

  useEffect(() => {
    const handleOnline = () => setIsOnline(true);
    const handleOffline = () => setIsOnline(false);

    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);

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

  return {
    // Status
    isInitialized,
    isLoading,
    error,
    isOnline,
    storageStats,

    // Auth operations
    saveAuth,
    getAuth,
    clearAuth,

    // Project operations
    saveProject,
    getProjects,
    getProject,
    deleteProject,

    // Rodal operations
    saveRodal,
    getRodalesByProject,
    getRodal,
    deleteRodal,

    // Species operations
    saveSpecies,
    saveSpeciesBulk,
    getSpecies,

    // Field record operations
    saveFieldRecord,
    getFieldRecordsByRodal,
    getPendingSyncRecords,
    updateSyncStatus,

    // Sync queue operations
    addToSyncQueue,
    getPendingSyncOperations,
    removeSyncOperation,

    // Utility operations
    clearAllData,
    refreshStats
  };
};