import { useState, useEffect, useRef } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import api from '../api/client'
import Dialog from '../components/Dialog'
import { useDialog } from '../hooks/useDialog'

function JobDetail({ job }) {
  const [steps, setSteps] = useState([])
  const [expanded, setExpanded] = useState(false)
  const [quizData, setQuizData] = useState(null)
  const { dialogProps, openAlert } = useDialog()
  const pollRef = useRef(null)
  const navigate = useNavigate()

  const load = async () => {
    try {
      const res = await api.get(`/quizzes/job/${job.job_id}`)
      setSteps(res.data.steps || [])
      if (res.data.status === 'completed' && res.data.quiz_id && !quizData) {
        const qRes = await api.get(`/quizzes/${res.data.quiz_id}`)
        setQuizData(qRes.data)
      }
    } catch { }
  }

  useEffect(() => {
    if (expanded) {
      load()
      if (job.status === 'running') {
        pollRef.current = setInterval(load, 3000)
      }
    }
    return () => clearInterval(pollRef.current)
  }, [expanded, job.status])

  // Parse skipped questions from quiz data
  const skipped = quizData?.skipped_questions ? JSON.parse(quizData.skipped_questions) : []

  // Parse chunk summaries from steps
  const chunkSteps = steps.filter(s => s.step === 'ai' && s.message.includes('questions extracted'))

  const statusColor = job.status === 'completed' ? 'var(--correct-fg)' : job.status === 'failed' ? 'var(--wrong-fg)' : '#92400e'
  const statusBg = job.status === 'completed' ? 'var(--correct-bg)' : job.status === 'failed' ? 'var(--wrong-bg)' : '#fef3c7'

  return (
    <div className="card" style={{ marginBottom: 12 }}>
      <Dialog {...dialogProps} />
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
        <div style={{ flex: 1 }}>
          <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 4, flexWrap: 'wrap' }}>
            <span style={{ fontWeight: 700, fontSize: '0.95rem' }}>{job.title}</span>
            <span style={{ fontSize: '0.72rem', fontWeight: 600, padding: '2px 8px', borderRadius: 10, background: statusBg, color: statusColor }}>
              {job.status}
            </span>
            {job.status === 'running' && <div className="spinner" style={{ width: 14, height: 14, borderWidth: 2 }} />}
          </div>
          <div style={{ fontSize: '0.8rem', color: 'var(--text-muted)' }}>
            {job.steps_count} steps
            {quizData && ` · ${quizData.questions_count} questions extracted`}
            {skipped.length > 0 && <span style={{ color: 'var(--wrong-fg)', marginLeft: 8 }}>· {skipped.length} questions skipped</span>}
          </div>
          {job.last_step && (
            <div style={{ fontSize: '0.78rem', color: 'var(--text-subtle)', marginTop: 2 }}>{job.last_step}</div>
          )}
        </div>
        <div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
          {job.quiz_id && (
            <Link to={`/quizzes/${job.quiz_id}`} className="btn btn-primary btn-sm">Open Quiz</Link>
          )}
          {job.status === 'running' && (
            <button className="btn btn-danger btn-sm" onClick={async () => {
              try {
                await api.post(`/quizzes/job/${job.job_id}/cancel`)
                job.status = 'cancelled'
                load()
              } catch (e) {
                await openAlert(e.response?.data?.detail || 'Failed to cancel', { title: 'Error' })
              }
            }}>Cancel</button>
          )}
          <button className="btn btn-secondary btn-sm" onClick={() => setExpanded(v => !v)}>
            {expanded ? 'Hide' : 'Details'}
          </button>
        </div>
      </div>

      {expanded && (
        <div style={{ marginTop: 16 }}>
          {/* Skipped questions warning */}
          {skipped.length > 0 && (
            <div style={{ background: 'var(--wrong-bg)', border: '1px solid var(--wrong-bd)', borderRadius: 8, padding: '12px 14px', marginBottom: 14 }}>
              <div style={{ fontWeight: 600, fontSize: '0.85rem', color: 'var(--wrong-fg)', marginBottom: 8 }}>
                {skipped.length} question{skipped.length !== 1 ? 's' : ''} could not be imported — no correct answer found
              </div>
              <p style={{ fontSize: '0.78rem', color: 'var(--wrong-fg)', marginBottom: 8, opacity: 0.85 }}>
                These questions were extracted from the PDF but skipped because the AI could not identify the correct answer. This usually means the "Correct Answer:" line was missing or ambiguous in the source document.
              </p>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                {skipped.map((q, i) => (
                  <div key={i} style={{ fontSize: '0.78rem', color: 'var(--text-muted)', padding: '4px 8px', background: 'rgba(255,255,255,0.5)', borderRadius: 4 }}>
                    {i + 1}. {q}…
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Per-chunk results */}
          {chunkSteps.length > 0 && (
            <div style={{ marginBottom: 14 }}>
              <div style={{ fontSize: '0.78rem', fontWeight: 700, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 8 }}>
                Chunk Breakdown
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                {chunkSteps.map((s, i) => (
                  <div key={i} style={{ fontSize: '0.8rem', color: 'var(--text)', padding: '4px 10px', background: 'var(--bg)', borderRadius: 6 }}>
                    {s.message}
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Full step log */}
          {steps.length > 0 && (
            <details>
              <summary style={{ fontSize: '0.78rem', color: 'var(--text-muted)', cursor: 'pointer', marginBottom: 8 }}>
                Full extraction log ({steps.length} steps)
              </summary>
              <div style={{ background: 'var(--bg)', borderRadius: 8, padding: '10px 14px', fontFamily: 'monospace', fontSize: '0.75rem', maxHeight: 260, overflowY: 'auto' }}>
                {steps.map((s, i) => (
                  <div key={i} style={{ marginBottom: 5, color: s.step === 'error' ? 'var(--wrong-fg)' : s.step === 'done' ? 'var(--correct-fg)' : 'var(--text-muted)' }}>
                    <span style={{ opacity: 0.5, marginRight: 8 }}>[{s.step}]</span>{s.message}
                  </div>
                ))}
              </div>
            </details>
          )}
        </div>
      )}
    </div>
  )
}

export default function JobsPage() {
  const [jobs, setJobs] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    api.get('/quizzes/jobs')
      .then(res => setJobs(res.data))
      .catch(console.error)
      .finally(() => setLoading(false))
  }, [])

  if (loading) return <div className="loading"><div className="spinner" /></div>

  return (
    <div style={{ maxWidth: 760, margin: '0 auto' }}>
      <div className="card" style={{ marginBottom: 16 }}>
        <h2>Extraction Jobs</h2>
        <p style={{ color: 'var(--text-muted)', fontSize: '0.875rem', marginTop: 4 }}>
          History of quiz extractions — including skipped questions and chunk details.
        </p>
      </div>

      {jobs.length === 0 ? (
        <div className="card"><div className="empty-state">No extractions yet.</div></div>
      ) : (
        jobs.map(job => <JobDetail key={job.job_id} job={job} />)
      )}
    </div>
  )
}
