import { Link } from '@inertiajs/react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { AppLayout } from '@/Components/Layout/AppLayout';

type ReplayMessage = {
  id: number;
  name: string;
  body: string;
  isHost: boolean;
  offsetSeconds: number;
};

type Props = {
  classId: number;
  classTitle: string;
  recording: { id: number; title: string; startedAt: string; durationSeconds: number; streamUrl: string };
  messages: ReplayMessage[];
};

function clock(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, minutes, remainder].map((part, index) => index === 0 ? String(part) : String(part).padStart(2, '0')).join(':');
}

export default function OnlineClassRecording({ classId, classTitle, recording, messages }: Props) {
  const [currentTime, setCurrentTime] = useState(0);
  const videoRef = useRef<HTMLVideoElement>(null);
  const chatRef = useRef<HTMLDivElement>(null);
  const visibleMessages = useMemo(() => messages.filter((message) => message.offsetSeconds <= currentTime + 0.35), [messages, currentTime]);

  useEffect(() => {
    chatRef.current?.scrollTo({ top: chatRef.current.scrollHeight, behavior: 'smooth' });
  }, [visibleMessages.length]);

  function seek(seconds: number) {
    if (!videoRef.current) return;
    videoRef.current.currentTime = seconds;
    setCurrentTime(seconds);
    void videoRef.current.play();
  }

  return (
    <AppLayout title={`بازپخش کلاس — ${classTitle}`}>
      <div className="page-stack">
        <section className="section-header">
          <div><h2>{recording.title}</h2><p>{classTitle} · ضبط شده در {recording.startedAt}</p></div>
          <Link href={`/school/online-classes/${classId}/logs`} className="btn btn-ghost"><i className="bi bi-arrow-right" /> حضور و ضبط‌ها</Link>
        </section>

        <div style={{ direction: 'ltr', display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(280px, 340px)', minHeight: 'min(70vh, 720px)', borderRadius: 14, overflow: 'hidden', background: '#080d18' }}>
          <main style={{ padding: '0.75rem', display: 'flex', alignItems: 'center', justifyContent: 'center', minWidth: 0 }}>
            <video ref={videoRef} src={recording.streamUrl} controls playsInline preload="metadata" onTimeUpdate={(event) => setCurrentTime(event.currentTarget.currentTime)} style={{ width: '100%', maxHeight: '68vh', borderRadius: 10, background: '#000' }} />
          </main>
          <aside style={{ direction: 'rtl', background: '#fff', display: 'flex', flexDirection: 'column', minHeight: 0 }}>
            <header style={{ padding: '0.8rem', borderBottom: '1px solid #e2e8f0' }}><strong>گفتگوی زمان ضبط</strong><small style={{ color: '#64748b', display: 'block', marginTop: '0.2rem' }}>{visibleMessages.length} از {messages.length} پیام · {clock(currentTime)}</small></header>
            <div ref={chatRef} style={{ background: '#f8fafc', flex: 1, minHeight: 160, overflowY: 'auto', padding: '0.7rem', display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
              {messages.length === 0 && <p style={{ color: '#94a3b8', textAlign: 'center', margin: 'auto', fontSize: '0.78rem' }}>در زمان این ضبط پیام عمومی ثبت نشده است.</p>}
              {visibleMessages.map((message) => <button key={message.id} type="button" onClick={() => seek(message.offsetSeconds)} style={{ alignSelf: 'stretch', background: 'transparent', border: 0, textAlign: 'right', cursor: 'pointer', padding: 0 }}>
                <small style={{ color: '#64748b', display: 'flex', gap: '0.35rem', marginBottom: '0.15rem' }}><strong style={{ color: message.isHost ? '#2563eb' : '#475569' }}>{message.name}</strong><span>{clock(message.offsetSeconds)}</span></small>
                <span style={{ background: message.isHost ? '#eff6ff' : '#fff', border: `1px solid ${message.isHost ? '#bfdbfe' : '#e2e8f0'}`, borderRadius: '10px 10px 3px 10px', color: '#334155', display: 'block', fontSize: '0.73rem', lineHeight: 1.7, padding: '0.45rem 0.55rem' }}>{message.body}</span>
              </button>)}
            </div>
            <div style={{ borderTop: '1px solid #e2e8f0', color: '#64748b', fontSize: '0.65rem', padding: '0.6rem', textAlign: 'center' }}>برای رفتن به زمان هر پیام، روی همان پیام بزنید.</div>
          </aside>
        </div>
      </div>
    </AppLayout>
  );
}
