import { Navigate, Route, useLocation, type RouteSectionProps } from '@solidjs/router'
import { Show } from 'solid-js'
import { AppShell } from '@/components/layout/app-shell'
import { AdminPage } from '@/pages/admin-page'
import { CalendarPage } from '@/pages/calendar-page'
import { CollectionsPage } from '@/pages/collections-page'
import { DashboardPage } from '@/pages/dashboard-page'
import { DiscoverPage } from '@/pages/discover-page'
import { DownloadsPage } from '@/pages/downloads-page'
import { GamesPage } from '@/pages/games-page'
import { LibraryPage } from '@/pages/library-page'
import { LoginPage } from '@/pages/login-page'
import { MoviesPage } from '@/pages/movies-page'
import { RecommendationsPage } from '@/pages/recommendations-page'
import { SettingsPage } from '@/pages/settings-page'
import { ShowsPage } from '@/pages/shows-page'
import { WatchLaterPage } from '@/pages/watch-later-page'
import { WatchedPage } from '@/pages/watched-page'
import { useAuth } from '@/stores/auth-store'

const resolveRedirectPath = (search: string): string => {
  const redirect = new URLSearchParams(search).get('redirect')

  if (!redirect || !redirect.startsWith('/app/')) {
    return '/app/dashboard'
  }

  return redirect
}

const SessionGate = (props: RouteSectionProps) => {
  const auth = useAuth()
  const location = useLocation()

  return (
    <Show
      when={!auth.isInitializing()}
      fallback={
        <div class="grid min-h-screen place-items-center">
          <p class="text-sm text-muted-fg">Preparing your session...</p>
        </div>
      }
    >
      <Show
        when={auth.isAuthenticated()}
        fallback={<Navigate href={`/login?redirect=${encodeURIComponent(`${location.pathname}${location.search}`)}`} />}
      >
        <AppShell>{props.children}</AppShell>
      </Show>
    </Show>
  )
}

const LoginGate = () => {
  const auth = useAuth()
  const redirectSearch = typeof window === 'undefined' ? '' : window.location.search

  return (
    <Show
      when={!auth.isInitializing()}
      fallback={
        <div class="grid min-h-screen place-items-center">
          <p class="text-sm text-muted-fg">Preparing your session...</p>
        </div>
      }
    >
      <Show when={!auth.isAuthenticated()} fallback={<Navigate href={resolveRedirectPath(redirectSearch)} />}>
        <LoginPage />
      </Show>
    </Show>
  )
}

const RootRedirect = () => {
  const auth = useAuth()

  return (
    <Show
      when={!auth.isInitializing()}
      fallback={
        <div class="grid min-h-screen place-items-center">
          <p class="text-sm text-muted-fg">Preparing your session...</p>
        </div>
      }
    >
      <Navigate href={auth.isAuthenticated() ? '/app/dashboard' : '/login'} />
    </Show>
  )
}

export const AppRoutes = () => (
  <>
    <Route path="/" component={RootRedirect} />
    <Route path="/login" component={LoginGate} />

    <Route path="/app" component={SessionGate}>
      <Route path="/" component={() => <Navigate href="/app/dashboard" />} />
      <Route path="/dashboard" component={DashboardPage} />
      <Route path="/discover" component={DiscoverPage} />
      <Route path="/movies" component={MoviesPage} />
      <Route path="/shows" component={ShowsPage} />
      <Route path="/games" component={GamesPage} />
      <Route path="/watch-later" component={WatchLaterPage} />
      <Route path="/watched" component={WatchedPage} />
      <Route path="/downloads" component={DownloadsPage} />
      <Route path="/calendar" component={CalendarPage} />
      <Route path="/recommendations" component={RecommendationsPage} />
      <Route path="/library" component={LibraryPage} />
      <Route path="/collections" component={CollectionsPage} />
      <Route path="/settings" component={SettingsPage} />
      <Route path="/admin" component={AdminPage} />
    </Route>

    <Route path="*" component={RootRedirect} />
  </>
)
