import { useEffect, useState } from 'react';
import api from '../../api/client.js';
import Spinner from '../../components/Spinner.jsx';
import { useToast } from '../../context/ToastContext.jsx';

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

export default function AdminApprovals() {
  const toast = useToast();
  const [questions, setQuestions] = useState(null);
  // Admin's chosen target bank per question (defaults to the user's selection on load).
  const [targets, setTargets] = useState({});

  const load = () =>
    api.get('/questions/pending').then(({ data }) => {
      setQuestions(data.questions);
      setTargets(Object.fromEntries(data.questions.map((q) => [q.id, q.category])));
    });
  useEffect(() => { load(); }, []);

  const approve = async (q) => {
    try {
      await api.post(`/questions/${q.id}/approve`, { category: targets[q.id] || q.category });
      const where = targets[q.id] === 'BOTH' ? 'Practice + Exam' : targets[q.id] === 'EXAM' ? 'Exam' : 'Practice';
      toast.success(`Question approved into ${where}`);
      setQuestions((qs) => qs.filter((x) => x.id !== q.id));
    } catch (e) {
      toast.error(e.message);
    }
  };

  const reject = async (id) => {
    try {
      await api.post(`/questions/${id}/reject`);
      toast.success('Question rejected');
      setQuestions((qs) => qs.filter((x) => x.id !== id));
    } catch (e) {
      toast.error(e.message);
    }
  };

  if (!questions) return <Spinner />;

  return (
    <div>
      <h2>Pending submissions <span className="muted">({questions.length})</span></h2>
      <p className="muted">Questions submitted by users. Choose which bank to publish them into, then approve.</p>

      {questions.length === 0 && <div className="card muted">Nothing to review. All caught up! 🎉</div>}

      {questions.map((q) => (
        <div key={q.id} className="card mb-2">
          <div className="row-between wrap">
            <span className="badge">{q.course.vendor.name} — {q.course.title}</span>
            <span className="badge badge-amber" style={{ marginLeft: 6 }}>
              suggested: {q.category === 'EXAM' ? 'Exam' : 'Practice'}
            </span>
            <span className="muted" style={{ fontSize: '0.85rem' }}>by {q.createdBy?.name || 'user'} ({q.createdBy?.email})</span>
          </div>
          <h4 className="mt-2">{q.text}</h4>
          <div className="mt-2">
            {q.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 && '✓ correct'}
              </div>
            ))}
          </div>
          {q.explanation && <p className="muted mt-2"><b>Explanation:</b> {q.explanation}</p>}

          <div className="row wrap mt-3" style={{ alignItems: 'center', gap: 10 }}>
            <label className="muted" style={{ fontSize: '0.85rem' }}>Add to bank:</label>
            <select
              className="select"
              style={{ width: 'auto' }}
              value={targets[q.id] || q.category}
              onChange={(e) => setTargets((t) => ({ ...t, [q.id]: e.target.value }))}
            >
              <option value="PRACTICE">Practice</option>
              <option value="EXAM">Exam</option>
              <option value="BOTH">Both (Practice + Exam)</option>
            </select>
            <button className="btn btn-success btn-sm" onClick={() => approve(q)}>✓ Approve</button>
            <button className="btn btn-danger btn-sm" onClick={() => reject(q.id)}>✕ Reject</button>
          </div>
        </div>
      ))}
    </div>
  );
}
