import { Check } from 'lucide-react'

interface Props {
  testName: string
  timeLeft: number      // seconds remaining; -1 = no limit (count-up mode)
  timeUsed: number      // seconds elapsed (used when no limit)
  totalQuestions: number
  answeredCount: number
  onSubmit: () => void
}

function formatTime(s: number): string {
  const h = Math.floor(s / 3600)
  const m = Math.floor((s % 3600) / 60)
  const sec = s % 60
  return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(sec).padStart(2, '0')}`
}

export function TestSessionHeader({
  testName, timeLeft, timeUsed, totalQuestions, answeredCount, onSubmit,
}: Props) {
  const isUnlimited = timeLeft === -1
  const displaySeconds = isUnlimited ? timeUsed : timeLeft
  const isUrgent = !isUnlimited && timeLeft < 300

  return (
    <header
      className="grid items-center flex-shrink-0"
      style={{
        gridTemplateColumns: '1fr auto 1fr',
        padding: '12px 24px',
        gap: 16,
        background: 'var(--at-surface)',
        borderBottom: '1px solid var(--at-line)',
      }}
    >
      <div className="flex flex-col gap-0.5" style={{ justifySelf: 'start' }}>
        <span
          style={{
            fontFamily: 'var(--at-serif)',
            fontStyle: 'italic',
            fontWeight: 400,
            fontSize: 11,
            letterSpacing: '0.04em',
            color: 'var(--at-mute)',
            textTransform: 'uppercase',
          }}
        >
          Phiên thi
        </span>
        <span style={{ fontWeight: 600, fontSize: 14, color: 'var(--at-ink)' }}>
          {testName} ·{' '}
          <span
            style={{
              color: 'var(--at-brand)',
              fontStyle: 'italic',
              fontFamily: 'var(--at-serif)',
              fontWeight: 400,
            }}
          >
            {answeredCount}/{totalQuestions}
          </span>{' '}
          câu
        </span>
      </div>

      <span
        className="tabular-nums text-center"
        style={{
          fontFamily: 'var(--at-mono)',
          fontSize: 22,
          fontWeight: 600,
          letterSpacing: '0.02em',
          color: isUrgent ? 'var(--at-bad)' : 'var(--at-brand)',
          animation: isUrgent ? 'pulse 1s infinite' : undefined,
        }}
      >
        {isUnlimited ? (
          <span style={{ color: 'var(--at-mute-2)', fontSize: 16 }}>∞</span>
        ) : (
          formatTime(displaySeconds)
        )}
      </span>

      <button
        onClick={onSubmit}
        className="inline-flex items-center gap-1.5 transition-[filter] hover:brightness-110"
        style={{
          justifySelf: 'end',
          padding: '8px 16px',
          borderRadius: 8,
          background: '#e53935',
          color: 'white',
          fontWeight: 600,
          fontSize: 13,
        }}
      >
        <Check size={14} strokeWidth={2.5} />
        Nộp bài
      </button>
    </header>
  )
}
