import { useEffect } from 'react';
import { Routes, Route, useNavigate } from 'react-router-dom';
import { RouterShell } from '@/lib/router-shell';
import { TooltipProvider } from '@/components/ui/tooltip';
import { useAuthStore } from '@/stores/auth-store';
import { LoginPage } from '@/features/auth/login-page';
import { QueryClientProvider } from '@tanstack/react-query';
import SettingsPage from '@/features/settings-page';
import AudioVideoSettingsPage from '@/features/settings/audio-video-settings-page';
import NetworkSelector from '@/features/network-selector';
import NetworkRoot from '@/features/network-root';
import ParticleViewResolver from '@/features/particles/particle-view-resolver';
import Layout from '@/features/layout';
import NetworkSettingsPage from '@/features/network-settings';
import { Toaster } from '@/components/ui/sonner';
import { PusherProvider } from '@/lib/pusher-provider';
import { createQueryClient } from '@/lib/query-client';
import {
  RouteErrorBoundary,
  TopLevelErrorBoundary,
} from '@/components/app-error-boundary';
import { SoundEffectsProvider } from '@/lib/sound-effects/sound-effects-provider';
import { platform } from '@/lib/platform';
import { InAppAutoplayCard } from '@/components/in-app-autoplay-card';

const queryClient = createQueryClient();

const App = () => {
  const status = useAuthStore((s) => s.status);
  const restoreSession = useAuthStore((s) => s.restoreSession);

  useEffect(() => {
    restoreSession();
  }, [restoreSession]);

  if (status === 'idle' || status === 'restoring') {
    return (
      <div className="flex min-h-screen items-center justify-center">
        <p className="text-muted-foreground text-sm">Loading...</p>
      </div>
    );
  }

  if (status !== 'authenticated') {
    return <LoginPage />;
  }

  return (
    <PusherProvider>
      <AuthenticatedApp />
    </PusherProvider>
  );
};

function DeepLinkNavigationListener() {
  const navigate = useNavigate();

  useEffect(() => {
    platform.deepLink
      .getPending()
      .then((path) => {
        if (path) navigate(path);
      })
      .catch((err) => {
        logError(err, { scope: 'deepLink.getPending' });
      });

    return platform.deepLink.onNavigate((path) => navigate(path));
  }, [navigate]);

  return null;
}

function AutoplayNavigationListener() {
  const navigate = useNavigate();

  useEffect(() => {
    return platform.autoplay.onNavigate((data) => {
      navigate(`/${data.networkId}/${data.streamId}`);
    });
  }, [navigate]);

  return null;
}

function AuthenticatedApp() {
  return (
    <RouterShell>
      <AutoplayNavigationListener />
      <DeepLinkNavigationListener />
      <InAppAutoplayCard />
      <RouteErrorBoundary>
        <Routes>
          <Route path="settings" element={<SettingsPage />} />
          <Route
            path="settings/audio-video"
            element={<AudioVideoSettingsPage />}
          />

          <Route path="/">
            <Route
              index
              element={
                <Layout>
                  <NetworkSelector />
                </Layout>
              }
            />
            <Route path=":networkId">
              <Route
                index
                element={
                  <Layout>
                    <NetworkRoot />
                  </Layout>
                }
              />
              <Route path="settings" element={<NetworkSettingsPage />} />
              <Route path="*" element={<ParticleViewResolver />} />
            </Route>
          </Route>
        </Routes>
      </RouteErrorBoundary>
    </RouterShell>
  );
}

const AppWithProviders = () => (
  <TopLevelErrorBoundary>
    <TooltipProvider>
      <QueryClientProvider client={queryClient}>
        <SoundEffectsProvider>
          <App />
          <Toaster />
        </SoundEffectsProvider>
      </QueryClientProvider>
    </TooltipProvider>
  </TopLevelErrorBoundary>
);

export default AppWithProviders;
