import { useEffect, useState } from 'react';
import { Link, useParams } from 'react-router-dom';
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', 'G', 'H'];

export default function Result() {
  const { attemptId } = useParams();
  const toast = useToast();
  const [result, setResult] = useState(null);
  const [error, setError] = useState('');
  const [ai, setAi] = useState({});
  const [aiBusy, setAiBusy] = useState(null);

  useEffect(() => {
    api.get(`/attempts/${attemptId}/result`)
      .then(({ data }) => setResult(data.result))
      .catch((e) => setError(e.message));
  }, [attemptId]);

  const explainAi = async (questionId) => {
    if (ai[questionId]) return;
    setAiBusy(questionId);
    try {
      const { data } = await api.post('/ai/explain', { questionId });
      setAi((prev) => ({ ...prev, [questionId]: data.explanation }));
    } catch (e) {
      toast.error(e.message);
    } finally {
      setAiBusy(null);
    }
  };

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

  const pct = result.total ? Math.round((result.score / result.total) * 100) : 0;
  const passed = pct >= 70;

  return (
    <div className="container page" style={{ maxWidth: 820 }}>
      <div className="card center">
        <span className={`badge ${passed ? 'badge-green' : 'badge-red'}`}>{passed ? 'Passed' : 'Keep practicing'}</span>
        <h1 className="mt-2" style={{ fontSize: '3rem', color: passed ? 'var(--green)' : 'var(--red)' }}>{pct}%</h1>
        <p className="muted">You scored <b>{result.score}</b> out of <b>{result.total}</b> on {result.course.title}</p>
        <div className="progress" style={{ maxWidth: 360, margin: '12px auto' }}>
          <span style={{ width: `${pct}%`, background: passed ? 'var(--green)' : 'var(--red)' }} />
        </div>
        <div className="row center mt-2 wrap" style={{ justifyContent: 'center' }}>
          <Link to={`/courses/${result.course.slug}`} className="btn">Retake</Link>
          <Link to="/dashboard" className="btn btn-ghost">My exams</Link>
        </div>
      </div>

      <h2 className="mt-4">Review</h2>
      {result.review.map((r, idx) => (
        <div key={r.questionId} className="card mt-2">
          <div className="row-between">
            <h3 style={{ margin: 0 }}>Q{idx + 1}. {r.text}</h3>
            <span className={`badge ${r.isCorrect ? 'badge-green' : 'badge-red'}`}>{r.isCorrect ? 'Correct' : 'Wrong'}</span>
          </div>
          <div className="mt-2">
            {r.options.map((opt, i) => {
              const picked = r.selectedOptionIds.includes(opt.id);
              let cls = 'option';
              if (opt.isCorrect) cls += ' correct';
              else if (picked) cls += ' incorrect';
              return (
                <div key={opt.id} className={cls} style={{ cursor: 'default' }}>
                  <div className="option-marker">{LETTERS[i]}</div>
                  <div>
                    {opt.text}
                    {opt.isCorrect && <span className="badge badge-green" style={{ marginLeft: 8 }}>Correct</span>}
                    {picked && !opt.isCorrect && <span className="badge badge-red" style={{ marginLeft: 8 }}>Your answer</span>}
                  </div>
                </div>
              );
            })}
          </div>
          {r.explanation && (
            <div className="explain-box"><b>Explanation</b><p style={{ margin: '6px 0 0' }}>{r.explanation}</p></div>
          )}
          <button className="btn btn-sm btn-ghost mt-2" onClick={() => explainAi(r.questionId)} disabled={aiBusy === r.questionId || !!ai[r.questionId]}>
            {aiBusy === r.questionId ? 'Thinking…' : ai[r.questionId] ? 'AI explained ✓' : '🤖 Explain with AI'}
          </button>
          {ai[r.questionId] && (
            <div className="explain-box" style={{ background: 'var(--blue-50)' }}>
              <b>AI explanation</b>
              <p style={{ margin: '6px 0 0', whiteSpace: 'pre-wrap' }}>{ai[r.questionId]}</p>
            </div>
          )}
        </div>
      ))}
    </div>
  );
}
