import { useState, useEffect, useCallback } from 'react'
import { useNavigate } from '@tanstack/react-router'
import { cn } from '@/lib/utils'
import { useTestStore } from '@/store/test-store'
import { useRequireAuth } from '@/hooks/use-require-auth'

const TOTAL_SECONDS = 600 // 10 minutes
const ANSWER_LABELS = ['A', 'B', 'C', 'D']

function formatTime(s: number) {
  return `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`
}

export function TestSession() {
  const navigate = useNavigate()
  const { partId, partName, questions, answers, setAnswer, submitExam } = useTestStore()
  const [currentQ, setCurrentQ] = useState(0)
  const [timeLeft, setTimeLeft] = useState(TOTAL_SECONDS)
  const { isAuthenticated, isLoading } = useRequireAuth()

  const handleSubmit = useCallback(() => {
    submitExam(TOTAL_SECONDS - timeLeft)
    navigate({ to: '/toeic/result' })
  }, [submitExam, navigate, timeLeft])

  // Countdown
  useEffect(() => {
    if (questions.length === 0) return
    const id = setInterval(() => {
      setTimeLeft((t) => {
        if (t <= 1) { clearInterval(id); handleSubmit(); return 0 }
        return t - 1
      })
    }, 1000)
    return () => clearInterval(id)
  }, [questions.length, handleSubmit])

  // Redirect if no exam started or not authenticated (wait for auth init)
  useEffect(() => {
    if (isLoading) return
    if (!isAuthenticated || questions.length === 0) navigate({ to: '/toeic' })
  }, [isLoading, isAuthenticated, questions.length, navigate])

  if (questions.length === 0) return null

  const question = questions[currentQ]
  const answeredCount = answers.filter((a) => a !== null).length
  const isUrgent = timeLeft < 60

  return (
    <div className="px-4 lg:px-6 py-6 max-w-6xl mx-auto page-enter">
      {/* Mobile progress bar */}
      <div className="lg:hidden mb-4">
        <div className="flex justify-between text-sm font-semibold mb-2">
          <span className="text-slate-700">Part {partId} — Câu {currentQ + 1}/{questions.length}</span>
          <span className={cn('font-bold tabular-nums', isUrgent ? 'text-red-600 timer-urgent' : 'text-blue-600')}>
            {formatTime(timeLeft)}
          </span>
        </div>
        <div className="h-1.5 w-full rounded-full bg-slate-200">
          <div
            className="h-full bg-blue-600 rounded-full transition-all"
            style={{ width: `${((currentQ + 1) / questions.length) * 100}%` }}
          />
        </div>
      </div>

      <div className="flex gap-5">
        {/* Left: Question */}
        <div className="flex-1 min-w-0">
          <div className="bg-white rounded-2xl p-6 border border-slate-200 mb-4">
            <div className="flex items-center gap-2 mb-4">
              <span className="bg-blue-600 text-white text-xs font-bold px-3 py-1 rounded-full">
                Câu {currentQ + 1}
              </span>
              <span className="text-xs text-slate-400">Part {partId} — {partName}</span>
            </div>
            <p className="text-base font-medium text-slate-800 leading-relaxed mb-6">
              {question.text}
            </p>
            <div className="space-y-3">
              {question.options.map((opt, i) => {
                const selected = answers[currentQ] === i
                return (
                  <button
                    key={i}
                    onClick={() => setAnswer(currentQ, i)}
                    className={cn(
                      'w-full flex items-center gap-3 p-4 border-2 rounded-xl text-sm font-medium text-left transition-all',
                      selected
                        ? 'border-blue-600 bg-blue-50 text-blue-700'
                        : 'border-slate-200 hover:border-blue-300 hover:bg-blue-50/50 text-slate-700',
                    )}
                  >
                    <span
                      className={cn(
                        'w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold flex-shrink-0',
                        selected ? 'bg-blue-600 text-white' : 'bg-slate-100 text-slate-500',
                      )}
                    >
                      {ANSWER_LABELS[i]}
                    </span>
                    {opt}
                  </button>
                )
              })}
            </div>
          </div>

          {/* Navigation */}
          <div className="flex items-center justify-between">
            <button
              onClick={() => setCurrentQ((q) => Math.max(0, q - 1))}
              disabled={currentQ === 0}
              className="flex items-center gap-2 px-5 py-2.5 border border-slate-200 rounded-xl text-sm font-semibold text-slate-600 hover:bg-slate-50 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
            >
              <span className="material-symbols-outlined" style={{ fontSize: 18 }}>chevron_left</span>
              Câu trước
            </button>
            <span className="text-xs text-slate-400 tabular-nums">{currentQ + 1} / {questions.length}</span>
            {currentQ < questions.length - 1 ? (
              <button
                onClick={() => setCurrentQ((q) => q + 1)}
                className="flex items-center gap-2 px-5 py-2.5 bg-blue-600 text-white rounded-xl text-sm font-semibold hover:bg-blue-700 transition-colors"
              >
                Câu tiếp theo
                <span className="material-symbols-outlined" style={{ fontSize: 18 }}>chevron_right</span>
              </button>
            ) : (
              <button
                onClick={handleSubmit}
                className="flex items-center gap-2 px-5 py-2.5 bg-red-600 text-white rounded-xl text-sm font-semibold hover:bg-red-700 transition-colors"
              >
                Nộp bài
                <span className="material-symbols-outlined" style={{ fontSize: 18 }}>send</span>
              </button>
            )}
          </div>
        </div>

        {/* Right panel — desktop only */}
        <div className="hidden lg:flex flex-col gap-4 w-60 flex-shrink-0">
          {/* Timer */}
          <div className="bg-white rounded-2xl p-5 border border-slate-200 text-center">
            <div className="text-xs text-slate-400 font-medium mb-2">Thời gian còn lại</div>
            <div
              className={cn(
                'text-5xl font-extrabold tabular-nums mb-1',
                isUrgent ? 'text-red-600 timer-urgent' : 'text-blue-600',
              )}
            >
              {formatTime(timeLeft)}
            </div>
            <div className="text-xs text-slate-400">phút : giây</div>
          </div>

          {/* Question dots */}
          <div className="bg-white rounded-2xl p-5 border border-slate-200">
            <div className="text-xs text-slate-400 font-medium mb-3">
              Danh sách câu · {answeredCount}/{questions.length} đã trả lời
            </div>
            <div className="grid grid-cols-5 gap-2">
              {questions.map((_, i) => (
                <button
                  key={i}
                  onClick={() => setCurrentQ(i)}
                  className={cn(
                    'w-8 h-8 rounded-full flex items-center justify-center text-[11px] font-semibold transition-all',
                    i === currentQ
                      ? 'border-2 border-blue-600 text-blue-600 shadow-sm shadow-blue-600/20'
                      : answers[i] !== null
                        ? 'bg-blue-600 text-white'
                        : 'border-2 border-slate-200 text-slate-400 hover:border-blue-300',
                  )}
                >
                  {i + 1}
                </button>
              ))}
            </div>
            <div className="flex items-center gap-3 mt-4 text-xs text-slate-400">
              <span className="w-4 h-4 rounded-full bg-blue-600 inline-block" /> Đã trả lời
              <span className="w-4 h-4 rounded-full border-2 border-slate-200 inline-block" /> Chưa làm
            </div>
          </div>

          <button
            onClick={handleSubmit}
            className="w-full py-3 bg-red-600 text-white rounded-xl font-bold text-sm hover:bg-red-700 transition-colors flex items-center justify-center gap-2"
          >
            <span className="material-symbols-outlined" style={{ fontSize: 18 }}>send</span>
            Nộp bài
          </button>
        </div>
      </div>

      {/* Mobile submit */}
      <div className="lg:hidden mt-4">
        <button
          onClick={handleSubmit}
          className="w-full py-3.5 bg-red-600 text-white rounded-xl font-bold text-sm hover:bg-red-700 transition-colors"
        >
          Nộp bài ngay
        </button>
      </div>
    </div>
  )
}
