import { Routes, Route, Navigate } from 'react-router-dom';
import { Toaster } from '@/components/ui/toaster';
import { useAuthStore } from '@/stores/useAuthStore';

// Layouts
import MainLayout from '@/components/common/Layout/MainLayout';
import AuthLayout from '@/components/common/Layout/AuthLayout';

// Auth Pages
import LoginPage from '@/pages/auth/LoginPage';

// Protected Pages
import DashboardPage from '@/pages/dashboard/DashboardPage';

// CRM Pages
import ClientsPage from '@/pages/crm/ClientsPage';
import ClientFormPage from '@/pages/crm/ClientFormPage';
import BrandsPage from '@/pages/crm/BrandsPage';
import BrandFormPage from '@/pages/crm/BrandFormPage';
import ProductsPage from '@/pages/crm/ProductsPage';
import ProductFormPage from '@/pages/crm/ProductFormPage';

// Assets Pages
import AssetsPage from '@/pages/assets/AssetsPage';

// Projects Pages
import ProjectsPage from '@/pages/projects/ProjectsPage';

// Protected Route Component
function ProtectedRoute({ children }: { children: React.ReactNode }) {
  const { isAuthenticated } = useAuthStore();

  if (!isAuthenticated) {
    return <Navigate to="/login" replace />;
  }

  return <>{children}</>;
}

function App() {
  return (
    <>
      <Routes>
        {/* Auth Routes */}
        <Route element={<AuthLayout />}>
          <Route path="/login" element={<LoginPage />} />
          <Route path="/register" element={<LoginPage />} />
          <Route path="/forgot-password" element={<LoginPage />} />
        </Route>

        {/* Protected Routes */}
        <Route
          element={
            <ProtectedRoute>
              <MainLayout />
            </ProtectedRoute>
          }
        >
          <Route path="/" element={<Navigate to="/dashboard" replace />} />
          <Route path="/dashboard" element={<DashboardPage />} />

          {/* CRM Routes */}
          <Route path="/crm/clients" element={<ClientsPage />} />
          <Route path="/crm/clients/new" element={<ClientFormPage />} />
          <Route path="/crm/clients/:id/edit" element={<ClientFormPage />} />
          <Route path="/crm/brands" element={<BrandsPage />} />
          <Route path="/crm/brands/new" element={<BrandFormPage />} />
          <Route path="/crm/brands/:id/edit" element={<BrandFormPage />} />
          <Route path="/crm/products" element={<ProductsPage />} />
          <Route path="/crm/products/new" element={<ProductFormPage />} />
          <Route path="/crm/products/:id/edit" element={<ProductFormPage />} />

          {/* Assets Routes */}
          <Route path="/assets" element={<AssetsPage />} />

          {/* Projects Routes */}
          <Route path="/projects" element={<ProjectsPage />} />
        </Route>

        {/* 404 */}
        <Route path="*" element={<Navigate to="/" replace />} />
      </Routes>
      <Toaster />
    </>
  );
}

export default App;
