import { useEffect, useState, useCallback } from 'react';
import { Link, useParams, useNavigate, useSearchParams } from 'react-router-dom';
import api from '../api/client.js';
import Spinner from '../components/Spinner.jsx';
import { useAuth } from '../context/AuthContext.jsx';
import { useToast } from '../context/ToastContext.jsx';

export default function CourseDetail() {
  const { slug } = useParams();
  const { isAuthenticated } = useAuth();
  const toast = useToast();
  const navigate = useNavigate();
  const [params, setParams] = useSearchParams();

  const [course, setCourse] = useState(null);
  const [error, setError] = useState('');
  const [buying, setBuying] = useState(false);
  const [payCfg, setPayCfg] = useState({ stripeConfigured: true, devUnlock: false });

  useEffect(() => {
    api.get('/payments/config').then(({ data }) => setPayCfg(data)).catch(() => {});
  }, []);

  const load = useCallback(async () => {
    try {
      const { data } = await api.get(`/courses/${slug}`);
      setCourse(data.course);
    } catch (e) {
      setError(e.message);
    }
  }, [slug]);

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

  // Handle Stripe redirect (?payment=success&session_id=...)
  useEffect(() => {
    const payment = params.get('payment');
    if (payment === 'success') {
      const sessionId = params.get('session_id');
      setParams({}, { replace: true });
      (async () => {
        // Confirm the session server-side (covers local dev with no webhook).
        if (sessionId) {
          try {
            await api.post('/payments/confirm', { sessionId });
          } catch {
            /* webhook may have already marked it paid */
          }
        }
        toast.success('Payment successful — full exam unlocked!');
        load();
      })();
    } else if (payment === 'cancelled') {
      toast.info('Payment cancelled.');
      setParams({}, { replace: true });
    }
  }, [params, setParams, toast, load]);

  const start = (mode) => {
    if (!isAuthenticated) {
      navigate('/login', { state: { from: `/courses/${slug}` } });
      return;
    }
    navigate(`/exam/${slug}?mode=${mode}`);
  };

  const buy = async () => {
    if (!isAuthenticated) {
      navigate('/login', { state: { from: `/courses/${slug}` } });
      return;
    }
    setBuying(true);
    try {
      if (payCfg.devUnlock) {
        // Local testing without Stripe keys
        await api.post('/payments/dev-grant', { courseId: course.id });
        toast.success('Full access unlocked (test mode)');
        await load();
        setBuying(false);
        return;
      }
      const { data } = await api.post('/payments/checkout', { courseId: course.id });
      window.location.href = data.url; // redirect to Stripe Checkout
    } catch (e) {
      toast.error(e.message);
      setBuying(false);
    }
  };

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

  const isFree = course.isFree || course.priceCents === 0;
  const priceLabel = isFree ? 'Free' : `$${(course.priceCents / 100).toFixed(2)}`;

  return (
    <div className="container page" style={{ maxWidth: 820 }}>
      <Link to={`/vendors/${course.vendor.slug}`} className="muted">← {course.vendor.name}</Link>

      <div className="card mt-2">
        <div className="row-between wrap">
          <div>
            {course.code && <span className="badge">{course.code}</span>}
            <h1 className="mt-2" style={{ marginBottom: 4 }}>{course.title}</h1>
            <p className="muted" style={{ margin: 0 }}>{course.vendor.name}</p>
          </div>
          <span className={`badge ${isFree ? 'badge-free' : ''}`} style={{ fontSize: '0.95rem' }}>{priceLabel}</span>
        </div>

        {course.description && <p className="mt-3">{course.description}</p>}

        <div className="row mt-2 wrap">
          <div className="stat"><div className="num">{course.totalQuestions}</div><div className="lbl">Questions</div></div>
          <div className="stat"><div className="num">{isFree ? '∞' : course.freeQuestionLimit}</div><div className="lbl">{isFree ? 'Full access' : 'Free preview'}</div></div>
          <div className="stat"><div className="num">{course.hasAccess ? '✓' : '🔒'}</div><div className="lbl">{course.hasAccess ? 'Unlocked' : 'Locked'}</div></div>
        </div>

        {!course.hasAccess && !isFree && (
          <div className="alert alert-info mt-3">
            You can try the first <b>{course.freeQuestionLimit} questions</b> for free. Unlock the full
            exam ({course.totalQuestions} questions) for <b>{priceLabel}</b>.
          </div>
        )}

        <div className="row mt-3 wrap">
          <button className="btn btn-lg" onClick={() => start('PRACTICE')}>
            🎯 Practice mode
          </button>
          <button className="btn btn-lg btn-ghost" onClick={() => start('EXAM')}>
            ⏱️ Exam mode
          </button>
          {!course.hasAccess && !isFree && (
            <button className="btn btn-lg btn-success" onClick={buy} disabled={buying}>
              {buying
                ? 'Working…'
                : payCfg.devUnlock
                ? '🔓 Unlock full exam (test mode)'
                : `🔓 Unlock full exam — ${priceLabel}`}
            </button>
          )}
        </div>

        <div className="mt-3">
          <Link to={`/courses/${slug}/contribute`} className="muted">
            + Contribute a question to this exam
          </Link>
        </div>
      </div>

      <div className="card mt-3">
        <h3>How it works</h3>
        <p className="muted" style={{ marginBottom: 8 }}>
          <b>Practice mode:</b> the correct answer and explanation appear immediately after each question.
        </p>
        <p className="muted" style={{ marginBottom: 0 }}>
          <b>Exam mode:</b> answers are hidden until you finish all questions — then you get your score and a
          full solution review. Copy-paste, screenshots and tab-switching are restricted.
        </p>
      </div>
    </div>
  );
}
