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

type ExamSettings = {
  randomizeQuestions: boolean;
  shuffleOptions: boolean;
  timeMode: 'full' | 'per_question';
  timePerQuestionSeconds: number | null;
};

type ExamOption = { id: number; body: string; isCorrect: boolean; imagePath: string | null };

type Question = {
  id: number;
  type: 'test' | 'descriptive' | 'file';
  body: string;
  score: number;
  sortOrder: number;
  imagePath: string | null;
  allowFileUpload: boolean;
  options: ExamOption[];
};

type ExamMeta = {
  id: number;
  title: string;
  status: string;
  type: string;
  settings: ExamSettings;
};

type Props = {
  exam: ExamMeta;
  questions: Question[];
};

const typeLabel: { [key: string]: string } = {
  test: 'تستی',
  descriptive: 'تشریحی',
  file: 'آپلود فایل',
};

const statusLabel: { [key: string]: { label: string; cls: string } } = {
  draft: { label: 'پیش‌نویس', cls: 'badge badge-secondary' },
  published: { label: 'منتشر', cls: 'badge badge-success' },
  archived: { label: 'آرشیو', cls: 'badge badge-secondary' },
};

const EMPTY_OPTION = { body: '', isCorrect: false, imagePath: null as string | null };

export default function TeacherExamQuestions({ exam, questions }: Props) {
  const [showForm, setShowForm] = useState(false);
  const [showSettings, setShowSettings] = useState(false);
  const [qType, setQType] = useState<'test' | 'descriptive' | 'file'>('test');
  const [body, setBody] = useState('');
  const [score, setScore] = useState('1');
  const [allowFileUpload, setAllowFileUpload] = useState(false);
  const [questionImage, setQuestionImage] = useState<string | null>(null);
  const [options, setOptions] = useState([{ ...EMPTY_OPTION }, { ...EMPTY_OPTION }, { ...EMPTY_OPTION }, { ...EMPTY_OPTION }]);
  const [settings, setSettings] = useState<ExamSettings>(exam.settings);
  const isPublished = exam.status === 'published';
  const imageInputRef = useRef<HTMLInputElement | null>(null);
  const imageTargetRef = useRef<'question' | number | null>(null);

  function csrfToken(): string {
    return document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '';
  }

  function uploadImage(target: 'question' | number) {
    imageTargetRef.current = target;
    imageInputRef.current?.click();
  }

  function onImageChange(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file || imageTargetRef.current === null) return;
    const formData = new FormData();
    formData.append('image', file);

    fetch(`/teacher/exams/${exam.id}/questions/upload-image`, {
      method: 'POST',
      headers: { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN': csrfToken() },
      body: formData,
    })
      .then((res) => res.json())
      .then((data) => {
        if (data.path) {
          if (imageTargetRef.current === 'question') {
            setQuestionImage(data.path);
          } else {
            const optIdx = imageTargetRef.current;
            setOptions((prev) => prev.map((o, i) => (i === optIdx ? { ...o, imagePath: data.path } : o)));
          }
        }
      })
      .catch(() => {})
      .finally(() => {
        if (imageInputRef.current) imageInputRef.current.value = '';
        imageTargetRef.current = null;
      });
  }

  function saveSettings() {
    router.put(`/teacher/exams/${exam.id}/settings`, {
      randomize_questions: settings.randomizeQuestions,
      shuffle_options: settings.shuffleOptions,
      time_mode: settings.timeMode,
      time_per_question_seconds: settings.timePerQuestionSeconds ? Number(settings.timePerQuestionSeconds) : null,
    }, {
      preserveScroll: true,
      onSuccess: () => setShowSettings(false),
    });
  }

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    type QuestionPayload = {
      question_type: string;
      body: string;
      score: number;
      image_path: string | null;
      allow_file_upload: boolean;
      options?: { body: string; is_correct: boolean; image_path?: string | null }[];
    };
    const payload: QuestionPayload = {
      question_type: qType,
      body,
      score: Number(score),
      image_path: questionImage,
      allow_file_upload: allowFileUpload,
    };
    if (qType === 'test') {
      payload.options = options.filter((o) => o.body.trim()).map((o) => ({ body: o.body, is_correct: o.isCorrect, image_path: o.imagePath }));
    }
    router.post(`/teacher/exams/${exam.id}/questions`, payload as Parameters<typeof router.post>[1], {
      onSuccess: () => {
        setShowForm(false);
        setBody('');
        setScore('1');
        setAllowFileUpload(false);
        setQuestionImage(null);
        setOptions([{ ...EMPTY_OPTION }, { ...EMPTY_OPTION }, { ...EMPTY_OPTION }, { ...EMPTY_OPTION }]);
      },
    });
  }

  function handleDelete(qId: number) {
    if (!confirm('سوال حذف شود؟')) return;
    router.delete(`/teacher/exams/${exam.id}/questions/${qId}`);
  }

  function handleStatusChange(status: string) {
    if (!confirm(`وضعیت امتحان به "${statusLabel[status]?.label}" تغییر دهید؟`)) return;
    router.put(`/teacher/exams/${exam.id}/status`, { status });
  }

  function setOption(idx: number, field: 'body' | 'isCorrect', value: string | boolean) {
    setOptions((prev) => prev.map((o, i) => (i === idx ? { ...o, [field]: value } : o)));
  }

  function markCorrect(idx: number) {
    setOptions((prev) => prev.map((o, i) => ({ ...o, isCorrect: i === idx })));
  }

  const badge = statusLabel[exam.status] ?? { label: exam.status, cls: 'badge badge-secondary' };

  return (
    <AppLayout title={`سوالات: ${exam.title}`}>
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>
              <i className="bi bi-list-check" style={{ marginLeft: '0.5rem', color: 'var(--color-primary)' }} />
              {exam.title}
            </h2>
            <p>{questions.length} سوال — {typeLabel[exam.type] ?? exam.type}</p>
          </div>
          <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center', flexWrap: 'wrap' }}>
            <span className={badge.cls}>{badge.label}</span>
            {!isPublished && questions.length > 0 && (
              <button className="btn btn-primary btn-sm" onClick={() => handleStatusChange('published')}>
                <i className="bi bi-send-check" /> انتشار امتحان
              </button>
            )}
            {isPublished && (
              <button className="btn btn-ghost btn-sm" onClick={() => handleStatusChange('draft')}>
                <i className="bi bi-pencil" /> بازگشت به پیش‌نویس
              </button>
            )}
            {!isPublished && (
              <button className="btn btn-ghost btn-sm" onClick={() => setShowSettings(!showSettings)}>
                <i className="bi bi-sliders" /> تنظیمات
              </button>
            )}
            {!isPublished && (
              <button className="btn btn-primary btn-sm" onClick={() => setShowForm(!showForm)}>
                <i className="bi bi-plus-lg" /> سوال جدید
              </button>
            )}
          </div>
        </section>

        <input type="file" ref={imageInputRef} onChange={onImageChange} accept="image/jpeg,image/png,image/gif,image/webp" style={{ display: 'none' }} />

        {showSettings && !isPublished && (
          <section className="panel-card">
            <h3 style={{ marginTop: 0, display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
              <i className="bi bi-sliders" style={{ color: 'var(--color-primary)' }} /> تنظیمات امتحان
            </h3>
            <div className="form-grid">
              <label className="form-check">
                <input type="checkbox" checked={settings.randomizeQuestions} onChange={(e) => setSettings({ ...settings, randomizeQuestions: e.target.checked })} />
                <span>ترتیب تصادفی سوالات</span>
              </label>
              <label className="form-check">
                <input type="checkbox" checked={settings.shuffleOptions} onChange={(e) => setSettings({ ...settings, shuffleOptions: e.target.checked })} />
                <span>بُر زدن گزینه‌ها</span>
              </label>
              <div className="form-group">
                <label className="form-label">نحوه زمان‌بندی</label>
                <select className="form-control" value={settings.timeMode} onChange={(e) => setSettings({ ...settings, timeMode: e.target.value as 'full' | 'per_question' })}>
                  <option value="full">زمان کل امتحان</option>
                  <option value="per_question">زمان جداگانه هر سوال</option>
                </select>
              </div>
              {settings.timeMode === 'per_question' && (
                <div className="form-group">
                  <label className="form-label">ثانیه برای هر سوال</label>
                  <input type="number" className="form-control" min="10" max="3600" value={settings.timePerQuestionSeconds ?? 60} onChange={(e) => setSettings({ ...settings, timePerQuestionSeconds: Number(e.target.value) })} />
                </div>
              )}
            </div>
            <div style={{ display: 'flex', gap: '0.75rem', marginTop: '1rem' }}>
              <button type="button" className="btn btn-primary" onClick={saveSettings}><i className="bi bi-check2" /> ذخیره تنظیمات</button>
              <button type="button" className="btn btn-ghost" onClick={() => setShowSettings(false)}>انصراف</button>
            </div>
          </section>
        )}

        {showForm && !isPublished && (
          <section className="panel-card">
            <h3 style={{ marginTop: 0 }}>افزودن سوال</h3>
            <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
              <div className="form-grid">
                <div className="form-group">
                  <label className="form-label">نوع سوال</label>
                  <select className="form-control" value={qType} onChange={(e) => setQType(e.target.value as 'test' | 'descriptive' | 'file')}>
                    <option value="test">تستی (چهارگزینه‌ای)</option>
                    <option value="descriptive">تشریحی</option>
                    <option value="file">آپلود فایل</option>
                  </select>
                </div>
                <div className="form-group">
                  <label className="form-label">نمره این سوال</label>
                  <input type="number" className="form-control" value={score} min="0.5" max="100" step="0.5" onChange={(e) => setScore(e.target.value)} required />
                </div>
              </div>

              <div className="form-group">
                <label className="form-label">متن سوال *</label>
                <textarea
                  className="form-control"
                  rows={3}
                  value={body}
                  onChange={(e) => setBody(e.target.value)}
                  required
                  maxLength={2000}
                  placeholder="متن سوال را اینجا بنویسید..."
                />
              </div>

              <div className="form-group">
                <label className="form-label">تصویر سوال (اختیاری)</label>
                {questionImage ? (
                  <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                    <img src={`/storage/${questionImage}`} alt="پیش‌نمایش" style={{ maxHeight: 80, borderRadius: 'var(--radius-sm)' }} />
                    <button type="button" className="btn btn-ghost btn-sm" onClick={() => uploadImage('question')}><i className="bi bi-arrow-repeat" /> تغییر</button>
                    <button type="button" className="btn btn-danger-ghost btn-sm" onClick={() => setQuestionImage(null)}><i className="bi bi-trash" /></button>
                  </div>
                ) : (
                  <button type="button" className="btn btn-soft btn-sm" onClick={() => uploadImage('question')}><i className="bi bi-image" /> افزودن تصویر</button>
                )}
              </div>

              {qType === 'descriptive' && (
                <label className="form-check" style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                  <input type="checkbox" checked={allowFileUpload} onChange={(e) => setAllowFileUpload(e.target.checked)} />
                  <span>اجازه آپلود فایل در پاسخ (عکس، PDF، ZIP)</span>
                </label>
              )}

              {qType === 'test' && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
                  <label className="form-label">گزینه‌ها (پاسخ صحیح را انتخاب کنید)</label>
                  {options.map((opt, idx) => (
                    <div key={idx} style={{ display: 'flex', flexDirection: 'column', gap: '0.3rem' }}>
                      <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
                        <span style={{ minWidth: 20, color: 'var(--color-text-muted)', fontSize: '0.85rem' }}>{idx + 1}</span>
                        <input
                          type="text"
                          className="form-control"
                          value={opt.body}
                          onChange={(e) => setOption(idx, 'body', e.target.value)}
                          placeholder={`گزینه ${idx + 1}`}
                          maxLength={500}
                          style={{ flex: 1 }}
                        />
                        <label
                          style={{
                            display: 'flex',
                            alignItems: 'center',
                            gap: '0.3rem',
                            cursor: 'pointer',
                            whiteSpace: 'nowrap',
                            color: opt.isCorrect ? 'var(--color-primary-active)' : 'var(--color-text-muted)',
                            fontSize: '0.82rem',
                            fontWeight: opt.isCorrect ? 700 : 400,
                          }}
                        >
                          <input
                            type="radio"
                            name="correct_option"
                            checked={opt.isCorrect}
                            onChange={() => markCorrect(idx)}
                            style={{ accentColor: 'var(--color-primary)' }}
                          />
                          صحیح
                        </label>
                      </div>
                      {opt.imagePath ? (
                        <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', marginRight: '2rem' }}>
                          <img src={`/storage/${opt.imagePath}`} alt="گزینه" style={{ maxHeight: 50, borderRadius: 'var(--radius-sm)' }} />
                          <button type="button" className="btn btn-ghost btn-sm" onClick={() => uploadImage(idx)}><i className="bi bi-arrow-repeat" /></button>
                        </div>
                      ) : (
                        <button type="button" className="btn btn-ghost btn-sm" style={{ marginRight: '2rem', width: 'fit-content' }} onClick={() => uploadImage(idx)}>
                          <i className="bi bi-image" /> تصویر گزینه
                        </button>
                      )}
                    </div>
                  ))}
                </div>
              )}

              <div style={{ display: 'flex', gap: '0.75rem' }}>
                <button type="submit" className="btn btn-primary"><i className="bi bi-check2" /> افزودن سوال</button>
                <button type="button" className="btn btn-ghost" onClick={() => setShowForm(false)}>انصراف</button>
              </div>
            </form>
          </section>
        )}

        {questions.length === 0 ? (
          <section className="panel-card">
            <div style={{ textAlign: 'center', padding: '2rem 1rem' }}>
              <div className="icon-badge" style={{ width: 56, height: 56, fontSize: '1.5rem', margin: '0 auto 1rem' }}>
                <i className="bi bi-list-check" />
              </div>
              <h2>سوالی اضافه نشده</h2>
              <p>از دکمه بالا سوال اضافه کنید.</p>
            </div>
          </section>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
            {questions.map((q, idx) => (
              <section key={q.id} className="panel-card">
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '0.5rem' }}>
                  <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
                    <span
                      style={{
                        background: 'var(--color-primary-soft)',
                        color: 'var(--color-primary-active)',
                        borderRadius: 'var(--radius-sm)',
                        padding: '0.1rem 0.5rem',
                        fontSize: '0.8rem',
                        fontWeight: 700,
                      }}
                    >
                      {idx + 1}
                    </span>
                    <span className="badge badge-secondary">{typeLabel[q.type] ?? q.type}</span>
                    {q.allowFileUpload && <span className="badge badge-success"><i className="bi bi-paperclip" /> فایل</span>}
                    <span style={{ fontSize: '0.8rem', color: 'var(--color-text-muted)' }}>{q.score} نمره</span>
                  </div>
                  {!isPublished && (
                    <button
                      className="btn btn-ghost btn-sm"
                      style={{ color: 'var(--color-danger)' }}
                      onClick={() => handleDelete(q.id)}
                    >
                      <i className="bi bi-trash" />
                    </button>
                  )}
                </div>

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

                {q.imagePath && (
                  <img src={`/storage/${q.imagePath}`} alt="تصویر سوال" style={{ maxWidth: '100%', maxHeight: 200, borderRadius: 'var(--radius-sm)', marginBottom: '0.75rem' }} />
                )}

                {q.type === 'test' && q.options.length > 0 && (
                  <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: '0.4rem' }}>
                    {q.options.map((opt) => (
                      <li
                        key={opt.id}
                        style={{
                          display: 'flex',
                          alignItems: 'center',
                          gap: '0.5rem',
                          padding: '0.4rem 0.75rem',
                          borderRadius: 'var(--radius-sm)',
                          background: opt.isCorrect ? 'var(--color-primary-soft)' : 'var(--color-bg-muted)',
                          border: opt.isCorrect ? '1px solid var(--color-primary)' : '1px solid transparent',
                          fontSize: '0.875rem',
                        }}
                      >
                        {opt.isCorrect && (
                          <i className="bi bi-check-circle-fill" style={{ color: 'var(--color-primary-active)', flexShrink: 0 }} />
                        )}
                        {opt.body}
                      </li>
                    ))}
                  </ul>
                )}
              </section>
            ))}
          </div>
        )}
      </div>
    </AppLayout>
  );
}
