import React from 'react';
import { createBrowserRouter, Outlet, Navigate, useLocation } from 'react-router-dom';
import { useAuth } from './auth/context';
import {
  ADMIN_BASE_PATH,
  ADMIN_DEFAULT_AFTER_LOGIN_PATH,
  ADMIN_HOME_PATH,
  ADMIN_LOGIN_PATH,
  ADMIN_LOGIN_START_PATH,
  ADMIN_PUBLIC_LANDING_PATH,
} from './constants';
import { consumeLastDestination } from './lib/returnTo';
const LoginPage = React.lazy(() => import('./pages/LoginPage'));
const DashboardPage = React.lazy(() => import('./pages/DashboardPage'));
const EventsPage = React.lazy(() => import('./pages/EventsPage'));
const SettingsPage = React.lazy(() => import('./pages/SettingsPage'));
const EventFormPage = React.lazy(() => import('./pages/EventFormPage'));
const EventPhotosPage = React.lazy(() => import('./pages/EventPhotosPage'));
const EventDetailPage = React.lazy(() => import('./pages/EventDetailPage'));
const EventMembersPage = React.lazy(() => import('./pages/EventMembersPage'));
const EventTasksPage = React.lazy(() => import('./pages/EventTasksPage'));
const EventToolkitPage = React.lazy(() => import('./pages/EventToolkitPage'));
const EventInvitesPage = React.lazy(() => import('./pages/EventInvitesPage'));
const EngagementPage = React.lazy(() => import('./pages/EngagementPage'));
const BillingPage = React.lazy(() => import('./pages/BillingPage'));
const TasksPage = React.lazy(() => import('./pages/TasksPage'));
const TaskCollectionsPage = React.lazy(() => import('./pages/TaskCollectionsPage'));
const EmotionsPage = React.lazy(() => import('./pages/EmotionsPage'));
const AuthCallbackPage = React.lazy(() => import('./pages/AuthCallbackPage'));
const WelcomeTeaserPage = React.lazy(() => import('./pages/WelcomeTeaserPage'));
const LoginStartPage = React.lazy(() => import('./pages/LoginStartPage'));
const ProfilePage = React.lazy(() => import('./pages/ProfilePage'));
const LogoutPage = React.lazy(() => import('./pages/LogoutPage'));
const WelcomeLandingPage = React.lazy(() => import('./onboarding/pages/WelcomeLandingPage'));
const WelcomePackagesPage = React.lazy(() => import('./onboarding/pages/WelcomePackagesPage'));
const WelcomeEventSetupPage = React.lazy(() => import('./onboarding/pages/WelcomeEventSetupPage'));
const WelcomeOrderSummaryPage = React.lazy(() => import('./onboarding/pages/WelcomeOrderSummaryPage'));

function RequireAuth() {
  const { status } = useAuth();
  const location = useLocation();

  if (status === 'loading') {
    return (
      <div className="flex min-h-screen items-center justify-center text-sm text-muted-foreground">
        Bitte warten ...
      </div>
    );
  }

  if (status === 'unauthenticated') {
    return <Navigate to={ADMIN_LOGIN_START_PATH} state={{ from: location }} replace />;
  }

  return <Outlet />;
}

function LandingGate() {
  const { status } = useAuth();
  const lastDestinationRef = React.useRef<string | null>(null);

  if (status === 'loading') {
    return (
      <div className="flex min-h-screen items-center justify-center text-sm text-muted-foreground">
        Bitte warten ...
      </div>
    );
  }

  if (status === 'authenticated') {
    if (lastDestinationRef.current === null) {
      lastDestinationRef.current = consumeLastDestination() ?? ADMIN_DEFAULT_AFTER_LOGIN_PATH;
    }

    return <Navigate to={lastDestinationRef.current ?? ADMIN_DEFAULT_AFTER_LOGIN_PATH} replace />;
  }

  return <WelcomeTeaserPage />;
}

export const router = createBrowserRouter([
  {
    path: ADMIN_BASE_PATH,
    element: <Outlet />,
    children: [
      { index: true, element: <LandingGate /> },
      { path: 'login', element: <LoginPage /> },
      { path: 'start', element: <LoginStartPage /> },
      { path: 'logout', element: <LogoutPage /> },
      { path: 'auth/callback', element: <AuthCallbackPage /> },
      {
        element: <RequireAuth />,
        children: [
          { path: 'dashboard', element: <DashboardPage /> },
          { path: 'events', element: <EventsPage /> },
          { path: 'events/new', element: <EventFormPage /> },
          { path: 'events/:slug', element: <EventDetailPage /> },
          { path: 'events/:slug/edit', element: <EventFormPage /> },
          { path: 'events/:slug/photos', element: <EventPhotosPage /> },
          { path: 'events/:slug/members', element: <EventMembersPage /> },
          { path: 'events/:slug/tasks', element: <EventTasksPage /> },
          { path: 'events/:slug/invites', element: <EventInvitesPage /> },
          { path: 'events/:slug/toolkit', element: <EventToolkitPage /> },
          { path: 'engagement', element: <EngagementPage /> },
          { path: 'tasks', element: <TasksPage /> },
          { path: 'task-collections', element: <TaskCollectionsPage /> },
          { path: 'emotions', element: <EmotionsPage /> },
          { path: 'billing', element: <BillingPage /> },
          { path: 'settings', element: <SettingsPage /> },
          { path: 'settings/profile', element: <ProfilePage /> },
          { path: 'welcome', element: <WelcomeLandingPage /> },
          { path: 'welcome/packages', element: <WelcomePackagesPage /> },
          { path: 'welcome/summary', element: <WelcomeOrderSummaryPage /> },
          { path: 'welcome/event', element: <WelcomeEventSetupPage /> },
        ],
      },
    ],
  },
  {
    path: '*',
    element: <Navigate to={ADMIN_PUBLIC_LANDING_PATH} replace />,
  },
]);
