import React, { useState, useEffect } from "react";
import { BrowserRouter, Routes, Route, NavLink } from "react-router-dom";
import HomePage from "./pages/HomePage";
import DebugPage from "./pages/DebugPage";
import SettingsPage from "./pages/SettingsPage";
import useProductStore from "./stores/useProductStore";
import AddProductModal from "./components/products/AddProductModal";
import CommandLogPopup from "./components/common/CommandLogPopup";
import * as api from "./api/client";

const FRONTEND_VERSION = "0.1.0";

const Header = () => {
  const { fetchProducts, scrapeAll, loading } = useProductStore();
  const [showAddModal, setShowAddModal] = useState(false);
  const [backendVersion, setBackendVersion] = useState(null);
  const [stats, setStats] = useState(null);

  useEffect(() => {
    api.fetchBackendVersion()
      .then((data) => setBackendVersion(data.version))
      .catch(() => setBackendVersion("?"));
  }, []);

  // Fetch system stats toutes les 30 secondes
  useEffect(() => {
    const fetchStats = () => {
      api.fetchSystemStats()
        .then((data) => setStats(data))
        .catch(() => setStats(null));
    };

    fetchStats();
    const interval = setInterval(fetchStats, 30000);
    return () => clearInterval(interval);
  }, []);

  const handleRefresh = () => {
    fetchProducts();
  };

  const handleScrapeAll = async () => {
    if (!confirm("Lancer le scraping de tous les produits ?")) return;
    try {
      await scrapeAll();
    } catch (err) {
      console.error("Erreur scrape all:", err);
    }
  };

  return (
    <>
      <header className="app-header">
        <div className="brand">
          <NavLink to="/">
            <img className="brand-logo" src="/store.svg" alt="Store" />
            suivi_produits
          </NavLink>
        </div>
        <nav className="nav-links">
          <NavLink to="/" end className={({ isActive }) => isActive ? "active" : ""}>
            <i className="fa-solid fa-home"></i> Accueil
          </NavLink>
          <NavLink to="/debug" className={({ isActive }) => isActive ? "active" : ""}>
            <i className="fa-solid fa-bug"></i> Debug
          </NavLink>
          <NavLink to="/settings" className={({ isActive }) => isActive ? "active" : ""}>
            <i className="fa-solid fa-cog"></i> Settings
          </NavLink>
        </nav>
        <div className="actions">
          <button className="btn btn-primary" onClick={() => setShowAddModal(true)}>
            <i className="fa-solid fa-plus"></i> Add Product
          </button>
          <button className="btn" onClick={handleScrapeAll} disabled={loading}>
            <i className="fa-solid fa-bolt"></i> Scrape All
          </button>
          <button className="btn" onClick={handleRefresh} disabled={loading}>
            <i className={`fa-solid fa-refresh ${loading ? "fa-spin" : ""}`}></i>
          </button>
        </div>
        {stats && (
          <div className="system-stats">
            <span title="CPU du process backend">
              <i className="fa-solid fa-microchip"></i> {stats.cpu_percent}%
            </span>
            <span title="Mémoire du process backend">
              <i className="fa-solid fa-memory"></i> {stats.memory_mb} Mo
            </span>
            <span title="Taille données (data + logs)">
              <i className="fa-solid fa-database"></i> {stats.data_size_mb < 1000 ? `${stats.data_size_mb} Mo` : `${(stats.data_size_mb / 1024).toFixed(1)} Go`}
            </span>
          </div>
        )}
        <div className="version-info">
          <span title="Version Frontend">FE v{FRONTEND_VERSION}</span>
          <span title="Version Backend">BE v{backendVersion || "..."}</span>
        </div>
      </header>

      {showAddModal && (
        <AddProductModal onClose={() => setShowAddModal(false)} />
      )}
    </>
  );
};

const App = () => (
  <BrowserRouter>
    <div className="app-shell">
      <Header />
      <Routes>
        <Route path="/" element={<HomePage />} />
        <Route path="/debug" element={<DebugPage />} />
        <Route path="/settings" element={<SettingsPage />} />
      </Routes>
      <CommandLogPopup />
    </div>
  </BrowserRouter>
);

export default App;
