import React, { useState } 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";

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

  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="/">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>
      </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>
    </div>
  </BrowserRouter>
);

export default App;
