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

type SelectOption = { value: number; label: string };

type Homework = {
  id: number;
  title: string;
  classroom: string;
  subject: string;
  status: string;
  dueAt: string;
  submissionCount: number;
};

type Props = {
  homeworks: Homework[];
  classes: SelectOption[];
  subjects: SelectOption[];
};

const statusLabel: Record<string, string> = {
  draft: 'پیش‌نویس',
  published: 'منتشر',
  closed: 'بسته',
  archived: 'آرشیو',
};

const statusClass: Record<string, string> = {
  draft: 'badge badge-secondary',
  published: 'badge badge-success',
  closed: 'badge badge-warning',
  archived: 'badge badge-secondary',
};

export default function TeacherHomeworks({ homeworks, classes, subjects }: Props) {
  const [showForm, setShowForm] = useState(false);
  const [form, setForm] = useState({
    title: '',
    classroom_id: '',
    subject_id: '',
    description: '',
    due_at: '',
    allow_file_upload: true,
  });

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    router.post('/teacher/homeworks', {
      ...form,
      classroom_id: Number(form.classroom_id),
      subject_id: form.subject_id ? Number(form.subject_id) : null,
    }, {
      onSuccess: () => {
        setShowForm(false);
        setForm({ title: '', classroom_id: '', subject_id: '', description: '', due_at: '', allow_file_upload: true });
      },
    });
  }

  function handleDelete(id: number) {
    if (!confirm('تکلیف حذف شود؟')) return;
    router.delete(`/teacher/homeworks/${id}`);
  }

  return (
    <AppLayout title="تکالیف">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2><i className="bi bi-journal-check" style={{ marginLeft: '0.5rem', color: 'var(--color-primary)' }} />تکالیف</h2>
            <p>مدیریت تکالیف کلاس‌های شما</p>
          </div>
          <button className="btn btn-primary" onClick={() => setShowForm(!showForm)}>
            <i className="bi bi-plus-lg" /> تکلیف جدید
          </button>
        </section>

        {showForm && (
          <section className="panel-card">
            <h3 style={{ marginTop: 0 }}>تکلیف جدید</h3>
            <form onSubmit={handleSubmit} className="form-grid">
              <div className="form-group">
                <label className="form-label">عنوان تکلیف *</label>
                <input
                  className="form-control"
                  value={form.title}
                  onChange={(e) => setForm({ ...form, title: e.target.value })}
                  required
                  maxLength={190}
                  placeholder="مثلاً: حل مسائل فصل ۳"
                />
              </div>

              <div className="form-group">
                <label className="form-label">کلاس *</label>
                <select
                  className="form-control"
                  value={form.classroom_id}
                  onChange={(e) => setForm({ ...form, classroom_id: e.target.value })}
                  required
                >
                  <option value="">انتخاب کلاس</option>
                  {classes.map((c) => (
                    <option key={c.value} value={c.value}>{c.label}</option>
                  ))}
                </select>
              </div>

              <div className="form-group">
                <label className="form-label">درس</label>
                <select
                  className="form-control"
                  value={form.subject_id}
                  onChange={(e) => setForm({ ...form, subject_id: e.target.value })}
                >
                  <option value="">انتخاب درس (اختیاری)</option>
                  {subjects.map((s) => (
                    <option key={s.value} value={s.value}>{s.label}</option>
                  ))}
                </select>
              </div>

              <div className="form-group">
                <label className="form-label">مهلت تحویل</label>
                <input
                  type="datetime-local"
                  className="form-control"
                  value={form.due_at}
                  onChange={(e) => setForm({ ...form, due_at: e.target.value })}
                />
              </div>

              <div className="form-group" style={{ gridColumn: '1 / -1' }}>
                <label className="form-label">توضیحات</label>
                <textarea
                  className="form-control"
                  rows={3}
                  value={form.description}
                  onChange={(e) => setForm({ ...form, description: e.target.value })}
                  placeholder="شرح تکلیف..."
                  maxLength={2000}
                />
              </div>

              <div className="form-group" style={{ gridColumn: '1 / -1', display: 'flex', alignItems: 'center', gap: '0.6rem' }}>
                <input
                  type="checkbox"
                  id="allow_file"
                  checked={form.allow_file_upload}
                  onChange={(e) => setForm({ ...form, allow_file_upload: e.target.checked })}
                  style={{ width: 16, height: 16 }}
                />
                <label htmlFor="allow_file" style={{ margin: 0, cursor: 'pointer' }}>
                  دانش‌آموزان می‌توانند فایل ضمیمه کنند
                </label>
              </div>

              <div style={{ gridColumn: '1 / -1', 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>
        )}

        {homeworks.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-journal-check" />
              </div>
              <h2>تکلیفی ثبت نشده</h2>
              <p>اولین تکلیف خود را از دکمه بالا ثبت کنید.</p>
            </div>
          </section>
        ) : (
          <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>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  {homeworks.map((hw) => (
                    <tr key={hw.id}>
                      <td style={{ fontWeight: 600 }}>{hw.title}</td>
                      <td>{hw.classroom}</td>
                      <td>{hw.subject}</td>
                      <td style={{ direction: 'ltr', textAlign: 'right', whiteSpace: 'nowrap', fontSize: '0.85rem', color: 'var(--color-text-muted)' }}>
                        {hw.dueAt}
                      </td>
                      <td>
                        <span
                          style={{
                            display: 'inline-flex',
                            alignItems: 'center',
                            gap: '0.3rem',
                            background: 'var(--color-primary-soft)',
                            color: 'var(--color-primary-active)',
                            borderRadius: 'var(--radius-sm)',
                            padding: '0.2rem 0.6rem',
                            fontSize: '0.82rem',
                            fontWeight: 700,
                          }}
                        >
                          <i className="bi bi-people" />
                          {hw.submissionCount}
                        </span>
                      </td>
                      <td>
                        <span className={statusClass[hw.status] ?? 'badge badge-secondary'}>
                          {statusLabel[hw.status] ?? hw.status}
                        </span>
                      </td>
                      <td>
                        <button
                          className="btn btn-ghost btn-sm"
                          style={{ color: 'var(--color-danger)' }}
                          onClick={() => handleDelete(hw.id)}
                          title="حذف تکلیف"
                        >
                          <i className="bi bi-trash" />
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </section>
        )}
      </div>
    </AppLayout>
  );
}
