'use client'

import { useEffect, useRef, useState } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { useLocale, useTranslations } from 'next-intl'
import { ArrowLeft, Clock, ShieldCheck } from 'lucide-react'
import ProtectedRoute from '@/components/ProtectedRoute'
import Header from '@/components/Header'
import RoleplayCertification, { CertificationQuestion } from '@/components/RoleplayCertification'
import { useAuth } from '@/contexts/AuthContext'
import { authFetch } from '@/lib/fetchAuth'

type CertificationState = {
  sessionId: string
  expiresAt: string
  minCorrect: number
  totalQuestions: number
  questions: CertificationQuestion[]
}

function formatTime(totalSeconds: number): string {
  const minutes = Math.floor(totalSeconds / 60)
  const seconds = totalSeconds % 60
  return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
}

export default function AccountCertificationPage() {
  const t = useTranslations('dashboard.certification')
  const tc = useTranslations('certification')
  const locale = useLocale()
  const router = useRouter()
  const { user, loading: authLoading, setUserCertified } = useAuth()

  const [loading, setLoading] = useState(true)
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [certification, setCertification] = useState<CertificationState | null>(null)
  const [remainingSeconds, setRemainingSeconds] = useState(0)
  const sessionStartedRef = useRef(false)

  const startSession = async () => {
    if (!user) return

    setLoading(true)
    setError(null)

    try {
      const response = await authFetch('/api/user/certification/start', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'x-locale': locale,
        },
        body: JSON.stringify({}),
      })
      const data = await response.json()

      if (response.status === 409) {
        router.replace(`/${locale}/dashboard`)
        return
      }

      if (!response.ok) {
        setError(data.error || t('error'))
        return
      }

      if (!Array.isArray(data.questions) || data.questions.length === 0) {
        setError(t('error'))
        return
      }

      setCertification({
        sessionId: data.sessionId,
        expiresAt: data.expiresAt,
        minCorrect: data.minCorrect,
        totalQuestions: data.totalQuestions,
        questions: data.questions,
      })
    } catch {
      setError(t('error'))
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    if (authLoading) return

    if (!user) {
      router.replace(`/${locale}/login`)
      return
    }

    if (user.certified) {
      router.replace(`/${locale}/dashboard`)
      return
    }

    if (sessionStartedRef.current) return
    sessionStartedRef.current = true
    startSession()
  }, [authLoading, user, locale, router])

  useEffect(() => {
    if (!certification?.expiresAt) return

    const updateTimer = () => {
      const expiresMs = new Date(certification.expiresAt).getTime()
      const seconds = Number.isFinite(expiresMs)
        ? Math.max(0, Math.floor((expiresMs - Date.now()) / 1000))
        : 0
      setRemainingSeconds(seconds)
    }

    updateTimer()
    const interval = setInterval(updateTimer, 1000)
    return () => clearInterval(interval)
  }, [certification?.expiresAt])

  const handleSubmit = async (answers: Array<{ questionId: number; selectedIndex: number }>) => {
    if (!user || !certification) return
    setSubmitting(true)
    setError(null)

    try {
      const response = await authFetch('/api/user/certification/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          sessionId: certification.sessionId,
          answers,
        }),
      })
      const data = await response.json()

      if (!response.ok) {
        if (response.status === 403 && data.score !== undefined) {
          setError(t('failed', { score: data.score, required: data.minCorrect ?? 18 }))
        } else if (response.status === 410) {
          setError(t('expired'))
        } else {
          setError(data.error || t('error'))
        }
        return
      }

      setUserCertified(true)
      router.replace(`/${locale}/dashboard?certified=1`)
    } catch {
      setError(t('error'))
    } finally {
      setSubmitting(false)
    }
  }

  const handleTimeout = () => {
    setError(t('expired'))
    setCertification(null)
    sessionStartedRef.current = false
    setTimeout(() => router.push(`/${locale}/dashboard`), 2000)
  }

  const handleRetry = () => {
    sessionStartedRef.current = true
    startSession()
  }

  const timerClass =
    remainingSeconds <= 60
      ? 'text-red-300 border-red-400/50 bg-red-500/15'
      : 'text-amber-200 border-amber-400/40 bg-amber-500/15'

  return (
    <ProtectedRoute>
      <>
        <Header />
        <main className="min-h-screen pt-16 bg-gradient-to-b from-[#1E1E2E] via-[#002647] to-[#1E1E2E]">
          <div className="container mx-auto px-6 max-w-3xl">
            {/* Cabecera scrollable — no fija */}
            <div className="pt-8 pb-8 border-b border-[#0087FF]/30">
              <Link
                href={`/${locale}/dashboard`}
                className="inline-flex items-center gap-2 text-sm text-gray-400 hover:text-white transition-colors"
              >
                <ArrowLeft className="w-4 h-4" />
                {t('backToDashboard')}
              </Link>

              <div className="mt-6 flex flex-col gap-5 sm:flex-row sm:items-start sm:justify-between">
                <div className="flex items-start gap-4 min-w-0">
                  <div className="w-12 h-12 rounded-2xl bg-[#0087FF]/15 border border-[#0087FF]/30 flex items-center justify-center shrink-0">
                    <ShieldCheck className="w-6 h-6 text-[#8ab4ff]" />
                  </div>
                  <div>
                    <h1 className="text-2xl font-bold text-white leading-tight">{t('pageTitle')}</h1>
                    <p className="text-gray-400 text-sm mt-2 leading-relaxed">{t('pageSubtitle')}</p>
                  </div>
                </div>

                {certification && (
                  <div className="flex flex-wrap items-center gap-2 text-xs shrink-0">
                    <span className={`inline-flex items-center gap-2 px-3.5 py-2 rounded-full border ${timerClass}`}>
                      <Clock className="w-4 h-4" />
                      {tc('timeRemaining', { time: formatTime(remainingSeconds) })}
                    </span>
                    <span className="inline-flex items-center gap-2 px-3.5 py-2 rounded-full border border-[#0087FF]/30 bg-[#0087FF]/15 text-[#8ab4ff]">
                      {certification.totalQuestions} {tc('questionsLabel')}
                    </span>
                  </div>
                )}
              </div>
            </div>

            {/* Preguntas */}
            <div className="py-6 pb-16">
              {loading && (
                <div className="flex flex-col items-center justify-center py-24 gap-4">
                  <div className="h-10 w-10 rounded-full border-2 border-[#0087FF]/30 border-t-[#0087FF] animate-spin" />
                  <p className="text-gray-400 text-sm">{t('starting')}</p>
                </div>
              )}

              {!loading && error && !certification && (
                <div className="text-center py-24 space-y-4">
                  <p className="text-red-400 text-sm">{error}</p>
                  <button
                    type="button"
                    onClick={handleRetry}
                    className="px-5 py-2.5 rounded-xl bg-[#0087FF] hover:bg-[#0072d1] text-white text-sm transition-colors"
                  >
                    {t('retry')}
                  </button>
                </div>
              )}

              {!loading && certification && (
                <RoleplayCertification
                  sessionId={certification.sessionId}
                  expiresAt={certification.expiresAt}
                  minCorrect={certification.minCorrect}
                  totalQuestions={certification.totalQuestions}
                  questions={certification.questions}
                  loading={submitting}
                  error={error}
                  onSubmit={handleSubmit}
                  onCancel={() => router.push(`/${locale}/dashboard`)}
                  onTimeout={handleTimeout}
                  fullScreen
                />
              )}
            </div>
          </div>
        </main>
      </>
    </ProtectedRoute>
  )
}
