import { AppLayout } from '@/Components/Layout/AppLayout';

type Option = { id: number; body: string; isCorrect: boolean };

type QuestionResult = {
  id: number;
  type: 'test' | 'descriptive' | 'file';
  body: string;
  score: number;
  imagePath: string | null;
  options: Option[];
  // MCQ
  studentOptionId?: number | null;
  correctOptionId?: number | null;
  isCorrect?: boolean;
  // descriptive
  studentText?: string | null;
  hasFile?: boolean;
  earnedScore: number | null;
  status: 'graded' | 'pending';
};

type Props = {
  exam: { id: number; title: string; maxScore: number; type: string };
  session: { score: number | null; status: string; submittedAt: string | null };
  results: QuestionResult[];
  studentName: string;
};

const statusColors = { correct: '#16a34a', wrong: '#dc2626', pending: '#d97706' };

export default function ExamResult({ exam, session, results, studentName }: Props) {
  const mcqTotal = results.filter((r) => r.type === 'test').length;
  const mcqCorrect = results.filter((r) => r.type === 'test' && r.isCorrect).length;
  const mcqWrong = results.filter((r) => r.type === 'test' && !r.isCorrect && r.studentOptionId !== null).length;
  const descriptivePending = results.filter((r) => r.type !== 'test' && r.status === 'pending').length;
  const scorePct = session.score !== null && exam.maxScore > 0
    ? Math.round((session.score / exam.maxScore) * 100)
    : null;

  return (
    <AppLayout title={`نتیجه: ${exam.title}`}>
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>
              <i className="bi bi-clipboard2-check" style={{ marginLeft: '0.5rem', color: 'var(--color-primary)' }} />
              نتیجه امتحان
            </h2>
            <p style={{ fontSize: '0.875rem', color: 'var(--color-text-muted)' }}>
              {exam.title} · {studentName}
              {session.submittedAt && <> · ارسال‌شده: {session.submittedAt}</>}
            </p>
          </div>
          <a href="/student/exams" className="btn btn-ghost btn-sm">
            <i className="bi bi-arrow-right" /> بازگشت به امتحانات
          </a>
        </section>

        {/* Score summary */}
        <div className="dashboard-grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))' }}>
          {session.score !== null && (
            <div className="panel-card" style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '2rem', fontWeight: 800, color: scorePct !== null && scorePct >= 50 ? '#16a34a' : '#dc2626' }}>
                {session.score.toFixed(1)}
              </div>
              <div style={{ fontSize: '0.8rem', color: 'var(--color-text-muted)' }}>از {exam.maxScore}</div>
              {scorePct !== null && (
                <div style={{ fontSize: '0.85rem', fontWeight: 600, color: scorePct >= 50 ? '#16a34a' : '#dc2626' }}>
                  {scorePct}%
                </div>
              )}
              <div style={{ fontSize: '0.75rem', color: 'var(--color-text-muted)' }}>نمره کل</div>
            </div>
          )}
          {mcqTotal > 0 && (
            <>
              <div className="panel-card" style={{ textAlign: 'center' }}>
                <div style={{ fontSize: '1.6rem', fontWeight: 700, color: '#16a34a' }}>{mcqCorrect}</div>
                <div style={{ fontSize: '0.8rem', color: 'var(--color-text-muted)' }}>صحیح از {mcqTotal}</div>
              </div>
              <div className="panel-card" style={{ textAlign: 'center' }}>
                <div style={{ fontSize: '1.6rem', fontWeight: 700, color: '#dc2626' }}>{mcqWrong}</div>
                <div style={{ fontSize: '0.8rem', color: 'var(--color-text-muted)' }}>اشتباه</div>
              </div>
            </>
          )}
          {descriptivePending > 0 && (
            <div className="panel-card" style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '1.6rem', fontWeight: 700, color: '#d97706' }}>{descriptivePending}</div>
              <div style={{ fontSize: '0.8rem', color: 'var(--color-text-muted)' }}>در انتظار تصحیح</div>
            </div>
          )}
        </div>

        {descriptivePending > 0 && (
          <div style={{ background: '#d97706' + '15', border: '1px solid #d9770630', borderRadius: 'var(--radius-md)', padding: '0.75rem 1rem', display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
            <i className="bi bi-clock-history" style={{ color: '#d97706', fontSize: '1.1rem' }} />
            <span style={{ fontSize: '0.875rem' }}>
              {descriptivePending} سوال تشریحی در انتظار تصحیح معلم است. نمره نهایی پس از بررسی معلم به‌روز می‌شود.
            </span>
          </div>
        )}

        {/* Per-question results */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
          {results.map((q, idx) => (
            <QuestionCard key={q.id} q={q} idx={idx} />
          ))}
        </div>
      </div>
    </AppLayout>
  );
}

function QuestionCard({ q, idx }: { q: QuestionResult; idx: number }) {
  if (q.type === 'test') {
    const isCorrect = q.isCorrect;
    const borderColor = isCorrect ? '#16a34a' : q.studentOptionId ? '#dc2626' : '#d97706';
    const bgColor = isCorrect ? '#16a34a' + '08' : q.studentOptionId ? '#dc2626' + '08' : '#d97706' + '08';

    return (
      <div className="panel-card" style={{ border: `1.5px solid ${borderColor}`, background: bgColor }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '0.5rem' }}>
          <span style={{ fontSize: '0.78rem', color: 'var(--color-text-muted)', fontWeight: 600 }}>
            سوال {idx + 1} · چهارگزینه‌ای · {q.score} نمره
          </span>
          <span style={{ fontSize: '0.78rem', fontWeight: 700, color: borderColor }}>
            {isCorrect
              ? <><i className="bi bi-check-circle-fill" /> صحیح (+{q.score})</>
              : q.studentOptionId
                ? <><i className="bi bi-x-circle-fill" /> اشتباه (۰)</>
                : <><i className="bi bi-dash-circle" /> پاسخ داده نشد</>}
          </span>
        </div>
        {q.imagePath && <img src={`/storage/${q.imagePath}`} alt="" style={{ maxWidth: 300, borderRadius: 'var(--radius-sm)', marginBottom: '0.5rem' }} />}
        <p style={{ fontSize: '0.9rem', marginBottom: '0.75rem', fontWeight: 500 }}>{q.body}</p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: '0.35rem' }}>
          {q.options.map((opt) => {
            const isStudentAnswer = opt.id === q.studentOptionId;
            const isCorrectAnswer = opt.id === q.correctOptionId;
            let bg = 'transparent';
            let border = '1px solid var(--color-border)';
            let icon = null;
            if (isCorrectAnswer && isStudentAnswer) {
              bg = '#16a34a18'; border = '1.5px solid #16a34a';
              icon = <i className="bi bi-check-circle-fill" style={{ color: '#16a34a', marginLeft: '0.4rem' }} />;
            } else if (isStudentAnswer && !isCorrectAnswer) {
              bg = '#dc262618'; border = '1.5px solid #dc2626';
              icon = <i className="bi bi-x-circle-fill" style={{ color: '#dc2626', marginLeft: '0.4rem' }} />;
            } else if (isCorrectAnswer) {
              bg = '#16a34a08'; border = '1.5px solid #16a34a80';
              icon = <i className="bi bi-check-circle" style={{ color: '#16a34a', marginLeft: '0.4rem' }} />;
            }
            return (
              <div key={opt.id} style={{ background: bg, border, borderRadius: 'var(--radius-sm)', padding: '0.4rem 0.7rem', fontSize: '0.875rem', display: 'flex', alignItems: 'center' }}>
                {icon}{opt.body}
              </div>
            );
          })}
        </div>
      </div>
    );
  }

  // Descriptive / file
  const isPending = q.status === 'pending';
  return (
    <div className="panel-card" style={{ border: `1.5px solid ${isPending ? '#d97706' : 'var(--color-border)'}` }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '0.5rem' }}>
        <span style={{ fontSize: '0.78rem', color: 'var(--color-text-muted)', fontWeight: 600 }}>
          سوال {idx + 1} · {q.type === 'file' ? 'فایل' : 'تشریحی'} · {q.score} نمره
        </span>
        <span style={{ fontSize: '0.78rem', fontWeight: 700, color: isPending ? '#d97706' : '#16a34a' }}>
          {isPending
            ? <><i className="bi bi-hourglass-split" /> در انتظار تصحیح</>
            : <><i className="bi bi-check-circle-fill" /> {q.earnedScore ?? 0} از {q.score}</>}
        </span>
      </div>
      <p style={{ fontSize: '0.9rem', marginBottom: '0.5rem', fontWeight: 500 }}>{q.body}</p>
      {q.studentText && (
        <div style={{ background: 'var(--color-bg-subtle)', borderRadius: 'var(--radius-sm)', padding: '0.5rem 0.75rem', fontSize: '0.85rem', color: 'var(--color-text-muted)', fontStyle: 'italic' }}>
          پاسخ شما: {q.studentText}
        </div>
      )}
      {q.hasFile && !q.studentText && (
        <div style={{ fontSize: '0.85rem', color: 'var(--color-text-muted)' }}>
          <i className="bi bi-paperclip" style={{ marginLeft: '0.25rem' }} />
          فایل ارسال شد
        </div>
      )}
      {!q.studentText && !q.hasFile && (
        <div style={{ fontSize: '0.85rem', color: '#dc2626' }}>پاسخی ارسال نشد</div>
      )}
    </div>
  );
}
