import { useState, useEffect, useCallback } from 'react';
import apiFetch from '@wordpress/api-fetch';

export const useCssOptimization = () => {
  const [cacheStats, setCacheStats] = useState(null);
  const [isClearing, setIsClearing] = useState(false);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(true);

  // Fetch cache statistics
  const fetchCacheStats = useCallback(async () => {
    try {
      setLoading(true);
      const response = await apiFetch({
        path: '/prorank-seo/v1/performance/css-cache/stats',
        method: 'GET',
      });
      setCacheStats(response);
      setError(null);
    } catch (err) {
      setError(err);
    } finally {
      setLoading(false);
    }
  }, []);

  // Clear CSS cache
  const clearCache = useCallback(
    async (type = 'all') => {
      try {
        setIsClearing(true);
        const response = await apiFetch({
          path: '/prorank-seo/v1/performance/css-cache/clear',
          method: 'POST',
          data: { type },
        });

        // Refresh stats after clearing
        await fetchCacheStats();

        return response;
      } catch (err) {
        setError(err);

        throw err;
      } finally {
        setIsClearing(false);
      }
    },
    [fetchCacheStats]
  );

  // Preview CSS minification
  const previewMinification = useCallback(async (url) => {
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/performance/css/preview',
        method: 'POST',
        data: { url },
      });
      return response;
    } catch (err) {
      setError(err);

      throw err;
    }
  }, []);

  // Get excluded files
  const getExcludedFiles = useCallback(async () => {
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/performance/css/excluded-files',
        method: 'GET',
      });
      return response;
    } catch (err) {
      setError(err);

      throw err;
    }
  }, []);

  // Initial load
  useEffect(() => {
    fetchCacheStats();
  }, [fetchCacheStats]);

  // Auto-refresh stats every minute if the component is active
  useEffect(() => {
    const interval = setInterval(() => {
      fetchCacheStats();
    }, 60000); // 1 minute

    return () => clearInterval(interval);
  }, [fetchCacheStats]);

  return {
    cacheStats,
    isClearing,
    error,
    loading,
    clearCache,
    previewMinification,
    getExcludedFiles,
    refreshStats: fetchCacheStats,
  };
};
