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

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

type ReportRow = {
  classId: number;
  classTitle: string;
  startedAt: string;
  userId: number;
  name: string;
  totalSeconds: number;
  minutes: number;
};

type Props = {
  classrooms: Classroom[];
  selectedClassId: number | null;
  report: ReportRow[];
};

const fmtMin = (min: number): string => {
  if (min < 60) return `${min} دقیقه`;
  const h = Math.floor(min / 60);
  const m = min % 60;
  return `${h} ساعت${m ? ` و ${m} دقیقه` : ''}`;
};

export default function AttendanceMinutes({ classrooms, selectedClassId, report }: Props) {
  const [cls, setCls] = useState<string>(selectedClassId ? String(selectedClassId) : '');

  const search = () => {
    if (cls) router.get('/school/attendance-minutes', { class_id: cls }, { preserveState: true });
  };

  // گروه‌بندی بر اساس کلاس
  const byClass = report.reduce<Record<number, ReportRow[]>>((acc, r) => {
    if (!acc[r.classId]) acc[r.classId] = [];
    acc[r.classId].push(r);
    return acc;
  }, {});

  return (
    <AppLayout title="گزارش دقایق حضور">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>گزارش دقایق حضور</h2>
            <p>مدت زمان حضور دانش‌آموزان در هر کلاس آنلاین.</p>
          </div>
        </section>

        <section className="panel-card">
          <div style={{ display: 'flex', gap: '0.75rem', flexWrap: 'wrap', alignItems: 'flex-end' }}>
            <div className="form-group" style={{ flex: '1 1 200px' }}>
              <label className="form-label">انتخاب کلاس</label>
              <select className="form-input" value={cls} onChange={e => setCls(e.target.value)}>
                <option value="">— انتخاب کنید —</option>
                {classrooms.map(c => <option key={c.id} value={String(c.id)}>{c.name}</option>)}
              </select>
            </div>
            <button className="btn btn-primary" type="button" onClick={search} disabled={!cls}>
              <i className="bi bi-search" /> نمایش گزارش
            </button>
          </div>
        </section>

        {report.length > 0 && Object.entries(byClass).map(([classId, rows]) => (
          <section key={classId} className="panel-card">
            <h3 style={{ fontWeight: 700, marginBottom: '0.75rem' }}>
              <i className="bi bi-camera-video" style={{ marginLeft: '0.4rem' }} />
              {rows[0].classTitle}
              <span style={{ fontSize: '0.8rem', fontWeight: 400, color: 'var(--color-text-soft)', marginRight: '0.5rem' }}>
                {rows[0].startedAt}
              </span>
            </h3>
            <div className="table-wrap">
              <table className="data-table">
                <thead>
                  <tr>
                    <th>دانش‌آموز</th>
                    <th>مدت حضور</th>
                    <th>دقیقه</th>
                  </tr>
                </thead>
                <tbody>
                  {rows.map(r => (
                    <tr key={r.userId}>
                      <td>{r.name}</td>
                      <td>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                          <div
                            style={{
                              height: 8,
                              borderRadius: 4,
                              background: 'var(--color-primary, #0EA678)',
                              width: Math.min(100, Math.round((r.minutes / 90) * 100)) + '%',
                              minWidth: 4,
                              maxWidth: 120,
                            }}
                          />
                          <span style={{ fontSize: '0.85rem' }}>{fmtMin(r.minutes)}</span>
                        </div>
                      </td>
                      <td style={{ fontSize: '0.85rem', color: 'var(--color-text-soft)' }}>{r.minutes}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </section>
        ))}

        {selectedClassId && report.length === 0 && (
          <section className="panel-card">
            <p style={{ color: 'var(--color-text-soft)', textAlign: 'center', padding: '2rem' }}>
              داده‌ای برای این کلاس ثبت نشده است.
            </p>
          </section>
        )}
      </div>
    </AppLayout>
  );
}
