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

const LETTERS = ['A', 'B', 'C', 'D', 'E', 'F']

function QuestionEditor({ q, quizId, onSaved, onDeleted }) {
  const [editing, setEditing] = useState(false)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')
  const [form, setForm] = useState({
    question_text: q.question_text,
    question_type: q.question_type,
    options: q.options ? [...q.options] : [],
    correct_answer: q.correct_answer,
    explanation: q.explanation || '',
  })

  const setOption = (i, val) => {
    const updated = [...form.options]
    // If this option was the correct answer, update correct_answer to new text
    const wasCorrect = form.options[i] === form.correct_answer
    updated[i] = val
    setForm(f => ({ ...f, options: updated, correct_answer: wasCorrect ? val : f.correct_answer }))
  }

  const save = async () => {
    if (!form.question_text.trim()) { setError('Question text is required'); return }
    if (form.options.length > 0 && !form.options.includes(form.correct_answer)) {
      setError('Correct answer must match one of the options exactly')
      return
    }
    setSaving(true); setError('')
    try {
      const res = await api.patch(`/quizzes/${quizId}/questions/${q.id}`, form)
      onSaved(res.data)
      setEditing(false)
    } catch (err) {
      setError(err.response?.data?.detail || 'Save failed')
    } finally { setSaving(false) }
  }

  const del = async () => {
    try {
      await api.delete(`/quizzes/${quizId}/questions/${q.id}`)
      onDeleted(q.id)
    } catch (err) {
      setError(err.response?.data?.detail || 'Delete failed')
    }
  }

  if (!editing) {
    return (
      <div className="review-card" style={{ borderLeftColor: 'var(--primary)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
          <p style={{ flex: 1, fontWeight: 600, fontSize: '0.95rem', color: 'var(--text)', lineHeight: 1.55 }}>
            {q.question_text}
          </p>
          <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
            <button className="btn btn-secondary btn-sm" onClick={() => setEditing(true)}>Edit</button>
            <ConfirmButton onConfirm={del} label="Delete" confirmLabel="Yes, delete" />
          </div>
        </div>
        {q.options && (
          <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 6 }}>
            {q.options.map((opt, i) => (
              <div key={i} style={{
                display: 'flex', gap: 10, alignItems: 'center', padding: '8px 12px',
                borderRadius: 6, fontSize: '0.875rem',
                background: opt === q.correct_answer ? 'var(--correct-bg)' : 'var(--option-bg)',
                border: `1px solid ${opt === q.correct_answer ? 'var(--correct-bd)' : 'var(--border)'}`,
                color: opt === q.correct_answer ? 'var(--correct-fg)' : 'var(--text)',
              }}>
                <span style={{ fontWeight: 700, width: 18 }}>{LETTERS[i]}.</span>
                <span style={{ flex: 1 }}>{opt}</span>
                {opt === q.correct_answer && <span style={{ fontSize: '0.75rem', fontWeight: 700 }}>✓ Correct</span>}
              </div>
            ))}
          </div>
        )}
        {q.explanation && (
          <div className="explanation" style={{ marginTop: 14 }}>
            <strong>Explanation:</strong> <span style={{ marginLeft: 4 }}>{q.explanation.slice(0, 200)}{q.explanation.length > 200 ? '…' : ''}</span>
          </div>
        )}
      </div>
    )
  }

  return (
    <div className="card" style={{ borderLeft: '4px solid var(--primary)' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
        <strong style={{ color: 'var(--text)' }}>Editing question</strong>
        <button className="btn btn-secondary btn-sm" onClick={() => { setEditing(false); setError('') }}>Cancel</button>
      </div>

      {error && <div className="alert alert-error">{error}</div>}

      <div className="form-group">
        <label>Question Text</label>
        <textarea rows={4} value={form.question_text} onChange={e => setForm(f => ({ ...f, question_text: e.target.value }))} />
      </div>

      {form.options.length > 0 && (
        <div className="form-group">
          <label>Answer Options — select the correct one</label>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {form.options.map((opt, i) => (
              <div key={i} style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                <input
                  type="radio"
                  name={`correct_${q.id}`}
                  checked={form.correct_answer === opt}
                  onChange={() => setForm(f => ({ ...f, correct_answer: opt }))}
                  style={{ width: 'auto', flexShrink: 0, accentColor: 'var(--primary)' }}
                  title="Mark as correct"
                />
                <span style={{
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  width: 24, height: 24, borderRadius: '50%', flexShrink: 0, fontSize: '0.72rem', fontWeight: 700,
                  background: form.correct_answer === opt ? 'var(--correct-fg)' : 'var(--border)',
                  color: form.correct_answer === opt ? 'white' : 'var(--text-muted)',
                }}>{LETTERS[i]}</span>
                <input
                  type="text" value={opt}
                  onChange={e => setOption(i, e.target.value)}
                  style={{ flex: 1, padding: '7px 12px', border: `1.5px solid ${form.correct_answer === opt ? 'var(--correct-bd)' : 'var(--border)'}`, borderRadius: 6, fontSize: '0.875rem', background: form.correct_answer === opt ? 'var(--correct-bg)' : 'var(--input-bg)', color: 'var(--text)', fontFamily: 'inherit' }}
                />
              </div>
            ))}
          </div>
          <p style={{ marginTop: 8, fontSize: '0.78rem', color: 'var(--text-subtle)' }}>
            Click the radio button to mark an option as correct. Editing an option text auto-updates the correct answer if it was selected.
          </p>
        </div>
      )}

      <div className="form-group">
        <label>Explanation (includes Critique and Content Specifications)</label>
        <textarea rows={8} value={form.explanation} onChange={e => setForm(f => ({ ...f, explanation: e.target.value }))} />
      </div>

      <button className="btn btn-primary" onClick={save} disabled={saving}>
        {saving ? 'Saving…' : 'Save Question'}
      </button>
    </div>
  )
}

export default function QuizEditPage() {
  const { id } = useParams()
  const navigate = useNavigate()
  const [quiz, setQuiz] = useState(null)
  const [questions, setQuestions] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [editingTitle, setEditingTitle] = useState(false)
  const [titleValue, setTitleValue] = useState('')
  const [savingTitle, setSavingTitle] = useState(false)

  useEffect(() => {
    Promise.all([
      api.get(`/quizzes/${id}`),
      api.get(`/quizzes/${id}/questions`),
    ]).then(([qRes, questRes]) => {
      setQuiz(qRes.data)
      setTitleValue(qRes.data.title)
      setQuestions(questRes.data)
    }).catch(() => navigate('/quizzes'))
      .finally(() => setLoading(false))
  }, [id])

  const handleSaved = (updated) => {
    const scrollY = window.scrollY
    setQuestions(prev => prev.map(q => q.id === updated.id ? updated : q))
    // Restore scroll position after React re-renders
    requestAnimationFrame(() => window.scrollTo({ top: scrollY, behavior: 'instant' }))
  }

  const handleDeleted = (questionId) => {
    setQuestions(prev => prev.filter(q => q.id !== questionId))
  }

  const saveTitle = async () => {
    if (!titleValue.trim()) { setError('Title cannot be empty'); return }
    setSavingTitle(true); setError('')
    try {
      const res = await api.patch(`/quizzes/${id}`, { title: titleValue.trim() })
      setQuiz(res.data)
      setTitleValue(res.data.title)
      setEditingTitle(false)
    } catch (err) {
      setError(err.response?.data?.detail || 'Failed to update title')
    } finally { setSavingTitle(false) }
  }

  if (loading) return <div className="loading"><div className="spinner"></div> Loading…</div>
  if (!quiz) return null

  return (
    <div style={{ maxWidth: 780, margin: '0 auto' }}>
      <div className="card" style={{ marginBottom: 8 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
          <div style={{ flex: 1 }}>
            <h2 style={{ marginBottom: 4 }}>Edit Quiz</h2>
            {!editingTitle ? (
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <p style={{ color: 'var(--text-muted)', fontSize: '0.875rem', margin: 0 }}>
                  {quiz.title} · {questions.length} questions
                </p>
                <button
                  className="btn btn-secondary btn-sm"
                  onClick={() => setEditingTitle(true)}
                  style={{ fontSize: '0.75rem', padding: '2px 8px' }}
                  title="Edit quiz title"
                >
                  ✏️ Edit Title
                </button>
              </div>
            ) : (
              <div style={{ marginTop: 8 }}>
                <input
                  type="text"
                  value={titleValue}
                  onChange={e => setTitleValue(e.target.value)}
                  placeholder="Quiz title"
                  style={{ width: '100%', padding: '6px 10px', marginBottom: 8, fontSize: '0.9rem' }}
                  autoFocus
                />
                <div style={{ display: 'flex', gap: 6 }}>
                  <button className="btn btn-primary btn-sm" onClick={saveTitle} disabled={savingTitle}>
                    {savingTitle ? 'Saving...' : 'Save'}
                  </button>
                  <button
                    className="btn btn-secondary btn-sm"
                    onClick={() => { setEditingTitle(false); setTitleValue(quiz.title); setError('') }}
                  >
                    Cancel
                  </button>
                </div>
              </div>
            )}
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <Link to={`/quizzes/${id}`} className="btn btn-secondary btn-sm">← Back to Quiz</Link>
          </div>
        </div>
      </div>

      {error && <div className="alert alert-error">{error}</div>}

      <p style={{ marginBottom: 16, fontSize: '0.85rem', color: 'var(--text-muted)' }}>
        Click <strong>Edit</strong> on any question to modify its text, options, correct answer, or explanation.
        Changes are saved per-question and take effect immediately.
      </p>

      {questions.length === 0 ? (
        <div className="card"><div className="empty-state">No questions found.</div></div>
      ) : questions.map((q, idx) => (
        <div key={q.id}>
          <div style={{ fontSize: '0.72rem', fontWeight: 700, color: 'var(--text-subtle)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 6 }}>
            Question {idx + 1}
          </div>
          <QuestionEditor
            q={q}
            quizId={id}
            onSaved={handleSaved}
            onDeleted={handleDeleted}
          />
        </div>
      ))}
    </div>
  )
}
