import { useState } from 'react';
import { AppLayout } from '@/Components/Layout/AppLayout';
import { formatPersianTimeRange } from '@/lib/persianDate';

type ScheduleRow = {
  id: number;
  day: string;
  dayNum: number;
  time: string;
  classroom: string;
  classroomId: number;
  subject: string;
  subjectId: number;
  teacher: string;
  room: string;
  hasClassToday: boolean;
  roomUrl: string | null;
};

type Props = {
  schedules: ScheduleRow[];
};

const DAYS = ['شنبه', 'یکشنبه', 'دوشنبه', 'سه‌شنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه'];

export default function ScheduleBuilder({ schedules }: Props) {
  const [creating, setCreating] = useState<number | null>(null);

  const createClass = (scheduleId: number) => {
    setCreating(scheduleId);
    const tab = window.open('about:blank', '_blank');
    if (tab) {
      tab.document.title = 'در حال آماده‌سازی کلاس…';
      tab.opener = null;
    }

    const match = document.cookie.match(/XSRF-TOKEN=([^;]+)/);
    fetch(`/school/schedule/${scheduleId}/create-class`, {
      method: 'POST',
      credentials: 'same-origin',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
        'X-XSRF-TOKEN': match ? decodeURIComponent(match[1]) : '',
      },
      body: '{}',
    })
      .then(async (response) => {
        if (!response.ok) throw new Error('کلاس ساخته نشد. دوباره تلاش کنید.');
        return response.json() as Promise<{ url: string }>;
      })
      .then(({ url }) => {
        if (tab) tab.location.replace(url);
        else window.open(url, '_blank', 'noopener,noreferrer');
        window.location.reload();
      })
      .catch((error: Error) => {
        tab?.close();
        window.alert(error.message);
      })
      .finally(() => setCreating(null));
  };

  const byDay = DAYS.reduce<Record<string, ScheduleRow[]>>((acc, d) => {
    acc[d] = schedules.filter(s => s.day === d);
    return acc;
  }, {});

  const hasSomeRows = schedules.length > 0;

  return (
    <AppLayout title="برنامه هفتگی">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>برنامه کلاس و معلم</h2>
            <p>دکمه «ایجاد کلاس امروز» یک اتاق کلاس داخلی می‌سازد و شما را وارد می‌کند.</p>
          </div>
        </section>

        {!hasSomeRows ? (
          <section className="panel-card">
            <h2>برنامه‌ای ثبت نشده</h2>
            <p>بعد از ثبت برنامه‌ها، جدول هفتگی نمایش داده می‌شود.</p>
          </section>
        ) : (
          DAYS.map(day => {
            const rows = byDay[day];
            if (!rows.length) return null;
            return (
              <section key={day} className="panel-card">
                <h3 style={{ fontWeight: 700, marginBottom: '0.75rem', fontSize: '1rem' }}>
                  <i className="bi bi-calendar-week" style={{ marginLeft: '0.35rem' }} />{day}
                </h3>
                <div className="table-wrap">
                  <table className="data-table">
                    <thead>
                      <tr>
                        <th>ساعت</th>
                        <th>کلاس</th>
                        <th>درس</th>
                        <th>معلم</th>
                        <th>اتاق</th>
                        <th></th>
                      </tr>
                    </thead>
                    <tbody>
                      {rows.map(s => (
                        <tr key={s.id}>
                          <td style={{ fontSize: '0.88rem' }}>{formatPersianTimeRange(s.time)}</td>
                          <td>{s.classroom}</td>
                          <td>{s.subject}</td>
                          <td>{s.teacher}</td>
                          <td>{s.room}</td>
                          <td>
                            {s.hasClassToday ? (
                              <a href={s.roomUrl ?? '#'} target="_blank" rel="noopener noreferrer" className="btn btn-soft btn-sm">
                                <i className="bi bi-box-arrow-up-left" /> ورود به کلاس امروز
                              </a>
                            ) : (
                              <button
                                className="btn btn-primary btn-sm"
                                type="button"
                                disabled={creating === s.id}
                                onClick={() => createClass(s.id)}
                              >
                                {creating === s.id ? (
                                  <><i className="bi bi-arrow-repeat" /> ایجاد...</>
                                ) : (
                                  <><i className="bi bi-camera-video-fill" /> ایجاد کلاس امروز</>
                                )}
                              </button>
                            )}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </section>
            );
          })
        )}
      </div>
    </AppLayout>
  );
}
