import { useEffect, useMemo } from 'react';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { SidebarProvider, SidebarInset, MobileSidebarTrigger } from '../components/ui/sidebar';
import { PractitionerSidebar } from './PractitionerSidebar';
import { AppSidebar } from '../components/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 { useAuthStore } from '../store/useAuthStore';
import { useHealthStore } from '../store/useHealthStore';
import { usePractitionerStore } from './store/usePractitionerStore';

import DashboardPage from './pages/DashboardPage';
import PatientsPage from './pages/PatientsPage';
import PatientDetailPage from './pages/PatientDetailPage';
import SchedulePage from './pages/SchedulePage';
import AppointmentsPage from './pages/AppointmentsPage';
import { SettingsPage } from '../pages/SettingsPage';
import { PlotsPage, TimelinePage, VisitsPage, PrescriptionsPage, PrescriptionDetailPage, DiseasesPage, TestsPage, ImagesPage, DevicesPage, VaccinationsPage } from '../pages';

function PractitionerPatientModeBadge({ patientName, isSelf }: { patientName: string; isSelf: boolean }) {
  return (
    <div className="mb-4 inline-flex items-center gap-2 rounded-full border border-amber-300 bg-amber-50 px-3 py-1.5 text-xs font-medium text-amber-800">
      <span className="h-2 w-2 rounded-full bg-amber-500" />
      {isSelf ? 'Viewing Your Data' : `Viewing ${patientName}'s Data`}
    </div>
  );
}

function PatientHomePage() {
  return (
    <>
      <Header />

      <div className="space-y-8">
        <BodyVisualization />
        <Timeline />
        <DataDashboard />
      </div>
    </>
  );
}

function PractitionerPatientRoutes({ isViewingSelf }: { isViewingSelf: boolean }) {
  return (
    <Routes>
      <Route path="/" element={<PatientHomePage />} />
      <Route path="/profile" element={<PatientHomePage />} />
      <Route path="/timeline" element={<TimelinePage />} />
      <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 />} />
      {isViewingSelf && <Route path="/devices" element={<DevicesPage />} />}
      <Route path="/vaccinations" element={<VaccinationsPage />} />
      <Route path="/plots" element={<PlotsPage />} />
      <Route path="*" element={<Navigate to="/" replace />} />
    </Routes>
  );
}

export default function PractitionerApp() {
  const user = useAuthStore((s) => s.user);
  const loadUserData = useHealthStore((s) => s.loadUserData);
  const loadPatients = usePractitionerStore((s) => s.loadPatients);
  const patients = usePractitionerStore((s) => s.patients);
  const viewingPatientId = usePractitionerStore((s) => s.viewingPatientId);
  const exitPatientView = usePractitionerStore((s) => s.exitPatientView);
  const isViewingSelf = Boolean(user?._id && viewingPatientId && user._id === viewingPatientId);

  const viewingPatientName = useMemo(() => {
    if (!viewingPatientId) return 'Patient';
    return patients.find((patient) => patient._id === viewingPatientId)?.dispName || 'Patient';
  }, [patients, viewingPatientId]);

  useEffect(() => {
    if (user?.sharingInfo?.length) {
      loadPatients(user.sharingInfo);
    }
  }, [user?.sharingInfo, loadPatients]);

  useEffect(() => {
    if (!viewingPatientId) return;
    loadUserData(viewingPatientId, true);
  }, [loadUserData, viewingPatientId]);

  return (
    <BrowserRouter>
      <SidebarProvider defaultOpen>
        {viewingPatientId ? (
          <AppSidebar
            showReturnToDashboard
            hideSettings
            hideDevices={!isViewingSelf}
            returnToDashboardPath={`/patients/${viewingPatientId}`}
            onReturnToDashboard={exitPatientView}
          />
        ) : (
          <PractitionerSidebar />
        )}

        <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">
                    {viewingPatientId && (
                      <PractitionerPatientModeBadge
                        patientName={viewingPatientName}
                        isSelf={isViewingSelf}
                      />
                    )}
                    {viewingPatientId ? (
                      <PractitionerPatientRoutes isViewingSelf={isViewingSelf} />
                    ) : (
                      <Routes>
                        <Route path="/" element={<DashboardPage />} />
                        <Route path="/patients" element={<PatientsPage />} />
                        <Route path="/patients/:patientId" element={<PatientDetailPage />} />
                        <Route path="/schedule" element={<SchedulePage />} />
                        <Route path="/appointments" element={<AppointmentsPage />} />
                        <Route path="/settings" element={<SettingsPage />} />
                        <Route path="*" element={<Navigate to="/" replace />} />
                      </Routes>
                    )}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </SidebarInset>

        {viewingPatientId && <DetailPanel />}
      </SidebarProvider>
    </BrowserRouter>
  );
}
