import React, { useEffect, useState } from 'react'
import SharedAssessmentView from './SharedAssessmentView'
import { getSharedAssessment } from '../lib/assessmentShareService'
import { useTranslation } from '../i18n/LanguageContext'

export default function SharedAssessmentPage({ shareToken, themeToggle }) {
  const t = useTranslation()
  const [assessment, setAssessment] = useState(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  useEffect(() => {
    let ignore = false

    const loadAssessment = async () => {
      if (!shareToken) {
        setError(t('shared.missing_token'))
        setLoading(false)
        return
      }

      setLoading(true)
      setError('')

      try {
        const sharedAssessment = await getSharedAssessment(shareToken)

        if (ignore) return

        if (!sharedAssessment) {
          setAssessment(null)
          setError(t('shared.invalid'))
          return
        }

        setAssessment(sharedAssessment)
      } catch (err) {
        if (ignore) return
        setAssessment(null)
        setError(err.message || t('shared.load_error'))
      } finally {
        if (!ignore) {
          setLoading(false)
        }
      }
    }

    loadAssessment()

    return () => {
      ignore = true
    }
  }, [shareToken])

  return (
    <div className="min-h-screen bg-gray-100 dark:bg-gray-950 text-gray-900 dark:text-gray-100">
      <div className="absolute top-4 right-4 z-20">{themeToggle}</div>

      {loading ? (
        <div className="min-h-screen flex items-center justify-center p-6">
          <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 shadow-sm p-6">
            {t('shared.loading')}
          </div>
        </div>
      ) : error ? (
        <div className="min-h-screen flex items-center justify-center p-6">
          <div className="max-w-xl w-full bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 shadow-sm p-6">
            <p className="text-xs uppercase tracking-[0.2em] text-rose-600 dark:text-rose-300">{t('shared.label')}</p>
            <h1 className="text-2xl font-bold mt-2">{t('shared.not_available')}</h1>
            <p className="text-gray-600 dark:text-gray-300 mt-3">{error}</p>
          </div>
        </div>
      ) : (
        <SharedAssessmentView assessment={assessment} />
      )}
    </div>
  )
}
