import React, { useEffect, useState } from 'react'
import { Moon, Sun } from 'lucide-react'
import PatTestManager from './components/PatTestManager'
import AuthPanel from './components/AuthPanel'
import { supabase } from './lib/supabaseClient'
import Landing from './components/Landing'
import SharedAssessmentPage from './components/SharedAssessmentPage'
import PublicInfoPage from './components/public/PublicInfoPage'
import ProfileTab from './components/ProfileTab'
import { useUserProfile } from './hooks/useUserProfile'
import { getCountryLabel, getCountryOption } from './data/countries'
import CountryFlag from './components/CountryFlag'
import { LanguageProvider } from './i18n/LanguageContext'
import { getTranslator } from './i18n/translations'

const readShareToken = () => {
  if (typeof window === 'undefined') return ''
  return new URLSearchParams(window.location.search).get('share') || ''
}

const readPublicPath = () => {
  if (typeof window === 'undefined') return '/'
  const hash = window.location.hash || ''
  return hash.startsWith('#/') ? hash.slice(1) : '/'
}

function App() {
  const [session, setSession] = useState(null)
  const [loading, setLoading] = useState(true)
  const [showAuth, setShowAuth] = useState(false)
  const [activeTab, setActiveTab] = useState('assessments')
  const [isEditingAssessment, setIsEditingAssessment] = useState(false)
  const [shareToken, setShareToken] = useState(() => readShareToken())
  const [publicPath, setPublicPath] = useState(() => readPublicPath())
  const [theme, setTheme] = useState(() => {
    if (typeof window === 'undefined') return 'light'
    const stored = localStorage.getItem('theme')
    if (stored === 'light' || stored === 'dark') return stored
    return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
  })
  const {
    profile,
    loading: profileLoading,
    error: profileError,
    saveProfile,
    deleteProfileData
  } = useUserProfile(session)

  const language = profile?.language || 'de'
  const t = getTranslator(language)

  useEffect(() => {
    const root = document.documentElement
    if (theme === 'dark') {
      root.classList.add('dark')
    } else {
      root.classList.remove('dark')
    }
    localStorage.setItem('theme', theme)
  }, [theme])

  useEffect(() => {
    const syncLocationState = () => {
      setShareToken(readShareToken())
      setPublicPath(readPublicPath())
    }

    window.addEventListener('popstate', syncLocationState)
    window.addEventListener('hashchange', syncLocationState)

    return () => {
      window.removeEventListener('popstate', syncLocationState)
      window.removeEventListener('hashchange', syncLocationState)
    }
  }, [])

  useEffect(() => {
    if (shareToken) {
      setLoading(false)
      return
    }

    if (!supabase) {
      setLoading(false)
      return
    }

    const fetchSession = async () => {
      const { data, error } = await supabase.auth.getSession()
      if (!error) {
        setSession(data.session)
      }
      setLoading(false)
    }

    fetchSession()

    const { data: authListener } = supabase.auth.onAuthStateChange((_event, newSession) => {
      setSession(newSession)
    })

    return () => {
      authListener?.subscription.unsubscribe()
    }
  }, [shareToken])

  useEffect(() => {
    if (isEditingAssessment && activeTab !== 'assessments') {
      setActiveTab('assessments')
    }
  }, [activeTab, isEditingAssessment])

  const handleSignOut = async () => {
    if (!supabase) return
    await supabase.auth.signOut()
    setSession(null)
    setShowAuth(false)
    setActiveTab('assessments')
    setIsEditingAssessment(false)
    navigatePublic('/')
  }

  const toggleTheme = () => setTheme((prev) => (prev === 'dark' ? 'light' : 'dark'))

  const navigatePublic = (path) => {
    if (typeof window === 'undefined') return

    const nextPath = path || '/'
    const nextHash = nextPath === '/' ? '' : `#${nextPath}`

    if (window.location.hash === nextHash) {
      setPublicPath(nextPath)
      window.scrollTo({ top: 0, behavior: 'smooth' })
      return
    }

    const nextUrl = `${window.location.pathname}${window.location.search}${nextHash}`
    window.history.pushState({}, '', nextUrl)
    setPublicPath(nextPath)
    setShareToken(readShareToken())
    window.scrollTo({ top: 0, behavior: 'smooth' })
  }

  const renderThemeToggle = () => (
    <button
      onClick={toggleTheme}
      className="flex items-center gap-2 px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-100 shadow-sm hover:shadow transition"
      aria-label="Darstellung wechseln"
      type="button"
    >
      {theme === 'dark' ? <Sun className="w-4 h-4" /> : <Moon className="w-4 h-4" />}
      <span className="text-sm font-medium">{theme === 'dark' ? t('nav.theme_light') : t('nav.theme_dark')}</span>
    </button>
  )

  if (shareToken) {
    return (
      <LanguageProvider language={language}>
        <SharedAssessmentPage shareToken={shareToken} themeToggle={renderThemeToggle()} />
      </LanguageProvider>
    )
  }

  if (!supabase) {
    return (
      <LanguageProvider language={language}>
        <div className="min-h-screen bg-gray-50 dark:bg-gray-950 text-gray-900 dark:text-gray-100 flex items-center justify-center p-6">
          <div className="absolute top-4 right-4">{renderThemeToggle()}</div>
          <div className="max-w-xl w-full bg-white/90 dark:bg-gray-900/80 border border-dashed border-gray-300 dark:border-gray-700 rounded-xl shadow-sm p-6">
            <h2 className="text-2xl font-bold text-gray-800 dark:text-gray-100 mb-2">Supabase noch nicht konfiguriert</h2>
            <p className="text-gray-600 dark:text-gray-300">
              Lege eine <code>.env</code> an (siehe <code>.env.example</code>) und trage
              <code> VITE_SUPABASE_URL </code> sowie <code>VITE_SUPABASE_ANON_KEY</code> ein, um Login und
              Registrierung zu aktivieren.
            </p>
            <p className="text-sm text-gray-500 dark:text-gray-400 mt-3">
              Anschließend Vite neu starten, damit die Variablen geladen werden.
            </p>
          </div>
        </div>
      </LanguageProvider>
    )
  }

  if (loading) {
    return (
      <LanguageProvider language={language}>
        <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-950 text-gray-600 dark:text-gray-300">
          <div className="absolute top-4 right-4">{renderThemeToggle()}</div>
          <span>Auth wird geladen...</span>
        </div>
      </LanguageProvider>
    )
  }

  if (!session) {
    if (showAuth) {
      return (
        <LanguageProvider language={language}>
          <AuthPanel onAuth={setSession} themeToggle={renderThemeToggle()} onBack={() => setShowAuth(false)} />
        </LanguageProvider>
      )
    }

    if (publicPath === '/datenschutz' || publicPath === '/impressum' || publicPath === '/kontakt') {
      return (
        <LanguageProvider language={language}>
          <PublicInfoPage
            path={publicPath}
            onGetStarted={() => setShowAuth(true)}
            onNavigate={navigatePublic}
            themeToggle={renderThemeToggle()}
          />
        </LanguageProvider>
      )
    }

    return (
      <LanguageProvider language={language}>
        <Landing
          onGetStarted={() => setShowAuth(true)}
          onNavigate={navigatePublic}
          themeToggle={renderThemeToggle()}
        />
      </LanguageProvider>
    )
  }

  const userDisplayName = [profile?.firstName, profile?.lastName]
    .filter(Boolean)
    .join(' ')
  const selectedCountry = getCountryOption(profile?.country)
  const countryLabel = getCountryLabel(profile?.country)
  const hasName = Boolean(userDisplayName)

  return (
    <LanguageProvider language={language}>
      <div className="min-h-screen bg-gray-50 dark:bg-gray-950 text-gray-900 dark:text-gray-100">
        <header className="bg-white/80 dark:bg-gray-900/70 backdrop-blur border-b border-gray-200 dark:border-gray-800">
          <div className="max-w-7xl mx-auto px-6 py-3 flex items-center justify-between gap-3 flex-wrap">
            <div>
              <p className="text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400">{t('nav.logged_in')}</p>
              <div className="flex items-center gap-2 flex-wrap text-sm font-semibold text-gray-800 dark:text-gray-100">
                {countryLabel && (
                  <CountryFlag
                    countryCode={selectedCountry?.code || profile?.country}
                    title={countryLabel}
                    className="h-4 w-6 rounded-[2px] shadow-sm ring-1 ring-black/10"
                  />
                )}
                <span>{hasName ? userDisplayName : session?.user?.email}</span>
              </div>
            </div>

            <nav className="flex items-center gap-2">
              <button
                type="button"
                onClick={() => setActiveTab('assessments')}
                className={`px-4 py-2 rounded-lg border text-sm font-semibold transition ${
                  activeTab === 'assessments'
                    ? 'bg-gray-900 text-white dark:bg-gray-100 dark:text-gray-900 border-gray-900 dark:border-gray-100'
                    : 'bg-white dark:bg-gray-900 text-gray-700 dark:text-gray-200 border-gray-300 dark:border-gray-700 hover:bg-gray-100 dark:hover:bg-gray-800'
                }`}
              >
                {t('nav.assessments')}
              </button>

              <button
                type="button"
                onClick={() => setActiveTab('analysis')}
                disabled={isEditingAssessment}
                className={`px-4 py-2 rounded-lg border text-sm font-semibold transition ${
                  activeTab === 'analysis'
                    ? 'bg-gray-900 text-white dark:bg-gray-100 dark:text-gray-900 border-gray-900 dark:border-gray-100'
                    : 'bg-white dark:bg-gray-900 text-gray-700 dark:text-gray-200 border-gray-300 dark:border-gray-700 hover:bg-gray-100 dark:hover:bg-gray-800'
                } ${isEditingAssessment ? 'opacity-50 cursor-not-allowed' : ''}`}
                title={isEditingAssessment ? t('nav.analysis_disabled') : t('nav.analysis_open')}
              >
                {t('nav.analysis')}
              </button>

              <button
                type="button"
                onClick={() => setActiveTab('profile')}
                disabled={isEditingAssessment}
                className={`px-4 py-2 rounded-lg border text-sm font-semibold transition ${
                  activeTab === 'profile'
                    ? 'bg-gray-900 text-white dark:bg-gray-100 dark:text-gray-900 border-gray-900 dark:border-gray-100'
                    : 'bg-white dark:bg-gray-900 text-gray-700 dark:text-gray-200 border-gray-300 dark:border-gray-700 hover:bg-gray-100 dark:hover:bg-gray-800'
                } ${isEditingAssessment ? 'opacity-50 cursor-not-allowed' : ''}`}
                title={isEditingAssessment ? t('nav.profile_disabled') : t('nav.profile_open')}
              >
                {t('nav.profile')}
              </button>
            </nav>

            <div className="flex items-center gap-3">
              {renderThemeToggle()}
              <button
                onClick={handleSignOut}
                className="px-4 py-2 bg-gray-900 dark:bg-gray-100 text-white dark:text-gray-900 rounded-lg hover:bg-gray-800 dark:hover:bg-gray-200 transition"
              >
                {t('nav.sign_out')}
              </button>
            </div>
          </div>
        </header>

        {activeTab !== 'profile' && (
          <PatTestManager
            user={session?.user}
            activeTab={activeTab}
            onEditingStateChange={setIsEditingAssessment}
            testsVisible={Boolean(profile?.testsVisible)}
            isProfileLoading={profileLoading}
          />
        )}

        {activeTab === 'profile' && (
          <ProfileTab
            session={session}
            profile={profile}
            loading={profileLoading}
            error={profileError}
            onSave={saveProfile}
            onDelete={deleteProfileData}
            onSessionChange={setSession}
          />
        )}
      </div>
    </LanguageProvider>
  )
}

export default App
