'use client'

import { useEffect, useMemo, useRef, useState } from 'react'
import { Button } from './ui/button'
import { ArrowRight, AlertTriangle } from 'lucide-react'
import { useTranslations } from 'next-intl'

export type CertificationQuestion = {
  id: number
  question: string
  options: string[]
}

type Props = {
  sessionId: string
  expiresAt: string
  minCorrect: number
  totalQuestions: number
  questions: CertificationQuestion[]
  loading: boolean
  error: string | null
  onSubmit: (answers: Array<{ questionId: number; selectedIndex: number }>) => void
  onCancel: () => void
  onTimeout: () => void
  cancelLabel?: string
  fullScreen?: boolean
}

function RadioOption({
  name,
  checked,
  onChange,
  label,
}: {
  name: string
  checked: boolean
  onChange: () => void
  label: string
}) {
  return (
    <label className="flex items-start gap-4 cursor-pointer group rounded-xl px-3 py-3 -mx-3 transition-colors hover:bg-white/[0.03]">
      <span className="relative mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center">
        <input
          type="radio"
          name={name}
          checked={checked}
          onChange={onChange}
          className="peer sr-only"
        />
        <span
          className={`h-5 w-5 rounded-full border-2 transition-colors ${
            checked
              ? 'border-[#0087FF] bg-[#0087FF]/20 shadow-[0_0_0_3px_rgba(0,135,255,0.15)]'
              : 'border-gray-500/80 group-hover:border-gray-400'
          }`}
        />
        <span
          className={`absolute h-2.5 w-2.5 rounded-full bg-[#0087FF] transition-transform ${
            checked ? 'scale-100' : 'scale-0'
          }`}
        />
      </span>
      <span className={`text-[15px] leading-relaxed ${checked ? 'text-white' : 'text-gray-300 group-hover:text-gray-200'}`}>
        {label}
      </span>
    </label>
  )
}

export default function RoleplayCertification({
  sessionId,
  expiresAt,
  minCorrect,
  totalQuestions,
  questions,
  loading,
  error,
  onSubmit,
  onCancel,
  onTimeout,
  cancelLabel,
  fullScreen = false,
}: Props) {
  const t = useTranslations('certification')
  const [answers, setAnswers] = useState<Record<number, number>>({})
  const [now, setNow] = useState(() => Date.now())
  const [footerVisible, setFooterVisible] = useState(false)
  const timedOutRef = useRef(false)
  const footerRef = useRef<HTMLDivElement>(null)

  const expiresMs = useMemo(() => new Date(expiresAt).getTime(), [expiresAt])
  const remainingSeconds = Number.isFinite(expiresMs)
    ? Math.max(0, Math.floor((expiresMs - now) / 1000))
    : 0
  const answeredCount = Object.keys(answers).length
  const allAnswered = questions.length > 0 && answeredCount === questions.length

  useEffect(() => {
    const interval = setInterval(() => setNow(Date.now()), 1000)
    return () => clearInterval(interval)
  }, [])

  useEffect(() => {
    if (remainingSeconds === 0 && !timedOutRef.current) {
      timedOutRef.current = true
      onTimeout()
    }
  }, [remainingSeconds, onTimeout])

  useEffect(() => {
    if (!fullScreen || !footerRef.current) return

    const observer = new IntersectionObserver(
      ([entry]) => setFooterVisible(entry.isIntersecting),
      { threshold: 0.25, rootMargin: '0px 0px -40px 0px' }
    )

    observer.observe(footerRef.current)
    return () => observer.disconnect()
  }, [fullScreen, questions.length])

  const handleSelect = (questionId: number, optionIndex: number) => {
    setAnswers((prev) => ({ ...prev, [questionId]: optionIndex }))
  }

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (!allAnswered || loading) return

    const payload = questions.map((q) => ({
      questionId: q.id,
      selectedIndex: answers[q.id],
    }))
    onSubmit(payload)
  }

  const submitFooter = (
    <div
      ref={fullScreen ? footerRef : undefined}
      className={
        fullScreen
          ? `mt-4 pt-10 border-t border-[#0087FF]/30 transition-all duration-500 ease-out ${
              footerVisible
                ? 'opacity-100 translate-y-0'
                : 'opacity-0 translate-y-6 pointer-events-none'
            }`
          : 'sticky bottom-0 pt-4 pb-1 bg-gradient-to-t from-[#0f1620] via-[#0f1620] to-transparent space-y-3'
      }
    >
      <div className="space-y-4">
        {!allAnswered && (
          <p className="text-amber-200/90 text-sm flex items-center justify-center gap-2">
            <AlertTriangle className="w-4 h-4 shrink-0" />
            {t('answerAll')}
          </p>
        )}

        {error && (
          <div className="p-4 bg-red-500/10 border border-red-500/40 rounded-xl">
            <p className="text-red-300 text-sm text-center">{error}</p>
          </div>
        )}

        <Button
          type="submit"
          disabled={loading || !allAnswered || remainingSeconds === 0}
          className="w-full bg-gradient-to-r from-[#0087FF] to-[#8ab4ff] text-white hover:from-[#0066CC] hover:to-[#6a9eff] rounded-full px-6 py-3.5 text-sm font-semibold shadow-lg shadow-[#0087FF]/25"
        >
          {loading ? (
            <div className="flex items-center justify-center space-x-2">
              <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white" />
              <span>{t('submitting')}</span>
            </div>
          ) : (
            <div className="flex items-center justify-center space-x-2">
              <span>{t('submit')}</span>
              <ArrowRight className="w-5 h-5" />
            </div>
          )}
        </Button>

        {!fullScreen && (
          <button
            type="button"
            onClick={onCancel}
            disabled={loading}
            className="w-full text-sm text-gray-400 hover:text-white transition-colors py-2"
          >
            {cancelLabel || t('cancel')}
          </button>
        )}
      </div>
    </div>
  )

  if (fullScreen) {
    return (
      <form onSubmit={handleSubmit}>
        <div>
          {questions.map((q, index) => (
            <div key={`${sessionId}-${q.id}`}>
              {index > 0 && (
                <div
                  className="my-10 h-px w-full bg-gradient-to-r from-transparent via-[#0087FF]/40 to-transparent"
                  aria-hidden="true"
                />
              )}

              <div className={index === 0 ? 'pb-10' : 'py-2 pb-10'}>
                <h3 className="text-lg font-semibold text-white mb-6 leading-snug">
                  <span className="text-[#8ab4ff] mr-2">{index + 1}.</span>
                  {q.question}
                </h3>
                <div className="space-y-1" role="radiogroup" aria-label={q.question}>
                  {q.options.map((option, optionIndex) => (
                    <RadioOption
                      key={optionIndex}
                      name={`question-${q.id}`}
                      checked={answers[q.id] === optionIndex}
                      onChange={() => handleSelect(q.id, optionIndex)}
                      label={option}
                    />
                  ))}
                </div>
              </div>
            </div>
          ))}
        </div>

        {submitFooter}

        {!footerVisible && (
          <p className="text-center text-gray-500 text-xs mt-8 pb-10 animate-pulse">
            {t('scrollToSubmit')}
          </p>
        )}
      </form>
    )
  }

  return (
    <div className="space-y-5">
      <div className="rounded-xl border border-[#0087FF]/20 bg-[#0c1320]/60 p-4 space-y-3">
        <p className="text-gray-400 text-sm">{t('introText', { minCorrect, totalQuestions })}</p>
      </div>

      <form onSubmit={handleSubmit} className="space-y-4 max-h-[52vh] overflow-y-auto pr-1">
        {questions.map((q, index) => (
          <fieldset
            key={`${sessionId}-${q.id}`}
            className="rounded-xl border border-[#0087FF]/15 bg-[#0c1320]/50 p-4 space-y-3"
          >
            <legend className="text-sm font-medium text-white px-1">
              {index + 1}. {q.question}
            </legend>
            <div className="space-y-2">
              {q.options.map((option, optionIndex) => (
                <RadioOption
                  key={optionIndex}
                  name={`question-${q.id}`}
                  checked={answers[q.id] === optionIndex}
                  onChange={() => handleSelect(q.id, optionIndex)}
                  label={option}
                />
              ))}
            </div>
          </fieldset>
        ))}
        {submitFooter}
      </form>
    </div>
  )
}
