import { useState, useEffect } from 'react';
import Login from './components/Login';
import Navigation from './components/Navigation';
import ProductPage from './components/ProductPage';
import WarehousePage from './components/WarehousePage';
import TransactionsPage from './components/TransactionsPage';
import ReportsPage from './components/ReportsPage';
import Dashboard from './components/Dashboard';

import { isAuthenticated } from './utils/auth';
import './App.css';

const menuItems = [
  { id: 'product', label: 'Product' },
  { id: 'warehouse', label: 'Warehouse' },
  { id: 'transactions', label: 'Transactions' },
  { id: 'reports', label: 'Reports' },
];

function App() {
  const [authenticated, setAuthenticated] = useState(false);
  const [currentPage, setCurrentPage] = useState('dashboard');

  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);

  useEffect(() => {
    setAuthenticated(isAuthenticated());
  }, []);

  const handleLoginSuccess = () => {
    setAuthenticated(true);
    setCurrentPage('dashboard');
  };


  const handleLogout = () => {
    setAuthenticated(false);
    setCurrentPage('dashboard');
  };


  const navigate = (page) => {
    setCurrentPage(page);
    setMobileMenuOpen(false);
  };

  if (!authenticated) {
    return <Login onLoginSuccess={handleLoginSuccess} />;
  }

  const renderPage = () => {
    switch (currentPage) {
      case 'dashboard':
        return <Dashboard />;
      case 'product':
        return <ProductPage />;
      case 'warehouse':
        return <WarehousePage />;
      case 'transactions':
        return <TransactionsPage />;
      case 'reports':
        return <ReportsPage />;
      default:
        return <Dashboard />;
    }
  };


  return (
    <div className="min-h-screen bg-gray-100">
      <Navigation currentPage={currentPage} onNavigate={navigate} onLogout={handleLogout}
        mobileMenuOpen={mobileMenuOpen} setMobileMenuOpen={setMobileMenuOpen} />

      <div className="flex flex-col md:flex-row">
        <aside className={`${mobileMenuOpen ? 'block' : 'hidden'} md:block w-full md:w-52 bg-gray-900 text-white md:min-h-[calc(100vh-4rem)]`}>
          <nav className="p-4 md:p-6">
            <ul className="space-y-2">
              {menuItems.map((item) => (
                <li key={item.id}>
                  <button onClick={() => navigate(item.id)}
                    className={`w-full text-left px-4 py-2 rounded transition ${
                      currentPage === item.id ? 'bg-blue-600' : 'hover:bg-gray-700'
                    }`}>
                    {item.label}
                  </button>
                </li>
              ))}
            </ul>
          </nav>
        </aside>

        <main className="flex-1 min-w-0">{renderPage()}</main>
      </div>
    </div>
  );
}

export default App;
