/* Panel admin: alumnos registrados + interesados + PDF estilo comprobante */

const ComprobanteStylePdfBtn = ({ theme, onClick, busy, label = 'PDF' }) => (
  <button
    type="button"
    onClick={onClick}
    disabled={busy}
    title="Descargar comprobante PDF"
    style={{
      display: 'inline-flex', alignItems: 'center', gap: 5, flexShrink: 0,
      padding: '6px 11px', borderRadius: 8, cursor: busy ? 'wait' : 'pointer',
      background: 'linear-gradient(180deg, #1e293b 0%, #0f172a 100%)',
      border: `2px solid ${theme?.warning || '#eab308'}`,
      color: '#fef08a', fontSize: 10, fontWeight: 800, letterSpacing: 0.4,
      fontFamily: 'Inter, sans-serif', textTransform: 'uppercase',
      boxShadow: '0 0 14px rgba(234,179,8,0.35)',
      opacity: busy ? 0.7 : 1,
    }}
  >
    <Icon name="doc" size={13} />
    {busy ? '…' : label}
  </button>
);

const InterestRegistrationsPanel = ({
  theme,
  kind,
  entityId,
  entity,
  studentRows = [],
  loadingStudents = false,
  onRemoveStudent,
  reload,
}) => {
  const [interested, setInterested] = React.useState([]);
  const [loadingInterested, setLoadingInterested] = React.useState(false);
  const [pdfBusyId, setPdfBusyId] = React.useState(null);
  const [rosterBusy, setRosterBusy] = React.useState(false);

  const isEvent = kind === 'event';
  const studentLabel = isEvent ? 'Alumnos con asistencia confirmada' : 'Alumnos registrados en el aviso';
  const interestedLabel = 'Interesados (no alumnos)';
  const dateKey = isEvent ? 'confirmed_at' : 'registered_at';

  React.useEffect(() => {
    if (!entityId || entityId === 'new') {
      setInterested([]);
      return;
    }
    let cancelled = false;
    setLoadingInterested(true);
    const args = isEvent ? { eventId: entityId } : { announcementId: entityId };
    fetchInterestedLeadsForContext(args)
      .then(rows => { if (!cancelled) setInterested(rows || []); })
      .catch(() => { if (!cancelled) setInterested([]); })
      .finally(() => { if (!cancelled) setLoadingInterested(false); });
    return () => { cancelled = true; };
  }, [entityId, isEvent, reload]);

  const entityPayload = {
    title: entity?.title,
    starts_at: entity?.starts_at,
    location: entity?.location,
  };

  const downloadStudentPdf = async (row) => {
    if (typeof exportInterestRegistrationReceiptPdf !== 'function') {
      alert('Módulo PDF no cargado. Recarga la página.');
      return;
    }
    setPdfBusyId(row.id);
    try {
      const settings = typeof fetchAcademySettings === 'function'
        ? await fetchAcademySettings()
        : {};
      let extra = null;
      if (row.student_id && typeof fetchStudentBriefForReceipt === 'function') {
        extra = await fetchStudentBriefForReceipt(row.student_id);
      }
      await exportInterestRegistrationReceiptPdf({
        kind,
        entity: entityPayload,
        registration: row,
        studentExtra: extra,
        settings,
        theme,
      });
    } catch (e) {
      alert(e.message || 'No se pudo generar el PDF');
    }
    setPdfBusyId(null);
  };

  const downloadRosterPdf = async () => {
    if (typeof exportInterestRegistrationsRosterPdf !== 'function') {
      alert('Módulo PDF no cargado. Recarga la página.');
      return;
    }
    setRosterBusy(true);
    try {
      const settings = typeof fetchAcademySettings === 'function'
        ? await fetchAcademySettings()
        : {};
      await exportInterestRegistrationsRosterPdf({
        kind,
        entity: entityPayload,
        studentRegistrations: studentRows,
        interestedLeads: interested,
        settings,
      });
    } catch (e) {
      alert(e.message || 'No se pudo generar el listado PDF');
    }
    setRosterBusy(false);
  };

  const total = studentRows.length + interested.length;
  const loading = loadingStudents || loadingInterested;

  return (
    <div style={{ borderTop: `1px solid ${theme.border}`, paddingTop: 16, display: 'grid', gap: 16 }}>
      <div style={{
        display: 'flex', flexWrap: 'wrap', gap: 10, alignItems: 'center', justifyContent: 'space-between',
      }}>
        <div style={{
          fontSize: 12, fontWeight: 700, color: theme.textMute, fontFamily: 'Inter, sans-serif',
          letterSpacing: 0.5, textTransform: 'uppercase',
        }}>
          Registros de interés ({total})
        </div>
        {entityId && entityId !== 'new' && total > 0 && (
          <ComprobanteStylePdfBtn
            theme={theme}
            busy={rosterBusy}
            label="PDF listado"
            onClick={downloadRosterPdf}
          />
        )}
      </div>

      <div>
        <div style={{
          fontSize: 11, fontWeight: 700, color: theme.textDim, marginBottom: 8,
          fontFamily: 'Inter, sans-serif', textTransform: 'uppercase',
        }}>
          {studentLabel} ({studentRows.length})
        </div>
        {loadingStudents ? (
          <div style={{ fontSize: 13, color: theme.textDim }}>Cargando alumnos…</div>
        ) : studentRows.length === 0 ? (
          <div style={{ fontSize: 13, color: theme.textDim }}>
            Aún no hay alumnos registrados desde el landing.
          </div>
        ) : (
          <div style={{ display: 'grid', gap: 8, maxHeight: 220, overflowY: 'auto' }}>
            {studentRows.map(c => (
              <div key={c.id} style={{
                display: 'flex', alignItems: 'center', gap: 10, padding: 10, borderRadius: 8,
                background: theme.bgInput, border: `1px solid ${theme.border}`,
              }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 700, fontSize: 13 }}>{c.student_code}</div>
                  <div style={{ fontSize: 12, color: theme.textDim }}>{c.student_name || '—'}</div>
                  <div style={{ fontSize: 11, color: theme.textMute }}>
                    {c[dateKey] ? new Date(c[dateKey]).toLocaleString('es-MX') : '—'}
                  </div>
                </div>
                <ComprobanteStylePdfBtn
                  theme={theme}
                  busy={pdfBusyId === c.id}
                  onClick={() => downloadStudentPdf(c)}
                />
                {onRemoveStudent && (
                  <Btn theme={theme} kind="ghost" size="sm" onClick={() => onRemoveStudent(c.id)}>Quitar</Btn>
                )}
              </div>
            ))}
          </div>
        )}
      </div>

      <div>
        <div style={{
          fontSize: 11, fontWeight: 700, color: theme.textDim, marginBottom: 8,
          fontFamily: 'Inter, sans-serif', textTransform: 'uppercase',
        }}>
          {interestedLabel} ({interested.length})
        </div>
        {loadingInterested ? (
          <div style={{ fontSize: 13, color: theme.textDim }}>Cargando interesados…</div>
        ) : interested.length === 0 ? (
          <div style={{ fontSize: 13, color: theme.textDim }}>
            Nadie ha enviado el formulario «No soy alumno» para este {isEvent ? 'evento' : 'aviso'}.
          </div>
        ) : (
          <div style={{ display: 'grid', gap: 8, maxHeight: 220, overflowY: 'auto' }}>
            {interested.map(l => (
              <div key={l.id} style={{
                padding: 10, borderRadius: 8,
                background: theme.bgInput, border: `1px solid ${theme.border}`,
              }}>
                <div style={{ fontWeight: 700, fontSize: 13 }}>{l.name || '—'}</div>
                <div style={{ fontSize: 12, color: theme.textDim, marginTop: 2 }}>
                  {l.phone || '—'}{l.email ? ` · ${l.email}` : ''}
                </div>
                {l.message && (
                  <div style={{ fontSize: 11, color: theme.textMute, marginTop: 4, lineHeight: 1.4 }}>
                    {l.message}
                  </div>
                )}
                <div style={{ fontSize: 11, color: theme.textMute, marginTop: 4 }}>
                  {l.created_at ? new Date(l.created_at).toLocaleString('es-MX') : '—'}
                  {l.status ? ` · ${l.status}` : ''}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {loading && total === 0 && (
        <div style={{ fontSize: 12, color: theme.textMute }}>Actualizando listados…</div>
      )}

      <p style={{ fontSize: 12, color: theme.textMute, margin: 0, fontFamily: 'Inter, sans-serif' }}>
        Cada alumno puede descargar un comprobante PDF individual. «PDF listado» incluye todos los alumnos e interesados.
      </p>
    </div>
  );
};

Object.assign(window, { ComprobanteStylePdfBtn, InterestRegistrationsPanel });
