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

type Session = {
  id: number;
  joinedAt: string;
  leftAt: string | null;
  durationSeconds: number;
  online: boolean;
};

type Person = {
  userId: number | null;
  name: string;
  studentCode: string | null;
  roleLabel: string;
  sessionCount: number;
  totalSeconds: number;
  lastJoinedAt: string;
  lastLeftAt: string | null;
  online: boolean;
  sessions: Session[];
};

type Recording = {
  id: number;
  title: string;
  sizeBytes: number;
  durationSeconds: number;
  startedAt: string;
  endedAt: string | null;
};

type Props = {
  classId: number;
  roomKey: string;
  classTitle: string;
  people: Person[];
  recordings: Recording[];
};

function duration(seconds: number): string {
  const safe = Math.max(0, Math.floor(seconds));
  const hours = Math.floor(safe / 3600);
  const minutes = Math.floor((safe % 3600) / 60);
  const remainder = safe % 60;
  return [hours > 0 ? `${hours} ساعت` : '', minutes > 0 ? `${minutes} دقیقه` : '', `${remainder} ثانیه`].filter(Boolean).join(' و ');
}

function size(bytes: number): string {
  if (bytes >= 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)} مگابایت`;
  return `${Math.max(1, Math.round(bytes / 1024))} کیلوبایت`;
}

export default function OnlineClassLogs({ classId, roomKey, classTitle, people, recordings }: Props) {
  const [openUser, setOpenUser] = useState<string | null>(null);
  const totalSeconds = people.reduce((sum, person) => sum + person.totalSeconds, 0);
  const activeCount = people.filter((person) => person.online).length;

  return (
    <AppLayout title={`حضور و ضبط‌ها — ${classTitle}`}>
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>حضور، ورود و خروج کلاس</h2>
            <p>{classTitle} — هر ورود و خروج جداگانه تا سطح ثانیه ثبت می‌شود.</p>
          </div>
          <div className="action-row">
            <a href={`/class-room/${roomKey}`} target="_blank" rel="noopener noreferrer" className="btn btn-primary"><i className="bi bi-door-open" /> ورود به اتاق</a>
            <Link href="/school/online-classes" className="btn btn-ghost"><i className="bi bi-arrow-right" /> بازگشت</Link>
          </div>
        </section>

        <div className="stats-grid">
          <article className="stat-card"><div className="stat-icon"><i className="bi bi-people" /></div><div><span>اعضای واردشده</span><strong>{people.length}</strong></div></article>
          <article className="stat-card"><div className="stat-icon"><i className="bi bi-broadcast-pin" /></div><div><span>اکنون داخل کلاس</span><strong>{activeCount}</strong></div></article>
          <article className="stat-card"><div className="stat-icon"><i className="bi bi-clock-history" /></div><div><span>مجموع حضور</span><strong style={{ fontSize: '1rem' }}>{duration(totalSeconds)}</strong></div></article>
          <article className="stat-card"><div className="stat-icon"><i className="bi bi-record-circle" /></div><div><span>جلسه ضبط‌شده</span><strong>{recordings.length}</strong></div></article>
        </div>

        <section className="panel-card">
          <div className="section-header" style={{ marginBottom: '0.75rem' }}>
            <div><h2>جزئیات حضور اعضا</h2><p>روی هر ردیف بزنید تا تمام ورودها و خروج‌ها دیده شود.</p></div>
          </div>

          {people.length === 0 ? <p style={{ color: 'var(--color-text-muted)' }}>هنوز کسی وارد این کلاس نشده است.</p> : (
            <div className="table-wrap" style={{ margin: '0 -1rem -1rem' }}>
              <table className="data-table">
                <thead><tr><th>نام و نقش</th><th>آخرین ورود</th><th>آخرین خروج</th><th>دفعات ورود</th><th>کل زمان حضور</th><th /></tr></thead>
                <tbody>
                  {people.map((person, index) => {
                    const key = person.userId ? `user-${person.userId}` : `unknown-${index}`;
                    const expanded = openUser === key;
                    return [
                      <tr key={key} onClick={() => setOpenUser(expanded ? null : key)} style={{ cursor: 'pointer' }}>
                        <td><strong>{person.name}</strong><div style={{ color: 'var(--color-text-muted)', fontSize: '0.72rem' }}>{person.roleLabel}{person.studentCode ? ` · ${person.studentCode}` : ''} {person.online && <span className="badge badge-success" style={{ marginRight: '0.3rem' }}>آنلاین</span>}</div></td>
                        <td>{person.lastJoinedAt}</td>
                        <td>{person.lastLeftAt ?? <span className="badge badge-success">هنوز داخل کلاس</span>}</td>
                        <td>{person.sessionCount}</td>
                        <td style={{ fontWeight: 700 }}>{duration(person.totalSeconds)}</td>
                        <td><i className={`bi bi-chevron-${expanded ? 'up' : 'down'}`} /></td>
                      </tr>,
                      expanded && <tr key={`${key}-sessions`}><td colSpan={6} style={{ background: 'var(--color-bg-soft, #f8fafc)', padding: '0.65rem 1rem' }}>
                        <div style={{ display: 'grid', gap: '0.4rem' }}>
                          {person.sessions.map((session, sessionIndex) => <div key={session.id} style={{ display: 'grid', gridTemplateColumns: '70px minmax(140px,1fr) minmax(140px,1fr) minmax(110px,.7fr)', gap: '0.5rem', alignItems: 'center', fontSize: '0.78rem' }}>
                            <strong>ورود {person.sessions.length - sessionIndex}</strong>
                            <span><i className="bi bi-box-arrow-in-left" style={{ color: 'var(--color-success)', marginLeft: '0.3rem' }} />{session.joinedAt}</span>
                            <span><i className="bi bi-box-arrow-right" style={{ color: 'var(--color-danger)', marginLeft: '0.3rem' }} />{session.leftAt ?? 'هنوز خارج نشده'}</span>
                            <span>{duration(session.durationSeconds)}</span>
                          </div>)}
                        </div>
                      </td></tr>,
                    ];
                  })}
                </tbody>
              </table>
            </div>
          )}
        </section>

        <section className="panel-card">
          <div className="section-header" style={{ marginBottom: '0.8rem' }}>
            <div><h2>ضبط‌های کلاس</h2><p>ویدئو همراه با گفتگوی عمومی همان زمان بازپخش می‌شود.</p></div>
          </div>
          {recordings.length === 0 ? <p style={{ color: 'var(--color-text-muted)' }}>هنوز ضبطی ذخیره نشده است. مدیر یا معلم از داخل اتاق می‌تواند ضبط را شروع کند.</p> : (
            <div style={{ display: 'grid', gap: '0.6rem', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))' }}>
              {recordings.map((recording) => <article key={recording.id} style={{ border: '1px solid var(--color-border)', borderRadius: 'var(--radius-md)', padding: '0.8rem', display: 'flex', flexDirection: 'column', gap: '0.45rem' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '0.55rem' }}><span className="stat-icon" style={{ width: 38, height: 38 }}><i className="bi bi-play-circle" /></span><div><strong>{recording.title}</strong><small style={{ display: 'block', color: 'var(--color-text-muted)' }}>{recording.startedAt}</small></div></div>
                <small style={{ color: 'var(--color-text-muted)' }}>{duration(recording.durationSeconds)} · {size(recording.sizeBytes)}</small>
                <Link href={`/school/online-classes/${classId}/recordings/${recording.id}`} className="btn btn-soft btn-sm" style={{ alignSelf: 'flex-start' }}><i className="bi bi-play-fill" /> مشاهده ضبط و گفتگو</Link>
              </article>)}
            </div>
          )}
        </section>
      </div>
    </AppLayout>
  );
}
