import { useEffect, useRef } from 'react'
import { useNavigate } from '@tanstack/react-router'
import { Check, Home, Minus, RotateCcw, Sparkles, X } from 'lucide-react'
import { useTestStore } from '@/store/test-store'
import { useRequireAuth } from '@/hooks/use-require-auth'
import { useAuthStore } from '@/store/auth-store'
import { saveTestResult } from '@/lib/progress-service'
import { useAwardActivity } from '@/hooks/use-gamification'
import { XP_REWARDS } from '@/lib/gamification-service'

const ANSWER_LABELS = ['A', 'B', 'C', 'D']

function formatMinSec(s: number) {
  const mm = String(Math.floor(s / 60)).padStart(2, '0')
  const ss = String(s % 60).padStart(2, '0')
  return `${mm}:${ss}`
}

function Ring({ percent, size = 110, stroke = 7, color, bg, children }: {
  percent: number; size?: number; stroke?: number; color: string; bg: string; children: React.ReactNode
}) {
  const cx = size / 2
  const r = cx - stroke
  const c = 2 * Math.PI * r
  const offset = c - (Math.min(percent, 100) / 100) * c
  return (
    <div className="relative grid place-items-center flex-shrink-0" style={{ width: size, height: size }}>
      <svg className="-rotate-90" width={size} height={size}>
        <circle cx={cx} cy={cx} r={r} fill="none" stroke={bg} strokeWidth={stroke} />
        <circle
          cx={cx} cy={cx} r={r}
          fill="none"
          stroke={color}
          strokeWidth={stroke}
          strokeLinecap="round"
          strokeDasharray={c}
          strokeDashoffset={offset}
          style={{ transition: 'stroke-dashoffset 0.7s ease' }}
        />
      </svg>
      <div className="absolute inset-0 grid place-items-center">{children}</div>
    </div>
  )
}

function HeadlineByPercent({ pct }: { pct: number }) {
  if (pct >= 80) return <>Xuất <i>sắc!</i></>
  if (pct >= 60) return <>Khá <i>tốt</i></>
  return <>Cần <i>ôn thêm</i></>
}

// Hero theme by estimated TOEIC score band — aligned to ETS proficiency levels.
// <225 Novice · 225–549 Elementary→Basic · 550–749 Working · ≥750 Professional
// Light backgrounds use ink text; dark use paper text.
function heroThemeByScore(score: number) {
  if (score < 225) {
    return {
      bg: 'var(--at-warm)',
      text: 'var(--at-paper)',
      muted: 'rgba(250,248,243,0.6)',
      labelMuted: 'rgba(250,248,243,0.5)',
      ringBg: 'rgba(255,255,255,0.15)',
      ringColor: 'var(--at-paper)',
      glow: 'rgba(255,255,255,0.18)',
      btnSolidBg: 'var(--at-paper)',
      btnSolidText: 'var(--at-ink)',
      btnGhostBorder: 'rgba(255,255,255,0.25)',
      btnGhostHover: 'rgba(255,255,255,0.1)',
    }
  }
  if (score < 550) {
    return {
      bg: 'var(--at-warm-soft)',
      text: 'var(--at-ink)',
      muted: 'var(--at-mute)',
      labelMuted: 'var(--at-mute)',
      ringBg: 'rgba(15,17,20,0.08)',
      ringColor: 'var(--at-warm)',
      glow: 'rgba(210,106,59,0.18)',
      btnSolidBg: 'var(--at-ink)',
      btnSolidText: 'var(--at-paper)',
      btnGhostBorder: 'var(--at-line)',
      btnGhostHover: 'rgba(15,17,20,0.05)',
    }
  }
  if (score < 750) {
    return {
      bg: 'var(--at-good-soft)',
      text: 'var(--at-ink)',
      muted: 'var(--at-mute)',
      labelMuted: 'var(--at-mute)',
      ringBg: 'rgba(15,17,20,0.08)',
      ringColor: 'var(--at-good)',
      glow: 'rgba(47,125,74,0.18)',
      btnSolidBg: 'var(--at-ink)',
      btnSolidText: 'var(--at-paper)',
      btnGhostBorder: 'var(--at-line)',
      btnGhostHover: 'rgba(15,17,20,0.05)',
    }
  }
  return {
    bg: 'var(--at-good)',
    text: 'var(--at-paper)',
    muted: 'rgba(250,248,243,0.65)',
    labelMuted: 'rgba(250,248,243,0.55)',
    ringBg: 'rgba(255,255,255,0.15)',
    ringColor: 'var(--at-paper)',
    glow: 'rgba(255,255,255,0.18)',
    btnSolidBg: 'var(--at-paper)',
    btnSolidText: 'var(--at-ink)',
    btnGhostBorder: 'rgba(255,255,255,0.25)',
    btnGhostHover: 'rgba(255,255,255,0.1)',
  }
}

export function TestResult() {
  const navigate = useNavigate()
  const { testId, testName, parts, answers, timeUsed, reset } = useTestStore()
  const { isAuthenticated, isLoading } = useRequireAuth()
  const user = useAuthStore((s) => s.user)
  const savedRef = useRef(false)
  const { mutate: awardActivity } = useAwardActivity()

  const allQuestions = parts.flatMap(p => p.questions)

  useEffect(() => {
    if (isLoading) return
    if (!isAuthenticated) navigate({ to: '/toeic' })
  }, [isLoading, isAuthenticated, navigate])

  useEffect(() => {
    if (!user || savedRef.current || allQuestions.length === 0) return
    savedRef.current = true
    const correctCount = allQuestions.filter(q => answers[q.id] === q.correctAnswer).length
    awardActivity({ xp: XP_REWARDS.test })
    saveTestResult(user.id, {
      testId,
      selectedParts: parts.map(p => p.partNumber),
      score: correctCount,
      total: allQuestions.length,
      timeUsed,
      answers: allQuestions.map(q => ({
        questionId: q.id,
        selected: answers[q.id] ?? null,
        correct: answers[q.id] === q.correctAnswer,
      })),
    })
  }, [user, allQuestions.length])

  if (allQuestions.length === 0) {
    return (
      <div className="px-6 py-10 text-center">
        <p style={{ color: 'var(--at-mute)' }} className="mb-4">Không có dữ liệu bài thi.</p>
        <button
          onClick={() => navigate({ to: '/toeic' })}
          style={{
            background: 'var(--at-ink)', color: 'var(--at-paper)',
            padding: '10px 20px', borderRadius: 10, fontWeight: 600, fontSize: 14,
          }}
        >
          Chọn đề thi
        </button>
      </div>
    )
  }

  const correct = allQuestions.filter(q => answers[q.id] === q.correctAnswer).length
  const wrong = allQuestions.filter(q => answers[q.id] !== null && answers[q.id] !== undefined && answers[q.id] !== q.correctAnswer).length
  const skipped = allQuestions.filter(q => answers[q.id] === null || answers[q.id] === undefined).length
  const total = allQuestions.length
  const pct = total > 0 ? Math.round((correct / total) * 100) : 0
  // TOEIC scaled score 10–990. Linear approximation from raw accuracy;
  // real ETS scaling is non-linear, but good enough as a practice estimate.
  const toeicEstimate = Math.round(10 + pct * 9.8)
  const theme = heroThemeByScore(toeicEstimate)

  return (
    <div className="px-6 lg:px-10 py-10 page-enter">
      {/* Top row — headline card (dark) + TOEIC estimate card */}
      <div className="grid gap-5 mb-5" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(380px, 1fr))' }}>
        {/* Hero result card — themed by score */}
        <div
          className="relative overflow-hidden"
          style={{
            background: theme.bg,
            color: theme.text,
            borderRadius: 24,
            padding: 32,
            boxShadow: 'var(--shadow-card)',
            transition: 'background 0.3s ease',
          }}
        >
          <div
            style={{
              position: 'absolute', top: -40, right: -40, width: 200, height: 200,
              borderRadius: '50%',
              background: `radial-gradient(circle, ${theme.glow}, transparent 60%)`,
            }}
          />
          <div className="relative">
            <div
              className="uppercase"
              style={{
                fontSize: 10.5, fontWeight: 700, letterSpacing: '0.16em',
                color: theme.labelMuted, marginBottom: 10,
              }}
            >
              Kết quả
            </div>
            <div
              style={{
                fontFamily: 'var(--at-serif)', fontSize: 40, fontWeight: 400,
                letterSpacing: '-0.025em', lineHeight: 1.05, marginBottom: 6,
              }}
            >
              <HeadlineByPercent pct={pct} />
            </div>
            <div style={{ fontSize: 13, color: theme.muted, marginBottom: 24 }}>
              {testName}
            </div>
            <div className="flex items-center gap-7 flex-wrap">
              <Ring percent={pct} color={theme.ringColor} bg={theme.ringBg}>
                <div style={{ color: theme.text, textAlign: 'center' }}>
                  <div
                    style={{
                      fontFamily: 'var(--at-serif)', fontSize: 30, fontWeight: 400,
                      letterSpacing: '-0.02em', lineHeight: 1,
                    }}
                  >
                    {pct}
                  </div>
                  <div
                    className="uppercase"
                    style={{
                      fontSize: 9.5, opacity: 0.6, letterSpacing: '0.14em',
                      marginTop: 4, fontWeight: 600,
                    }}
                  >
                    điểm
                  </div>
                </div>
              </Ring>
              <div>
                <div
                  className="uppercase"
                  style={{
                    fontSize: 10.5, color: theme.labelMuted,
                    letterSpacing: '0.14em', fontWeight: 600, marginBottom: 2,
                  }}
                >
                  Đúng
                </div>
                <div
                  className="tabular-nums"
                  style={{
                    fontFamily: 'var(--at-serif)', fontSize: 28, fontWeight: 400,
                    letterSpacing: '-0.02em',
                  }}
                >
                  {correct}
                  <span style={{ opacity: 0.5, fontSize: 18, fontStyle: 'italic' }}>
                    /{total}
                  </span>
                </div>
                <div
                  className="uppercase"
                  style={{
                    fontSize: 10.5, color: theme.labelMuted,
                    letterSpacing: '0.14em', fontWeight: 600, marginTop: 14, marginBottom: 2,
                  }}
                >
                  Thời gian
                </div>
                <div
                  className="tabular-nums"
                  style={{
                    fontFamily: 'var(--at-mono)', fontSize: 24, fontWeight: 500,
                    letterSpacing: '0.02em',
                  }}
                >
                  {formatMinSec(timeUsed)}
                </div>
              </div>
              <div className="ml-auto flex flex-col gap-2">
                <button
                  onClick={() => navigate({ to: '/toeic/session' })}
                  className="inline-flex items-center gap-2 transition-[filter] hover:brightness-110"
                  style={{
                    padding: '10px 18px', borderRadius: 10,
                    background: theme.btnSolidBg, color: theme.btnSolidText,
                    fontSize: 13, fontWeight: 600,
                  }}
                >
                  <RotateCcw size={14} />
                  Làm lại
                </button>
                <button
                  onClick={() => { reset(); navigate({ to: '/toeic' }) }}
                  className="inline-flex items-center gap-2 transition-colors"
                  style={{
                    padding: '10px 18px', borderRadius: 10,
                    background: 'transparent', color: theme.text,
                    border: `1px solid ${theme.btnGhostBorder}`,
                    fontSize: 13, fontWeight: 600,
                  }}
                  onMouseEnter={(e) => (e.currentTarget.style.background = theme.btnGhostHover)}
                  onMouseLeave={(e) => (e.currentTarget.style.background = 'transparent')}
                >
                  <Home size={14} />
                  Trang chủ
                </button>
              </div>
            </div>
          </div>
        </div>

        {/* TOEIC estimate card */}
        <div
          style={{
            background: 'var(--at-surface)',
            border: '1px solid var(--at-line)',
            borderRadius: 24,
            padding: 32,
            boxShadow: 'var(--shadow-sm)',
          }}
        >
          <div
            className="uppercase"
            style={{
              fontFamily: 'var(--at-serif)', fontStyle: 'italic', fontWeight: 500,
              fontSize: 12, letterSpacing: '0.08em',
              color: 'var(--at-mute)', marginBottom: 8,
            }}
          >
            Dự kiến TOEIC
          </div>
          <div
            style={{
              fontFamily: 'var(--at-serif)', fontSize: 24, fontWeight: 500,
              letterSpacing: '-0.015em', marginBottom: 4, color: 'var(--at-ink)',
            }}
          >
            Điểm <i style={{ color: 'var(--at-brand)' }}>ước tính</i>
          </div>
          <div style={{ fontSize: 12.5, color: 'var(--at-mute)', marginBottom: 18 }}>
            Dựa trên bài thi hôm nay
          </div>
          <div className="flex items-baseline gap-2 mb-4">
            <div
              className="tabular-nums"
              style={{
                fontFamily: 'var(--at-serif)', fontSize: 56, fontWeight: 400,
                letterSpacing: '-0.035em', color: 'var(--at-brand)', lineHeight: 1,
              }}
            >
              {toeicEstimate}
            </div>
            <div
              style={{
                fontSize: 14, color: 'var(--at-mute)',
                fontFamily: 'var(--at-serif)', fontStyle: 'italic',
              }}
            >
              / 990
            </div>
          </div>
          <div
            style={{
              height: 6, background: 'var(--at-line-2)',
              borderRadius: 999, overflow: 'hidden', position: 'relative',
              marginBottom: 6,
            }}
          >
            <span
              style={{
                position: 'absolute', inset: '0 auto 0 0',
                background: 'var(--at-brand)',
                width: `${(toeicEstimate / 990) * 100}%`,
                borderRadius: 999,
                transition: 'width 0.7s cubic-bezier(0.2,0.7,0.2,1)',
              }}
            />
          </div>
          <div className="flex justify-between" style={{ fontSize: 11, color: 'var(--at-mute)' }}>
            <span>0</span>
            <span>Mục tiêu: 850</span>
            <span>990</span>
          </div>
          <div style={{ height: 1, background: 'var(--at-line)', margin: '18px 0' }} />
          <div className="grid grid-cols-3 gap-4">
            <Stat label="Đúng" value={correct} color="var(--at-good)" />
            <Stat label="Sai" value={wrong} color="var(--at-bad)" />
            <Stat label="Bỏ qua" value={skipped} color="var(--at-mute)" />
          </div>
        </div>
      </div>

      {/* Per-part review */}
      {parts.map(part => (
        <div
          key={part.partNumber}
          style={{
            background: 'var(--at-surface)',
            border: '1px solid var(--at-line)',
            borderRadius: 18,
            padding: 24,
            marginBottom: 16,
            boxShadow: 'var(--shadow-sm)',
          }}
        >
          <div className="flex items-center justify-between mb-4">
            <div>
              <div
                className="uppercase"
                style={{
                  fontFamily: 'var(--at-serif)', fontStyle: 'italic', fontWeight: 500,
                  fontSize: 12, letterSpacing: '0.08em', color: 'var(--at-brand)',
                  marginBottom: 4,
                }}
              >
                Part {part.partNumber}
              </div>
              <div
                style={{
                  fontFamily: 'var(--at-serif)', fontSize: 22, fontWeight: 400,
                  letterSpacing: '-0.015em', color: 'var(--at-ink)',
                }}
              >
                {part.partName}
              </div>
            </div>
            <div className="flex items-center gap-2">
              <Chip kind="good" icon={<Check size={10} strokeWidth={3} />}>
                {part.questions.filter(q => answers[q.id] === q.correctAnswer).length} đúng
              </Chip>
              <Chip kind="bad" icon={<X size={10} strokeWidth={3} />}>
                {part.questions.filter(q => answers[q.id] !== null && answers[q.id] !== undefined && answers[q.id] !== q.correctAnswer).length} sai
              </Chip>
            </div>
          </div>

          <div>
            {part.questions.map((q, i) => {
              const userAnswer = answers[q.id] ?? null
              const isCorrect = userAnswer === q.correctAnswer
              const isSkipped = userAnswer === null || userAnswer === undefined
              const statusColor = isCorrect
                ? 'var(--at-good)'
                : isSkipped
                  ? 'var(--at-mute)'
                  : 'var(--at-bad)'
              const statusBg = isCorrect
                ? 'var(--at-good-soft)'
                : isSkipped
                  ? 'var(--at-line-2)'
                  : 'var(--at-bad-soft)'
              return (
                <div
                  key={q.id}
                  className="flex items-start gap-3"
                  style={{
                    padding: '14px 0',
                    borderTop: i === 0 ? 'none' : '1px solid var(--at-line)',
                  }}
                >
                  <div
                    className="grid place-items-center flex-shrink-0"
                    style={{
                      width: 28, height: 28, borderRadius: 8,
                      background: statusBg, color: statusColor,
                    }}
                  >
                    {isCorrect
                      ? <Check size={16} strokeWidth={2.5} />
                      : isSkipped
                        ? <Minus size={16} strokeWidth={2.5} />
                        : <X size={16} strokeWidth={2.5} />}
                  </div>

                  <div className="flex-1 min-w-0">
                    <div
                      className="mb-1.5"
                      style={{
                        fontSize: 13.5, fontWeight: 500, color: 'var(--at-ink)',
                        lineHeight: 1.5,
                      }}
                    >
                      <span style={{ color: 'var(--at-mute)', fontFamily: 'var(--at-serif)', fontStyle: 'italic' }}>
                        Câu {i + 1}.{' '}
                      </span>
                      {q.text || <span style={{ color: 'var(--at-mute-2)' }}>— (nghe/nhìn)</span>}
                    </div>
                    <div style={{ fontSize: 12.5, color: 'var(--at-mute)', lineHeight: 1.5 }}>
                      Đáp án đúng:{' '}
                      <b style={{ color: 'var(--at-good)' }}>
                        {ANSWER_LABELS[q.correctAnswer]}. {q.options[q.correctAnswer]}
                      </b>
                      {!isCorrect && !isSkipped && userAnswer !== null && (
                        <>
                          {' · '}Bạn chọn:{' '}
                          <b style={{ color: 'var(--at-bad)' }}>
                            {ANSWER_LABELS[userAnswer]}. {q.options[userAnswer]}
                          </b>
                        </>
                      )}
                    </div>
                    {q.explanation && (
                      <div
                        className="mt-2"
                        style={{
                          fontSize: 12.5,
                          color: 'var(--at-ink-2)',
                          background: 'var(--at-paper-2)',
                          border: '1px solid var(--at-line)',
                          borderRadius: 8,
                          padding: '10px 12px',
                          lineHeight: 1.55,
                        }}
                      >
                        <span
                          style={{
                            fontFamily: 'var(--at-serif)', fontStyle: 'italic',
                            color: 'var(--at-brand)', marginRight: 6,
                          }}
                        >
                          <Sparkles size={10} className="inline -mt-0.5 mr-1" />
                          Giải thích
                        </span>
                        {q.explanation}
                      </div>
                    )}
                  </div>
                </div>
              )
            })}
          </div>
        </div>
      ))}
    </div>
  )
}

function Stat({ label, value, color }: { label: string; value: number; color: string }) {
  return (
    <div>
      <div
        className="uppercase"
        style={{
          fontSize: 10.5, color: 'var(--at-mute)',
          letterSpacing: '0.1em', fontWeight: 600, marginBottom: 4,
        }}
      >
        {label}
      </div>
      <div
        className="tabular-nums"
        style={{
          fontFamily: 'var(--at-serif)', fontSize: 22, fontWeight: 400,
          letterSpacing: '-0.02em', color,
        }}
      >
        {value}
      </div>
    </div>
  )
}

function Chip({ kind, icon, children }: {
  kind: 'good' | 'bad'; icon: React.ReactNode; children: React.ReactNode
}) {
  const bg = kind === 'good' ? 'var(--at-good-soft)' : 'var(--at-bad-soft)'
  const fg = kind === 'good' ? 'var(--at-good-ink)' : 'var(--at-bad)'
  return (
    <span
      className="inline-flex items-center gap-1.5"
      style={{
        padding: '5px 10px', borderRadius: 999,
        background: bg, color: fg,
        fontSize: 11, fontWeight: 600, letterSpacing: '0.02em',
      }}
    >
      {icon}
      {children}
    </span>
  )
}
