import { useEffect, useState } from 'react';
import { Link, useParams, useNavigate } 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';

export default function SubmitQuestion() {
  const { slug } = useParams();
  const toast = useToast();
  const navigate = useNavigate();
  const [course, setCourse] = useState(null);
  const [error, setError] = useState('');
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    api.get(`/courses/${slug}`).then(({ data }) => setCourse(data.course)).catch((e) => setError(e.message));
  }, [slug]);

  const submit = async (payload) => {
    setBusy(true);
    try {
      await api.post('/questions/submit', { courseId: course.id, ...payload });
      toast.success('Question submitted! An admin will review it shortly.');
      navigate(`/courses/${slug}`);
    } catch (e) {
      toast.error(e.message);
    } finally {
      setBusy(false);
    }
  };

  if (error) return <div className="container page"><div className="alert alert-error">{error}</div></div>;
  if (!course) return <Spinner />;

  return (
    <div className="container page" style={{ maxWidth: 720 }}>
      <Link to={`/courses/${slug}`} className="muted">← {course.title}</Link>
      <h1 className="mt-2">Contribute a question</h1>
      <p className="muted">
        Help others learn. Your question for <b>{course.title}</b> will be reviewed by an admin before it
        appears in the exam.
      </p>
      <div className="card mt-2">
        <QuestionForm onSubmit={submit} submitLabel="Submit for review" busy={busy} showCategory={false} />
      </div>
    </div>
  );
}
