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

// Standalone contribution: pick any published exam (grouped by vendor), then add a
// question + options under the Practice or Exam bank. Goes to admin approval.
export default function Contribute() {
  const toast = useToast();
  const [courses, setCourses] = useState(null);
  const [courseId, setCourseId] = useState('');
  const [busy, setBusy] = useState(false);
  const [formKey, setFormKey] = useState(0); // bump to remount QuestionForm with a fresh, empty form

  useEffect(() => {
    api.get('/courses')
      .then(({ data }) => setCourses(data.courses))
      .catch((e) => { toast.error(e.message); setCourses([]); });
  }, [toast]);

  const submit = async (payload) => {
    if (!courseId) return toast.error('Choose an exam first.');
    setBusy(true);
    try {
      await api.post('/questions/submit', { courseId, ...payload });
      toast.success('Question submitted! An admin will review it. Add another below.');
      setFormKey((k) => k + 1); // reset the form so a new question can be added
    } catch (e) {
      toast.error(e.message);
    } finally {
      setBusy(false);
    }
  };

  if (!courses) return <Spinner />;

  // Group exam options by vendor name for a tidy dropdown.
  const byVendor = courses.reduce((acc, c) => {
    const v = c.vendor?.name || 'Other';
    (acc[v] = acc[v] || []).push(c);
    return acc;
  }, {});

  return (
    <div className="container page" style={{ maxWidth: 720 }}>
      <h1>Contribute a question</h1>
      <p className="muted">
        Help others learn. Pick the exam and add your question — an admin will review it and decide
        which bank it goes into before it appears.
      </p>

      <div className="card mt-2">
        <div className="field">
          <label className="label">Exam</label>
          <select className="select" value={courseId} onChange={(e) => setCourseId(e.target.value)} required>
            <option value="">Select an exam…</option>
            {Object.entries(byVendor).map(([vendor, list]) => (
              <optgroup key={vendor} label={vendor}>
                {list.map((c) => (
                  <option key={c.id} value={c.id}>{c.title}{c.code ? ` (${c.code})` : ''}</option>
                ))}
              </optgroup>
            ))}
          </select>
          {courses.length === 0 && (
            <span className="muted" style={{ fontSize: '0.82rem' }}>
              No exams available yet. <Link to="/vendors">Browse vendors</Link>
            </span>
          )}
        </div>

        <QuestionForm key={formKey} onSubmit={submit} submitLabel="Submit for review" busy={busy} showCategory={false} />
      </div>
    </div>
  );
}
