import { useEffect, useState, type ReactNode } from 'react';
import { BrowserRouter, Routes, Route, useLocation } from 'react-router-dom';
import { AppSidebar } from './components/Sidebar';
import { SidebarProvider, SidebarInset, MobileSidebarTrigger } from './components/ui/sidebar';
import { Header } from './components/Header';
import { BodyVisualization } from './components/BodyVisualization';
import { Timeline } from './components/Timeline';
import { DataDashboard } from './components/DataDashboard';
import { DetailPanel } from './components/DetailPanel';
import { Hippo } from './components/Hippo';
import { useHealthStore } from './store/useHealthStore';
import { useAuthStore } from './store/useAuthStore';
import { PlotsPage, TimelinePage, VisitsPage, PrescriptionsPage, PrescriptionDetailPage, DiseasesPage, TestsPage, ImagesPage, DevicesPage, SettingsPage, VaccinationsPage } from './pages';
import LoginPage from './pages/LoginPage';
import SignUpPage from './pages/SignUpPage';
import PractitionerApp from './practitioner/PractitionerApp';

// Home page component (original dashboard)
function HomePage() {
  const [showTimeline, setShowTimeline] = useState(true);

  return (
    <>
      <Header />

      <div className="space-y-8">
        {/* 3D Body Visualization */}
        <BodyVisualization />

        {/* Timeline (Moved up) */}
        <div>
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold text-gray-900 tracking-tight">Medical Timeline</h2>
            <button
              onClick={() => setShowTimeline(!showTimeline)}
              className="text-sm font-medium text-primary hover:text-blue-700 transition-colors"
            >
              {showTimeline ? 'Hide Timeline' : 'Show Timeline'}
            </button>
          </div>
          {showTimeline && <Timeline />}
        </div>

        {/* Customizable Data Widgets */}
        <DataDashboard />
      </div>
    </>
  );
}

/**
 * Keeps a heavy page mounted across navigation so its state (3D Canvas,
 * Timeline viewport, widget layout, etc.) survives a route change. Lazy
 * on first visit — never mounted until the user actually navigates here.
 */
function KeepAlive({ active, children }: { active: boolean; children: ReactNode }) {
  const [mounted, setMounted] = useState(active);
  if (active && !mounted) setMounted(true);
  if (!mounted) return null;
  return <div style={{ display: active ? undefined : 'none' }}>{children}</div>;
}

// Routes that keep their components mounted across navigation.
const KEEP_ALIVE_PATHS = ['/', '/profile', '/timeline'];

function PatientRoutes() {
  const { pathname } = useLocation();
  const showHome = pathname === '/' || pathname === '/profile';
  const showTimeline = pathname === '/timeline';
  const showOther = !KEEP_ALIVE_PATHS.includes(pathname);

  return (
    <>
      <KeepAlive active={showHome}>
        <HomePage />
      </KeepAlive>

      <KeepAlive active={showTimeline}>
        <TimelinePage />
      </KeepAlive>

      {showOther && (
        <Routes>
          <Route path="/visits" element={<VisitsPage />} />
          <Route path="/prescriptions" element={<PrescriptionsPage />} />
          <Route path="/prescriptions/:id" element={<PrescriptionDetailPage />} />
          <Route path="/diagnoses" element={<DiseasesPage />} />
          <Route path="/tests" element={<TestsPage />} />
          <Route path="/images" element={<ImagesPage />} />
          <Route path="/devices" element={<DevicesPage />} />
          <Route path="/vaccinations" element={<VaccinationsPage />} />
          <Route path="/plots" element={<PlotsPage />} />
          <Route path="/settings" element={<SettingsPage />} />
        </Routes>
      )}
    </>
  );
}

function App() {
  const closeDetailPanel = useHealthStore((state) => state.closeDetailPanel);
  const nextCondition = useHealthStore((state) => state.nextCondition);
  const prevCondition = useHealthStore((state) => state.prevCondition);
  const loadUserData = useHealthStore((state) => state.loadUserData);

  const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
  const isLoading = useAuthStore((s) => s.isLoading);
  const loadFromStorage = useAuthStore((s) => s.loadFromStorage);
  const user = useAuthStore((s) => s.user);

  const [showSignUp, setShowSignUp] = useState(false);

  // On mount, attempt to restore auth from localStorage
  useEffect(() => {
    loadFromStorage();
  }, [loadFromStorage]);

  // Load user medical data when authenticated
  useEffect(() => {
    if (isAuthenticated && user?._id) {
      loadUserData(user._id);
    }
  }, [isAuthenticated, user?._id, loadUserData]);

  // Keyboard navigation
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      switch (e.key) {
        case 'ArrowLeft':
          prevCondition();
          break;
        case 'ArrowRight':
          nextCondition();
          break;
        case 'Escape':
          closeDetailPanel();
          break;
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [closeDetailPanel, nextCondition, prevCondition]);

  // Show a minimal loading indicator while checking auth
  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full" />
      </div>
    );
  }

  // Not authenticated → show login or sign up page
  if (!isAuthenticated) {
    if (showSignUp) {
      return <SignUpPage onSwitchToLogin={() => setShowSignUp(false)} />;
    }
    return <LoginPage onSwitchToSignUp={() => setShowSignUp(true)} />;
  }

  // Practitioner → separate app shell
  if (user?.roles?.includes('practitioner')) {
    return <PractitionerApp />;
  }

  return (
    <BrowserRouter>
      <SidebarProvider defaultOpen>
        <AppSidebar />

        <SidebarInset className="app-shell">
          <div className="app-frame">
            <div className="content-frame">
              <div className="min-h-0 min-w-0 flex-1 overflow-x-hidden overflow-y-auto">
                <MobileSidebarTrigger />

                <div className="px-5 pb-8 pt-5 md:px-8 md:pb-10 md:pt-8">
                  <div className="mx-auto max-w-[1600px] min-w-0">
                    <PatientRoutes />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </SidebarInset>

        <DetailPanel />
        <Hippo />
      </SidebarProvider>
    </BrowserRouter>
  );
}

export default App;
