import { useEffect, useRef, useState } from 'react';
import { router } from '@inertiajs/react';
import { AppLayout } from '@/Components/Layout/AppLayout';

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

type Question = {
  id: number;
  type: 'test' | 'descriptive' | 'file';
  body: string;
  score: number;
  options: Option[];
  savedOptionId: number | null;
  savedText: string | null;
};

type ExamMeta = {
  id: number;
  title: string;
  maxScore: number;
  durationMinutes: number | null;
};

type Props = {
  exam: ExamMeta;
  sessionId: number;
  questions: Question[];
  remainingSeconds: number | null;
};

function formatTime(secs: number): string {
  const h = Math.floor(secs / 3600);
  const m = Math.floor((secs % 3600) / 60);
  const s = secs % 60;
  if (h > 0) return `${h}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  return `${m}:${String(s).padStart(2, '0')}`;
}

export default function TakeExam({ exam, sessionId, questions, remainingSeconds }: Props) {
  const [answers, setAnswers] = useState<Record<number, { optionId?: number; text?: string }>>(() => {
    const init: Record<number, { optionId?: number; text?: string }> = {};
    for (const q of questions) {
      init[q.id] = { optionId: q.savedOptionId ?? undefined, text: q.savedText ?? undefined };
    }
    return init;
  });

  const [timeLeft, setTimeLeft] = useState<number | null>(remainingSeconds);
  const [submitting, setSubmitting] = useState(false);
  const saveQueueRef = useRef<Record<number, ReturnType<typeof setTimeout>>>({});

  useEffect(() => {
    if (timeLeft === null || timeLeft <= 0) return;
    const timer = setInterval(() => {
      setTimeLeft((prev) => {
        if (prev === null || prev <= 1) {
          clearInterval(timer);
          handleSubmit();
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
    return () => clearInterval(timer);
  }, []);

  function autoSave(questionId: number, payload: { optionId?: number; text?: string }) {
    if (saveQueueRef.current[questionId]) {
      clearTimeout(saveQueueRef.current[questionId]);
    }
    saveQueueRef.current[questionId] = setTimeout(() => {
      fetch(`/student/exams/${exam.id}/answer`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-Requested-With': 'XMLHttpRequest',
          'X-XSRF-TOKEN': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1] ?? ''),
        },
        body: JSON.stringify({
          session_id: sessionId,
          question_id: questionId,
          option_id: payload.optionId ?? null,
          answer_text: payload.text ?? null,
        }),
      }).catch(() => {});
    }, 600);
  }

  function setOption(questionId: number, optionId: number) {
    setAnswers((prev) => {
      const next = { ...prev, [questionId]: { ...prev[questionId], optionId } };
      autoSave(questionId, { optionId });
      return next;
    });
  }

  function setText(questionId: number, text: string) {
    setAnswers((prev) => {
      const next = { ...prev, [questionId]: { ...prev[questionId], text } };
      autoSave(questionId, { text });
      return next;
    });
  }

  function handleSubmit() {
    if (submitting) return;
    setSubmitting(true);
    router.post(
      `/student/exams/${exam.id}/submit`,
      { session_id: sessionId },
      { onError: () => setSubmitting(false) }
    );
  }

  const answeredCount = questions.filter((q) => {
    const a = answers[q.id];
    return q.type === 'test' ? a?.optionId : (a?.text?.trim() ?? '').length > 0;
  }).length;

  const urgent = timeLeft !== null && timeLeft < 300;

  return (
    <AppLayout title={`امتحان: ${exam.title}`}>
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2><i className="bi bi-pencil-square" style={{ marginLeft: '0.5rem', color: 'var(--color-primary)' }} />{exam.title}</h2>
            <p>پاسخ‌ها به‌صورت خودکار ذخیره می‌شوند.</p>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: '0.25rem' }}>
            {timeLeft !== null && (
              <span
                className={`status-pill ${urgent ? 'warning' : 'success'}`}
                style={{ fontVariantNumeric: 'tabular-nums', direction: 'ltr' }}
              >
                <i className="bi bi-stopwatch" /> {formatTime(timeLeft)}
              </span>
            )}
            <span style={{ fontSize: '0.8rem', color: 'var(--color-text-muted)' }}>
              {answeredCount} از {questions.length} پاسخ داده شد
            </span>
          </div>
        </section>

        <div
          style={{
            height: 6,
            background: 'var(--color-border)',
            borderRadius: 99,
            overflow: 'hidden',
            position: 'sticky',
            top: 64,
            zIndex: 10,
          }}
        >
          <div
            style={{
              height: '100%',
              width: `${questions.length > 0 ? (answeredCount / questions.length) * 100 : 0}%`,
              background: 'var(--color-primary)',
              borderRadius: 99,
              transition: 'width 0.3s',
            }}
          />
        </div>

        {questions.length === 0 ? (
          <section className="panel-card">
            <p style={{ textAlign: 'center', color: 'var(--color-text-muted)' }}>
              این امتحان هنوز سوالی ندارد.
            </p>
          </section>
        ) : (
          questions.map((q, idx) => (
            <section key={q.id} className="panel-card">
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '0.75rem' }}>
                <h3 style={{ margin: 0, fontSize: '1rem' }}>سوال {idx + 1}</h3>
                <span style={{ fontSize: '0.8rem', color: 'var(--color-text-muted)', background: 'var(--color-bg-muted)', padding: '0.15rem 0.5rem', borderRadius: 'var(--radius-sm)' }}>
                  {q.score} نمره
                </span>
              </div>

              <p style={{ margin: '0 0 1rem', lineHeight: 1.7 }}>{q.body}</p>

              {q.type === 'test' && (
                <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
                  {q.options.map((opt) => {
                    const selected = answers[q.id]?.optionId === opt.id;
                    return (
                      <li key={opt.id}>
                        <label
                          style={{
                            display: 'flex',
                            alignItems: 'center',
                            gap: '0.75rem',
                            padding: '0.6rem 0.9rem',
                            borderRadius: 'var(--radius-sm)',
                            border: `1px solid ${selected ? 'var(--color-primary)' : 'var(--color-border)'}`,
                            background: selected ? 'var(--color-primary-soft)' : 'var(--color-bg)',
                            cursor: 'pointer',
                            transition: 'all 0.15s',
                          }}
                        >
                          <input
                            type="radio"
                            name={`q-${q.id}`}
                            checked={selected}
                            onChange={() => setOption(q.id, opt.id)}
                            style={{ accentColor: 'var(--color-primary)', flexShrink: 0 }}
                          />
                          <span>{opt.body}</span>
                        </label>
                      </li>
                    );
                  })}
                </ul>
              )}

              {q.type === 'descriptive' && (
                <textarea
                  className="form-control"
                  rows={4}
                  placeholder="پاسخ خود را اینجا بنویسید..."
                  value={answers[q.id]?.text ?? ''}
                  onChange={(e) => setText(q.id, e.target.value)}
                  maxLength={5000}
                />
              )}

              {q.type === 'file' && (
                <div
                  style={{
                    padding: '1rem',
                    background: 'var(--color-bg-muted)',
                    borderRadius: 'var(--radius-sm)',
                    color: 'var(--color-text-muted)',
                    fontSize: '0.875rem',
                    textAlign: 'center',
                  }}
                >
                  <i className="bi bi-paperclip" style={{ marginLeft: '0.3rem' }} />
                  ارسال فایل برای این سوال از طریق پانل فعلی در دسترس نیست؛ با معلم هماهنگ کنید.
                </div>
              )}

              {answers[q.id]?.optionId || (answers[q.id]?.text?.trim() ?? '').length > 0 ? (
                <div style={{ marginTop: '0.5rem', fontSize: '0.78rem', color: 'var(--color-primary-active)', display: 'flex', alignItems: 'center', gap: '0.3rem' }}>
                  <i className="bi bi-cloud-check" /> ذخیره شد
                </div>
              ) : null}
            </section>
          ))
        )}

        <section className="panel-card" style={{ position: 'sticky', bottom: '1rem' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '0.75rem' }}>
            <span style={{ color: 'var(--color-text-muted)', fontSize: '0.875rem' }}>
              <i className="bi bi-info-circle" style={{ marginLeft: '0.3rem' }} />
              پس از ارسال، امکان ویرایش وجود ندارد.
            </span>
            <button
              className="btn btn-primary"
              onClick={handleSubmit}
              disabled={submitting}
              style={{ minWidth: 140 }}
            >
              {submitting
                ? <><i className="bi bi-hourglass-split" /> در حال ارسال...</>
                : <><i className="bi bi-send-check" /> ثبت نهایی پاسخ‌ها</>
              }
            </button>
          </div>
        </section>
      </div>
    </AppLayout>
  );
}
