import React from 'react';
import { createRoot } from 'react-dom/client';
import { BrowserRouter, Routes, Route, Navigate, useLocation } from 'react-router-dom';
import './bootstrap';
import '../css/app.css';

// Layouts
import AppLayout from './components/medical/AppLayout';

// Pages - Medical (Admin)
import Login from './pages/medical/Login';
import Dashboard from './pages/medical/Dashboard';
import Pacientes from './pages/medical/Pacientes';
import Citas from './pages/medical/Citas';
import HistoriasClinicas from './pages/medical/HistoriasClinicas';
import RecetasMedicas from './pages/medical/RecetasMedicas';
import Examenes from './pages/medical/Examenes';
import Vacunas from './pages/medical/Vacunas';
import Facturacion from './pages/medical/Facturacion';
import Usuarios from './pages/medical/Usuarios';
import Configuracion from './pages/medical/Configuracion';
import Categorias from './pages/medical/Categorias';
import PatientPortal from './pages/medical/PatientPortal';

// Pages - Portal del Paciente
import LoginPaciente from './pages/portal-paciente/LoginPaciente';
import DashboardPaciente from './pages/portal-paciente/DashboardPaciente';
import MisExamenes from './pages/portal-paciente/MisExamenes';
import PerfilPaciente from './pages/portal-paciente/PerfilPaciente';
import HistorialPaciente from './pages/portal-paciente/HistorialPaciente';

// Context Providers
import { ThemeProvider } from './context/ThemeContext';
import { UserProvider, useUser } from './context/UserContext';

// Componente para proteger rutas
function ProtectedRoute({ children }: { children: React.ReactNode }) {
    const { user, loading } = useUser();
    const location = useLocation();

    if (loading) {
        return (
            <div className="min-h-screen flex items-center justify-center bg-gray-100">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
            </div>
        );
    }

    // Si no hay usuario y no está en login, redirigir a login
    if (!user && location.pathname !== '/login') {
        return <Navigate to="/login" replace />;
    }

    // Si hay usuario y está en login, redirigir a dashboard
    if (user && location.pathname === '/login') {
        return <Navigate to="/dashboard" replace />;
    }

    return children;
}

function App() {
    return (
        <ThemeProvider>
            <UserProvider>
                <AppRoutes />
            </UserProvider>
        </ThemeProvider>
    );
}

function AppRoutes() {
    const { user, loading } = useUser();

    return (
        <BrowserRouter>
            <Routes>
                {/* Ruta de Login - redirige si ya está autenticado */}
                <Route
                    path="/login"
                    element={
                        loading ? (
                            <div className="min-h-screen flex items-center justify-center bg-gray-100">
                                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
                            </div>
                        ) : user ? (
                            <Navigate to="/dashboard" replace />
                        ) : (
                            <Login />
                        )
                    }
                />

                {/* Rutas protegidas con Layout */}
                <Route
                    path="/"
                    element={
                        <ProtectedRoute>
                            <AppLayout />
                        </ProtectedRoute>
                    }
                >
                    <Route index element={<Navigate to="/dashboard" replace />} />
                    <Route path="dashboard" element={<Dashboard />} />
                    <Route path="pacientes" element={<Pacientes />} />
                    <Route path="citas" element={<Citas />} />
                    <Route path="historias-clinicas" element={<HistoriasClinicas />} />
                    <Route path="recetas" element={<RecetasMedicas />} />
                    <Route path="categorias" element={<Categorias />} />
                    <Route path="examenes" element={<Examenes />} />
                    <Route path="vacunas" element={<Vacunas />} />
                    <Route path="facturacion" element={<Facturacion />} />
                    <Route path="usuarios" element={<Usuarios />} />
                    <Route path="configuracion" element={<Configuracion />} />
                </Route>


                {/* Portal del Paciente */}
                <Route path="/paciente/login" element={<LoginPaciente />} />
                <Route path="/paciente/dashboard" element={<DashboardPaciente />} />
                <Route path="/paciente/examenes" element={<MisExamenes />} />
                <Route path="/paciente/perfil" element={<PerfilPaciente />} />
                <Route path="/paciente/historial" element={<HistorialPaciente />} />

                {/* Portal antiguo (mantener por compatibilidad) */}
                <Route path="/portal-paciente" element={<PatientPortal />} />


                {/* Fallback */}
                <Route path="*" element={<Navigate to={user ? "/dashboard" : "/login"} replace />} />
            </Routes>
        </BrowserRouter>
    );
}

const container = document.getElementById('app');
if (container) {
    const root = createRoot(container);
    root.render(
        <React.StrictMode>
            <App />
        </React.StrictMode>
    );
}
