import React, { useEffect, useRef } from "react";
import useProductStore from "../stores/useProductStore";
import useConfigStore from "../stores/useConfigStore";
import ProductGrid from "../components/products/ProductGrid";

const HomePage = () => {
  const { products, loading, error, fetchProducts, clearError } = useProductStore();
  const { config, fetchConfig } = useConfigStore();
  const refreshIntervalRef = useRef(null);

  // Chargement initial
  useEffect(() => {
    fetchConfig();
    fetchProducts();
  }, [fetchProducts, fetchConfig]);

  // Auto-refresh basé sur la config (rechargement complet de la page)
  useEffect(() => {
    const refreshInterval = config.ui?.refresh_auto_seconds || 0;

    // Nettoyer l'ancien intervalle
    if (refreshIntervalRef.current) {
      clearInterval(refreshIntervalRef.current);
      refreshIntervalRef.current = null;
    }

    // Configurer le nouvel intervalle si > 0
    if (refreshInterval > 0) {
      refreshIntervalRef.current = setInterval(() => {
        window.location.reload();
      }, refreshInterval * 1000);
    }

    // Cleanup à la destruction du composant
    return () => {
      if (refreshIntervalRef.current) {
        clearInterval(refreshIntervalRef.current);
      }
    };
  }, [config.ui?.refresh_auto_seconds]);

  const columns = config.ui?.columns_desktop || 3;

  return (
    <main className="home-page">
      {error && (
        <div className="error-banner">
          <span>{error}</span>
          <button onClick={clearError} className="btn-close">
            <i className="fa-solid fa-times"></i>
          </button>
        </div>
      )}

      {loading && products.length === 0 ? (
        <div className="loading-state">
          <i className="fa-solid fa-spinner fa-spin"></i>
          <p>Chargement des produits...</p>
        </div>
      ) : (
        <ProductGrid products={products} columns={columns} />
      )}
    </main>
  );
};

export default HomePage;
