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

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

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

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

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 };

export default function TeacherExamQuestions({ exam, questions }: Props) {
  const [showForm, setShowForm] = useState(false);
  const [qType, setQType] = useState<'test' | 'descriptive' | 'file'>('test');
  const [body, setBody] = useState('');
  const [score, setScore] = useState('1');
  const [options, setOptions] = useState([{ ...EMPTY_OPTION }, { ...EMPTY_OPTION }, { ...EMPTY_OPTION }, { ...EMPTY_OPTION }]);
  const isPublished = exam.status === 'published';

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    type QuestionPayload = {
      question_type: string;
      body: string;
      score: number;
      options?: { body: string; is_correct: boolean }[];
    };
    const payload: QuestionPayload = { question_type: qType, body, score: Number(score) };
    if (qType === 'test') {
      payload.options = options.filter((o) => o.body.trim()).map((o) => ({ body: o.body, is_correct: o.isCorrect }));
    }
    router.post(`/teacher/exams/${exam.id}/questions`, payload as Parameters<typeof router.post>[1], {
      onSuccess: () => {
        setShowForm(false);
        setBody('');
        setScore('1');
        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-primary btn-sm" onClick={() => setShowForm(!showForm)}>
                <i className="bi bi-plus-lg" /> سوال جدید
              </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>

              {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', 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>
                  ))}
                </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>
                    <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.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>
  );
}
