import { useEffect, useState } from 'react'
import { Link, Outlet, createRootRoute, useRouterState } from '@tanstack/react-router'
import { useQuery } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { Menu, X } from 'lucide-react'
import { useTheme, type Theme } from '@/theme/ThemeProvider'
import { setLanguage } from '@/shared/lib/i18n'
import { Toaster } from '@/shared/ui/toaster'
import { Button } from '@/shared/ui/button'
import { useAuthStore } from '@/features/auth/store'
import { bootstrapSession, clearSession, logout } from '@/features/auth/api'
import { TelegramLinkWarningBanner } from '@/features/telegram/TelegramLinkWarningBanner'
import { getMyBillingStatus } from '@/features/billing/api'

export const Route = createRootRoute({ component: RootLayout })

function RootLayout() {
  const { t, i18n } = useTranslation()
  const { theme, setTheme } = useTheme()
  const { user, isBootstrapping } = useAuthStore()
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false)
  const pathname = useRouterState({ select: (s) => s.location.pathname })

  // Гейтится наличием сессии и активации — та же логика, что и /billing (ActivationGate). Долгий
  // staleTime: это лишь решение "показывать ли пункт меню", а не источник актуального статуса оплаты.
  const billingStatusQuery = useQuery({
    queryKey: ['my-billing-status'],
    queryFn: getMyBillingStatus,
    enabled: !isBootstrapping && !!user?.isActivated,
    staleTime: 5 * 60 * 1000,
  })

  useEffect(() => {
    void bootstrapSession()
  }, [])

  // Закрываем мобильное меню при переходе на другую страницу.
  useEffect(() => {
    setMobileMenuOpen(false)
  }, [pathname])

  const themes: Theme[] = ['light', 'dark', 'system']
  const langs = ['ru', 'en']

  const handleLogout = async () => {
    try {
      await logout()
    } finally {
      clearSession()
    }
  }

  const navLinks = !isBootstrapping && user && (
    <>
      <Link to="/dashboard" className="text-muted-foreground hover:text-foreground">
        {t('nav.dashboard')}
      </Link>
      {user.isActivated && (
        <>
          <Link to="/instructions" className="text-muted-foreground hover:text-foreground">
            {t('nav.instructions')}
          </Link>
          <Link to="/news" className="text-muted-foreground hover:text-foreground">
            {t('nav.news')}
          </Link>
          <Link to="/support" className="text-muted-foreground hover:text-foreground">
            {t('nav.support')}
          </Link>
          {billingStatusQuery.data?.billingEnabled && (
            <Link to="/billing" className="text-muted-foreground hover:text-foreground">
              {t('nav.billing')}
            </Link>
          )}
        </>
      )}
      <Link to="/settings" className="text-muted-foreground hover:text-foreground">
        {t('nav.settings')}
      </Link>
      {user.role === 'admin' && (
        <Link to="/admin" className="text-muted-foreground hover:text-foreground">
          {t('nav.admin')}
        </Link>
      )}
      <Button variant="ghost" size="sm" className="justify-start" onClick={handleLogout}>
        {t('nav.logout')}
      </Button>
    </>
  )

  const selects = (
    <>
      <label className="flex items-center gap-2">
        <select
          className="w-full rounded-md border border-border bg-muted px-2 py-1 sm:w-auto"
          value={i18n.language}
          onChange={(e) => setLanguage(e.target.value)}
        >
          {langs.map((l) => (
            <option key={l} value={l}>
              {l.toUpperCase()}
            </option>
          ))}
        </select>
      </label>
      <label className="flex items-center gap-2">
        <select
          className="w-full rounded-md border border-border bg-muted px-2 py-1 sm:w-auto"
          value={theme}
          onChange={(e) => setTheme(e.target.value as Theme)}
        >
          {themes.map((th) => (
            <option key={th} value={th}>
              {t(th)}
            </option>
          ))}
        </select>
      </label>
    </>
  )

  return (
    <div className="flex min-h-svh flex-col">
      <header className="border-b border-border px-4 py-3 sm:px-6 sm:py-4">
        <div className="flex items-center justify-between gap-2">
          <Link to="/" className="text-lg font-semibold text-primary">
            {t('appName')}
          </Link>

          <nav className="hidden items-center gap-4 text-sm sm:flex">
            {navLinks}
            {selects}
          </nav>

          <button
            type="button"
            className="text-foreground sm:hidden"
            onClick={() => setMobileMenuOpen((v) => !v)}
            aria-label={t('nav.toggleMenu')}
          >
            {mobileMenuOpen ? <X className="h-5 w-5" /> : <Menu className="h-5 w-5" />}
          </button>
        </div>

        {mobileMenuOpen && (
          <nav className="mt-3 flex flex-col items-stretch gap-3 text-sm sm:hidden">
            {navLinks}
            {selects}
          </nav>
        )}
      </header>

      <TelegramLinkWarningBanner />

      <main className="flex flex-1 flex-col">
        <Outlet />
      </main>

      <Toaster />
    </div>
  )
}
