// src/features/admin/ui/admin-transcript-modal.jsx
//
// Admin-only modal that shows the AI summary + raw transcript for a
// completed lesson. Mounted from the admin schedule row's "Transcript"
// button — appears only for bookings with audio.
//
// Status states:
//   - null               → "No recording" (no audio file uploaded yet)
//   - 'pending'          → "Queued — Process now" button (POSTs /api/transcribe-lesson)
//   - 'processing'       → "In progress…" with refresh
//   - 'done'             → render summary + transcript
//   - 'error'            → show error + "Retry" button (clears status, POSTs again)
//
// "Process now" / "Retry" need an admin Bearer JWT — we pull it from
// the active Supabase session.

(function () {
  const AdminTranscriptModal = ({ booking, onClose }) => {
    const data = window.useAdminData();
    const [busy, setBusy]       = React.useState(false);
    const [errMsg, setErrMsg]   = React.useState('');
    const [b, setB]             = React.useState(booking);

    // Re-read the current row from data.bookings each render so an
    // out-of-band refresh (e.g. realtime / status flip) is reflected.
    React.useEffect(() => {
      const fresh = (data.bookings || []).find(x => x.id === booking.id);
      if (fresh) setB(fresh);
    }, [data.bookings, booking.id]);

    async function callTranscribe() {
      setBusy(true);
      setErrMsg('');
      try {
        const { data: sess } = await window.supa.auth.getSession();
        const token = sess?.session?.access_token;
        if (!token) throw new Error('Not signed in');
        const r = await fetch('/api/transcribe-lesson', {
          method: 'POST',
          headers: { 'content-type': 'application/json', Authorization: `Bearer ${token}` },
          body: JSON.stringify({ bookingId: b.id }),
        });
        const j = await r.json().catch(() => ({}));
        if (!r.ok || !j.ok) throw new Error(j.error || `HTTP ${r.status}`);
        const result = (j.results && j.results[0]) || {};
        if (result.status === 'error') throw new Error(result.error || 'transcription failed');
        // Refresh admin cache from server so the modal redraws with the
        // new transcript/summary/status.
        if (typeof data.refreshBookings === 'function') {
          await data.refreshBookings();
        } else if (typeof data.refresh === 'function') {
          await data.refresh();
        }
      } catch (e) {
        setErrMsg(e.message || String(e));
      } finally {
        setBusy(false);
      }
    }

    const at  = b.scheduledAt ? new Date(b.scheduledAt) : null;
    const status = b.transcriptStatus;
    const hasAudio = !!b.audioStoragePath;

    return (
      <div onClick={onClose} style={overlay}>
        <div onClick={e => e.stopPropagation()} style={dialog}>
          <div style={titleRow}>
            <div>
              <div style={{ fontFamily:"'Cormorant Garamond', serif", fontSize:24, fontWeight:700, color:'oklch(22% 0.06 265)' }}>
                Lesson recording
              </div>
              <div style={{ fontSize:13, color:'oklch(50% 0.04 265)', marginTop:2 }}>
                {b.student?.name || '—'} with {b.instructor?.name || '—'} · {at ? at.toLocaleString() : ''}
              </div>
            </div>
            <button onClick={onClose} style={closeBtn} title="Close">×</button>
          </div>

          {!hasAudio && (
            <Box>
              <div style={{ fontSize:14, color:'oklch(40% 0.04 265)' }}>
                No audio was recorded for this lesson. Recording only happens when the student or
                teacher clicks "Join meeting" from the dashboard and grants mic permission.
              </div>
            </Box>
          )}

          {hasAudio && !status && (
            <Box>
              <div style={{ fontSize:14, color:'oklch(40% 0.04 265)', marginBottom:10 }}>
                Audio uploaded but not yet queued for transcription. This usually means the lesson
                isn't marked completed yet. You can process it now.
              </div>
              <PrimaryBtn busy={busy} onClick={callTranscribe} label="Process now" />
            </Box>
          )}

          {hasAudio && status === 'pending' && (
            <Box>
              <div style={{ fontSize:14, color:'oklch(40% 0.04 265)', marginBottom:10 }}>
                Queued for transcription. Click below to process this booking right now (skips the
                queue).
              </div>
              <PrimaryBtn busy={busy} onClick={callTranscribe} label="Process now" />
            </Box>
          )}

          {hasAudio && status === 'processing' && (
            <Box>
              <div style={{ fontSize:14, color:'oklch(40% 0.04 265)' }}>
                Transcription in progress. Reload in a minute.
              </div>
            </Box>
          )}

          {hasAudio && status === 'error' && (
            <Box tone="error">
              <div style={{ fontSize:14, color:'oklch(38% 0.16 25)', marginBottom:8, fontWeight:600 }}>
                Last attempt failed
              </div>
              <div style={{ fontSize:13, color:'oklch(40% 0.1 25)', marginBottom:12, whiteSpace:'pre-wrap' }}>
                {b.transcriptError || 'Unknown error'}
              </div>
              <PrimaryBtn busy={busy} onClick={callTranscribe} label="Retry" />
            </Box>
          )}

          {hasAudio && status === 'done' && (
            <>
              <Section title="AI summary">
                <div style={{ fontSize:14, lineHeight:1.6, color:'oklch(22% 0.06 265)', whiteSpace:'pre-wrap' }}>
                  {b.aiSummary || '(no summary)'}
                </div>
              </Section>
              <Section title="Full transcript">
                <div style={{ fontSize:13, lineHeight:1.55, color:'oklch(30% 0.04 265)', whiteSpace:'pre-wrap', maxHeight:360, overflow:'auto', padding:12, background:'oklch(97% 0.005 265)', borderRadius:8 }}>
                  {b.transcript || '(no transcript)'}
                </div>
              </Section>
              {b.transcriptProcessedAt && (
                <div style={{ fontSize:11, color:'oklch(56% 0.03 265)', marginTop:8 }}>
                  Processed {new Date(b.transcriptProcessedAt).toLocaleString()}
                </div>
              )}
            </>
          )}

          {errMsg && (
            <div style={{ marginTop:14, fontSize:13, color:'oklch(38% 0.16 25)' }}>
              Error: {errMsg}
            </div>
          )}

          <div style={{ display:'flex', justifyContent:'flex-end', marginTop:18 }}>
            <button onClick={onClose} style={secondaryBtn}>Close</button>
          </div>
        </div>
      </div>
    );
  };

  const Box = ({ children, tone }) => (
    <div style={{
      background: tone === 'error' ? 'oklch(98% 0.03 25)' : 'oklch(97% 0.005 265)',
      border: tone === 'error' ? '1px solid oklch(88% 0.1 25)' : '1px solid oklch(91% 0.01 265)',
      borderRadius:10, padding:14, marginTop:10,
    }}>{children}</div>
  );

  const Section = ({ title, children }) => (
    <div style={{ marginTop:18 }}>
      <div style={{ fontSize:12, fontWeight:700, letterSpacing:'0.05em', textTransform:'uppercase', color:'oklch(40% 0.04 265)', marginBottom:8 }}>
        {title}
      </div>
      {children}
    </div>
  );

  const PrimaryBtn = ({ busy, onClick, label }) => (
    <button disabled={busy} onClick={onClick} style={{
      background:'oklch(22% 0.06 265)', color:'#fff', border:'none', borderRadius:8,
      padding:'10px 16px', fontSize:14, fontWeight:700, cursor:busy?'wait':'pointer',
      fontFamily:"'Plus Jakarta Sans', sans-serif",
    }}>{busy ? 'Working…' : label}</button>
  );

  const overlay = {
    position:'fixed', inset:0, background:'rgba(0,0,0,0.45)',
    display:'flex', alignItems:'center', justifyContent:'center', zIndex:1000, padding:20,
  };
  const dialog = {
    background:'#fff', borderRadius:14, padding:24, maxWidth:680, width:'100%',
    maxHeight:'90vh', overflow:'auto', fontFamily:"'Plus Jakarta Sans', sans-serif",
  };
  const titleRow = { display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:12, marginBottom:6 };
  const closeBtn = {
    border:'none', background:'transparent', fontSize:28, lineHeight:1, color:'oklch(50% 0.04 265)',
    cursor:'pointer', padding:0, marginLeft:8,
  };
  const secondaryBtn = {
    background:'#fff', border:'1px solid oklch(86% 0.02 265)', borderRadius:8,
    padding:'9px 16px', fontSize:13, fontWeight:600, color:'oklch(30% 0.04 265)',
    cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif",
  };

  window.AdminTranscriptModal = AdminTranscriptModal;
})();
