import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import api from '../api/client'
import ConfirmButton from './ConfirmButton'

export default function InProgressQuizzes() {
  const [inProgress, setInProgress] = useState([])
  const navigate = useNavigate()

  useEffect(() => {
    api.get('/attempts/in-progress').then(res => setInProgress(res.data)).catch(() => {})
  }, [])

  const deleteAttempt = async (attemptId) => {
    await api.delete(`/attempts/${attemptId}`)
    setInProgress(prev => prev.filter(a => a.attempt_id !== attemptId))
  }

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

  return (
    <div className="card" style={{ marginBottom: 16, borderLeft: '4px solid #f59e0b' }}>
      <h2 style={{ marginBottom: 12, fontSize: '1rem', color: '#92400e' }}>
        ⏸ In Progress ({inProgress.length})
      </h2>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {inProgress.map(a => (
          <div key={a.attempt_id} style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            padding: '10px 14px', background: 'var(--bg)', borderRadius: 8, gap: 12,
          }}>
            <div>
              <div style={{ fontWeight: 600, fontSize: '0.9rem' }}>{a.quiz_title}</div>
              <div style={{ fontSize: '0.78rem', color: 'var(--text-muted)' }}>
                Started {new Date(a.started_at).toLocaleDateString()} · {a.total_questions} questions
              </div>
            </div>
            <div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
              <button className="btn btn-primary btn-sm" onClick={() => navigate(`/quizzes/${a.quiz_id}`)}>Resume</button>
              <ConfirmButton
                label="Delete" confirmLabel="Yes, delete"
                onConfirm={() => deleteAttempt(a.attempt_id)}
              />
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}
