import { useEffect, useState, useCallback } from 'react';
import { Link, useParams } from 'react-router-dom';
import api from '../../api/client.js';
import QuestionForm from '../../components/QuestionForm.jsx';
import Spinner from '../../components/Spinner.jsx';
import { useToast } from '../../context/ToastContext.jsx';
import { useConfirm } from '../../context/ConfirmContext.jsx';

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

export default function AdminQuestions() {
  const { courseId } = useParams();
  const toast = useToast();
  const confirm = useConfirm();
  const [questions, setQuestions] = useState(null);
  const [course, setCourse] = useState(null);
  const [showForm, setShowForm] = useState(false);
  const [editing, setEditing] = useState(null);
  const [busy, setBusy] = useState(false);
  const [tab, setTab] = useState('PRACTICE');

  const load = useCallback(() => {
    setQuestions(null);
    api.get(`/questions/course/${courseId}`, { params: { category: tab } })
      .then(({ data }) => setQuestions(data.questions));
    api.get('/courses/admin/all').then(({ data }) =>
      setCourse(data.courses.find((c) => c.id === courseId) || null)
    );
  }, [courseId, tab]);

  useEffect(() => { load(); }, [load]);

  const create = async (payload) => {
    setBusy(true);
    try {
      await api.post('/questions', { courseId, ...payload });
      toast.success('Question added');
      setShowForm(false);
      load();
    } catch (e) {
      toast.error(e.message);
    } finally {
      setBusy(false);
    }
  };

  const update = async (payload) => {
    setBusy(true);
    try {
      await api.patch(`/questions/${editing.id}`, { courseId, ...payload });
      toast.success('Question updated');
      setEditing(null);
      load();
    } catch (e) {
      toast.error(e.message);
    } finally {
      setBusy(false);
    }
  };

  const startEdit = (qn) => {
    setShowForm(false);
    setEditing(qn);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const remove = async (id) => {
    const ok = await confirm({
      title: 'Delete this question?',
      message: 'The question and its options will be permanently removed.',
      confirmLabel: 'Delete',
      tone: 'danger',
    });
    if (!ok) return;
    try {
      await api.delete(`/questions/${id}`);
      toast.success('Deleted');
      load();
    } catch (e) {
      toast.error(e.message);
    }
  };

  if (!questions) return <Spinner />;

  return (
    <div>
      <Link to="/admin/courses" className="muted">← Courses</Link>
      <div className="row-between mt-2 mb-3 wrap">
        <h2 style={{ margin: 0 }}>{course?.title || 'Questions'} <span className="muted">({questions.length})</span></h2>
        <button className="btn" onClick={() => { setEditing(null); setShowForm((s) => !s); }}>{showForm ? 'Close' : '+ Add question'}</button>
      </div>

      <div className="row wrap mb-3" style={{ gap: 6 }}>
        {['PRACTICE', 'EXAM'].map((c) => (
          <button key={c}
            className={`btn btn-sm ${tab === c ? '' : 'btn-ghost'}`}
            onClick={() => { setShowForm(false); setEditing(null); setTab(c); }}>
            {c === 'PRACTICE' ? 'Practice bank' : 'Exam bank'}
          </button>
        ))}
      </div>

      {editing && (
        <div className="card mb-3">
          <div className="row-between">
            <h3 style={{ margin: 0 }}>Edit question</h3>
            <button className="btn btn-sm btn-ghost" onClick={() => setEditing(null)}>Cancel</button>
          </div>
          <div className="mt-2">
            <QuestionForm key={editing.id} initial={editing} onSubmit={update} busy={busy} submitLabel="Save changes" />
          </div>
        </div>
      )}

      {showForm && !editing && (
        <div className="card mb-3">
          <h3>New {tab === 'EXAM' ? 'exam' : 'practice'} question</h3>
          <QuestionForm initial={{ category: tab }} onSubmit={create} busy={busy} submitLabel="Add question" />
        </div>
      )}

      {questions.map((qn, idx) => (
        <div key={qn.id} className="card mb-2">
          <div className="row-between">
            <h4 style={{ margin: 0 }}>Q{idx + 1}. {qn.text}</h4>
            <div className="row" style={{ gap: 6 }}>
              <span className="badge">{qn.category === 'EXAM' ? 'Exam' : 'Practice'}</span>
              <span className={`badge ${qn.status === 'APPROVED' ? 'badge-green' : qn.status === 'PENDING' ? 'badge-amber' : 'badge-red'}`}>{qn.status}</span>
              <button className="btn btn-sm btn-ghost" onClick={() => startEdit(qn)}>Edit</button>
              <button className="btn btn-sm btn-danger" onClick={() => remove(qn.id)}>Delete</button>
            </div>
          </div>
          <div className="mt-2">
            {qn.options.map((o, i) => (
              <div key={o.id} style={{ color: o.isCorrect ? 'var(--green)' : 'var(--muted)', fontWeight: o.isCorrect ? 600 : 400 }}>
                {LETTERS[i]}. {o.text} {o.isCorrect && '✓'}
              </div>
            ))}
          </div>
          {qn.explanation && <p className="muted mt-2" style={{ marginBottom: 0 }}><b>Explanation:</b> {qn.explanation}</p>}
          {qn.createdBy && <p className="muted" style={{ fontSize: '0.82rem', marginBottom: 0 }}>Added by {qn.createdBy.name}</p>}
        </div>
      ))}
      {questions.length === 0 && <div className="card muted">No {tab === 'EXAM' ? 'exam' : 'practice'} questions yet. Add one above or import a CSV/Excel file.</div>}
    </div>
  );
}
