import { useState } from 'react';
import { useForm, router, Link } from '@inertiajs/react';
import { AppLayout } from '@/Components/Layout/AppLayout';
import { TextInput } from '@/Components/Forms/TextInput';
import { SelectInput } from '@/Components/Forms/SelectInput';

type OnlineClass = {
  id: number;
  title: string;
  meetingUrl: string;
  startsAt: string;
  endsAt: string;
  classroom: string;
  subject: string;
  teacher: string;
  joinCount: number;
};

type Classroom = { id: number; name: string };
type Subject = { id: number; name: string };

type Props = {
  classes: OnlineClass[];
  classrooms: Classroom[];
  subjects: Subject[];
};

export default function OnlineClasses({ classes, classrooms, subjects }: Props) {
  const [showForm, setShowForm] = useState(false);

  const form = useForm({
    classroom_id: '',
    subject_id: '',
    title: '',
    meeting_url: '',
    starts_at: '',
    ends_at: '',
  });

  function handleSubmit(event: React.FormEvent) {
    event.preventDefault();
    form.post('/school/online-classes', {
      onSuccess: () => {
        form.reset();
        setShowForm(false);
      },
    });
  }

  function handleDelete(id: number, title: string) {
    if (!confirm(`حذف کلاس آنلاین «${title}»؟`)) return;
    router.delete(`/school/online-classes/${id}`, { preserveScroll: true });
  }

  const classroomOptions = [
    { value: '', label: 'انتخاب کلاس...' },
    ...classrooms.map((c) => ({ value: String(c.id), label: c.name })),
  ];

  const subjectOptions = [
    { value: '', label: 'بدون درس' },
    ...subjects.map((s) => ({ value: String(s.id), label: s.name })),
  ];

  return (
    <AppLayout title="کلاس‌های آنلاین">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>کلاس‌های آنلاین</h2>
            <p>ثبت لینک جلسات آنلاین برای کلاس‌ها.</p>
          </div>
          <button className="btn btn-primary" type="button" onClick={() => setShowForm(!showForm)}>
            <i className="bi bi-camera-video" /> کلاس جدید
          </button>
        </section>

        {showForm && (
          <form className="panel-card" onSubmit={handleSubmit}>
            <h2>افزودن کلاس آنلاین</h2>
            <div className="form-grid">
              <SelectInput
                label="کلاس"
                options={classroomOptions}
                value={form.data.classroom_id}
                onChange={(e) => form.setData('classroom_id', e.target.value)}
              />
              <SelectInput
                label="درس (اختیاری)"
                options={subjectOptions}
                value={form.data.subject_id}
                onChange={(e) => form.setData('subject_id', e.target.value)}
              />
              <TextInput
                label="عنوان جلسه"
                value={form.data.title}
                onChange={(e) => form.setData('title', e.target.value)}
                error={form.errors.title}
              />
              <TextInput
                label="لینک جلسه (URL)"
                type="url"
                value={form.data.meeting_url}
                onChange={(e) => form.setData('meeting_url', e.target.value)}
                error={form.errors.meeting_url}
              />
              <TextInput
                label="شروع جلسه"
                type="datetime-local"
                value={form.data.starts_at}
                onChange={(e) => form.setData('starts_at', e.target.value)}
              />
              <TextInput
                label="پایان جلسه"
                type="datetime-local"
                value={form.data.ends_at}
                onChange={(e) => form.setData('ends_at', e.target.value)}
              />
            </div>
            <div className="action-row">
              <button className="btn btn-primary" disabled={form.processing} type="submit">ثبت</button>
              <button className="btn btn-ghost" type="button" onClick={() => setShowForm(false)}>لغو</button>
            </div>
          </form>
        )}

        {classes.length > 0 ? (
          <div className="table-wrap">
            <table className="data-table">
              <thead>
                <tr>
                  <th>عنوان</th>
                  <th>کلاس</th>
                  <th>درس</th>
                  <th>شروع</th>
                  <th>پایان</th>
                  <th>ورودی‌ها</th>
                  <th>عملیات</th>
                </tr>
              </thead>
              <tbody>
                {classes.map((c) => (
                  <tr key={c.id}>
                    <td>
                      <a href={c.meetingUrl} target="_blank" rel="noreferrer" className="btn btn-ghost btn-sm">
                        <i className="bi bi-box-arrow-up-left" /> {c.title}
                      </a>
                    </td>
                    <td>{c.classroom}</td>
                    <td>{c.subject}</td>
                    <td>{c.startsAt}</td>
                    <td>{c.endsAt}</td>
                    <td style={{ textAlign: 'center' }}>
                      <Link href={`/school/online-classes/${c.id}/logs`} className="badge badge-muted" style={{ textDecoration: 'none' }}>
                        {c.joinCount} نفر
                      </Link>
                    </td>
                    <td>
                      <button
                        className="btn btn-danger-ghost btn-sm"
                        type="button"
                        onClick={() => handleDelete(c.id, c.title)}
                      >
                        <i className="bi bi-trash" /> حذف
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <section className="panel-card">
            <h2>هنوز کلاس آنلاینی ثبت نشده</h2>
            <p>از دکمه «کلاس جدید» اولین جلسه را ثبت کن.</p>
          </section>
        )}
      </div>
    </AppLayout>
  );
}
