import { BrowserRouter, Routes, Route, Navigate, useNavigate } from 'react-router-dom'
import { useState, useEffect, useRef } from 'react'
import { initTelegramApp } from './utils/telegram'
import { verifyAuth } from './utils/api'
import { initTheme } from './utils/theme'
import Layout from './components/Layout'
import Feed from './pages/Feed'
import Search from './pages/Search'
import Notifications from './pages/Notifications'
import Profile from './pages/Profile'
import UserProfile from './pages/UserProfile'
import CommentsPage from './pages/CommentsPage'
import PostMenuPage from './pages/PostMenuPage'
import './styles/index.css'

function AppContent() {
  const [user, setUser] = useState(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)
  const navigate = useNavigate()
  const startParamProcessed = useRef(false)
  const initAppCalled = useRef(false)

  useEffect(() => {
    initTheme()

    if (!initAppCalled.current) {
      initAppCalled.current = true
      initApp()
    }
  }, [])

  const waitForInitData = async () => {
    const start = Date.now()
    const timeout = 5000

    while (Date.now() - start < timeout) {
      const tg = window.Telegram?.WebApp
      if (tg?.initData && tg.initData.length > 0) {
        return tg
      }
      await new Promise(resolve => setTimeout(resolve, 100))
    }

    throw new Error('Telegram не передал initData. Откройте приложение в официальном клиенте.')
  }

  const initApp = async () => {
    try {
      initTelegramApp()

      const tg = await waitForInitData()

      tg.disableVerticalSwipes?.()
      tg.ready?.()
      tg.expand?.()

      const userData = await verifyAuth()
      setUser(userData)
      setError(null)

      if (!startParamProcessed.current && tg?.startParam?.startsWith('post_')) {
        startParamProcessed.current = true
        const postId = tg.startParam.replace('post_', '')
        setTimeout(() => {
          navigate(`/feed?post=${postId}`, { replace: true })
        }, 200)
      }
    } catch (err) {
      console.error('Ошибка инициализации:', err)
      setError(err?.response?.data?.error || err.message || 'Ошибка авторизации')
    } finally {
      setLoading(false)
    }
  }

  if (loading) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
        flexDirection: 'column',
        gap: '16px'
      }}>
        <div className="spinner" />
        <p style={{ color: 'var(--text-secondary)' }}>Загрузка...</p>
      </div>
    )
  }

  if (error) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
        flexDirection: 'column',
        gap: '16px',
        padding: '20px'
      }}>
        <p style={{ color: 'var(--text-primary)', textAlign: 'center' }}>
          Ошибка загрузки приложения
        </p>
        <p style={{ color: 'var(--text-secondary)', textAlign: 'center' }}>
          {error}
        </p>
        <button 
          onClick={() => window.location.reload()}
          style={{
            padding: '12px 24px',
            borderRadius: '12px',
            background: 'var(--button-accent)',
            color: 'white',
            border: 'none',
            cursor: 'pointer',
            fontSize: '16px'
          }}
        >
          Попробовать снова
        </button>
      </div>
    )
  }

  if (!user) {
    return null
  }

  return (
    <Routes>
      <Route path="/" element={<Layout user={user} />}>
        <Route index element={<Navigate to="/feed" replace />} />
        <Route path="feed" element={<Feed user={user} />} />
        <Route path="search" element={<Search user={user} />} />
        <Route path="notifications" element={<Notifications user={user} />} />
        <Route path="profile" element={<Profile user={user} setUser={setUser} />} />
        <Route path="user/:id" element={<UserProfile currentUser={user} />} />
        <Route path="post/:postId/comments" element={<CommentsPage user={user} />} />
        <Route path="post/:postId/menu" element={<PostMenuPage user={user} />} />
      </Route>
    </Routes>
  )
}

function App() {
  return (
    <BrowserRouter>
      <AppContent />
    </BrowserRouter>
  )
}

export default App

