import { useForm } from '@inertiajs/react';
import { AppLayout } from '@/Components/Layout/AppLayout';
import { TextInput } from '@/Components/Forms/TextInput';
import { SelectInput } from '@/Components/Forms/SelectInput';
import { JalaliDateTimePicker } from '@/Components/Forms/JalaliDateTimePicker';

type Option = { value: string | number; label: string };

type Props = {
  classes: Option[];
  subjects: Option[];
  recentExams: Array<{
    id: number;
    title: string;
    classroom: string;
    subject: string;
    status: string;
    startsAt: string;
  }>;
};

export default function ExamBuilder({ classes, subjects, recentExams }: Props) {
  const form = useForm({
    title: '',
    classroom_id: '',
    subject_id: '',
    type: 'mixed',
    starts_at: '',
    ends_at: '',
    duration_minutes: '',
    max_score: '20',
    randomize_questions: false,
    shuffle_options: false,
    time_mode: 'full',
    time_per_question_seconds: '60',
  });

  const classOptions = classes.length > 0 ? classes : [{ value: '', label: 'کلاسی ثبت نشده' }];
  const subjectOptions = subjects.length > 0 ? subjects : [{ value: '', label: 'درسی ثبت نشده' }];

  return (
    <AppLayout title="ساخت امتحان">
      <div className="page-stack">
        <section className="split-panel">
          <form className="panel-card" onSubmit={(event) => { event.preventDefault(); form.post('/teacher/exams', { preserveScroll: true, onSuccess: () => form.reset() }); }}>
            <h2>اطلاعات امتحان</h2>
            <div className="form-grid">
              <TextInput label="عنوان امتحان" placeholder="مثلا آزمون فصل اول ریاضی" value={form.data.title} onChange={(event) => form.setData('title', event.target.value)} error={form.errors.title} />
              <SelectInput label="کلاس" value={form.data.classroom_id} onChange={(event) => form.setData('classroom_id', event.target.value)} options={[{ value: '', label: 'انتخاب کلاس' }, ...classOptions]} />
              <SelectInput label="درس" value={form.data.subject_id} onChange={(event) => form.setData('subject_id', event.target.value)} options={[{ value: '', label: 'انتخاب درس' }, ...subjectOptions]} />
              <SelectInput label="نوع امتحان" value={form.data.type} onChange={(event) => form.setData('type', event.target.value)} options={[
                { value: 'test', label: 'تستی' },
                { value: 'descriptive', label: 'تشریحی' },
                { value: 'mixed', label: 'ترکیبی' },
                { value: 'file', label: 'فایل' },
                { value: 'offline', label: 'حضوری/آفلاین' },
              ]} />
              <JalaliDateTimePicker label="زمان شروع" value={form.data.starts_at} onChange={(value) => form.setData('starts_at', value)} />
              <JalaliDateTimePicker label="زمان پایان" value={form.data.ends_at} onChange={(value) => form.setData('ends_at', value)} />
              <TextInput label="مدت زمان" type="number" min="1" value={form.data.duration_minutes} onChange={(event) => form.setData('duration_minutes', event.target.value)} />
              <TextInput label="نمره کامل" type="number" min="1" value={form.data.max_score} onChange={(event) => form.setData('max_score', event.target.value)} />
            </div>

            <h3 style={{ margin: '1.25rem 0 0.5rem', fontSize: '1rem' }}>
              <i className="bi bi-gear" style={{ marginLeft: '0.4rem', color: 'var(--color-primary)' }} />
              تنظیمات امتحان
            </h3>
            <div className="form-grid">
              <div className="form-group">
                <label className="form-check">
                  <input type="checkbox" checked={form.data.randomize_questions} onChange={(e) => form.setData('randomize_questions', e.target.checked)} />
                  <span>ترتیب تصادفی سوالات</span>
                </label>
              </div>
              <div className="form-group">
                <label className="form-check">
                  <input type="checkbox" checked={form.data.shuffle_options} onChange={(e) => form.setData('shuffle_options', e.target.checked)} />
                  <span>بُر زدن گزینه‌ها</span>
                </label>
              </div>
              <div className="form-group">
                <label className="form-label">نحوه زمان‌بندی</label>
                <select className="form-control" value={form.data.time_mode} onChange={(e) => form.setData('time_mode', e.target.value)}>
                  <option value="full">زمان کل امتحان</option>
                  <option value="per_question">زمان جداگانه هر سوال</option>
                </select>
              </div>
              {form.data.time_mode === 'per_question' && (
                <TextInput label="ثانیه برای هر سوال" type="number" min="10" max="3600" value={form.data.time_per_question_seconds} onChange={(e) => form.setData('time_per_question_seconds', e.target.value)} />
              )}
            </div>
            <p style={{ fontSize: '0.8rem', color: 'var(--color-text-muted)', margin: '0.5rem 0 0' }}>
              <i className="bi bi-shield-lock" style={{ marginLeft: '0.3rem' }} />
              در زمان امتحان: کپی، کلیک راست و خروج از صفحه برای دانش‌آموز غیرفعال است.
            </p>

            <button className="btn btn-primary" disabled={form.processing} type="submit"><i className="bi bi-plus-circle" /> ساخت امتحان</button>
          </form>
          <aside className="panel-card">
            <h2>نوع سوال‌ها</h2>
            <ul className="check-list">
              <li><span>تستی با گزینه‌ها</span><i className="bi bi-ui-checks" /></li>
              <li><span>تشریحی با تصحیح معلم</span><i className="bi bi-pencil-square" /></li>
              <li><span>آپلود فایل پاسخ</span><i className="bi bi-paperclip" /></li>
              <li><span>Auto-save و timer</span><i className="bi bi-stopwatch" /></li>
            </ul>
          </aside>
        </section>
        {recentExams.length > 0 ? (
          <section className="panel-card" style={{ padding: 0, overflow: 'hidden' }}>
            <div style={{ overflowX: 'auto' }}>
              <table className="data-table" style={{ width: '100%' }}>
                <thead>
                  <tr>
                    <th>عنوان</th>
                    <th>کلاس</th>
                    <th>درس</th>
                    <th>وضعیت</th>
                    <th>شروع</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  {recentExams.map((exam) => (
                    <tr key={exam.id}>
                      <td style={{ fontWeight: 600 }}>{exam.title}</td>
                      <td>{exam.classroom}</td>
                      <td>{exam.subject}</td>
                      <td>
                        <span className={exam.status === 'published' ? 'badge badge-success' : 'badge badge-secondary'}>
                          {exam.status === 'published' ? 'منتشر' : exam.status === 'archived' ? 'آرشیو' : 'پیش‌نویس'}
                        </span>
                      </td>
                      <td style={{ fontSize: '0.85rem', color: 'var(--color-text-muted)', whiteSpace: 'nowrap' }}>{exam.startsAt}</td>
                      <td>
                        <div className="action-row--compact">
                          <a
                            href={`/teacher/exams/${exam.id}/questions`}
                            className="btn btn-ghost btn-sm"
                            title="مدیریت سوالات"
                          >
                            <i className="bi bi-list-check" />
                          </a>
                          <a
                            href={`/teacher/exams/${exam.id}/submissions`}
                            className="btn btn-ghost btn-sm"
                            title="تصحیح و نمره‌دهی"
                          >
                            <i className="bi bi-clipboard2-check" />
                          </a>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </section>
        ) : (
          <section className="panel-card"><h2>امتحانی ثبت نشده</h2><p>بعد از ذخیره امتحان، لیست امتحانات واقعی از دیتابیس اینجا نمایش داده می‌شود.</p></section>
        )}
      </div>
    </AppLayout>
  );
}
