/* Modal de pago del alumno: transferencia + comprobante (incluye adelantos) */

const PaymentModal = ({ open, onClose, payment, theme, onPaymentUpdated, student, studentCode, studentUuid }) => {
  const [step, setStep] = React.useState(1);
  const [file, setFile] = React.useState(null);
  const [busy, setBusy] = React.useState(false);
  const [pdfBusy, setPdfBusy] = React.useState(false);
  const [error, setError] = React.useState('');
  const fileRef = React.useRef(null);

  React.useEffect(() => {
    if (open) {
      setStep(1);
      setFile(null);
      setError('');
    }
  }, [open, payment?.key]);

  if (!payment) return null;

  if (payment.hideAmount && !payment.advancePay) {
    return (
      <Modal open={open} onClose={onClose} theme={theme} width={480}>
        <div style={{ padding: 24 }}>
          <h3 style={{ fontFamily: 'Bebas Neue, sans-serif', fontSize: 24, color: theme.text, margin: '0 0 12px' }}>
            MENSUALIDAD {payment.name?.toUpperCase()}
          </h3>
          <p style={{ fontSize: 14, color: theme.textDim, fontFamily: 'Inter, sans-serif', lineHeight: 1.5 }}>
            Este mes aún no inicia su periodo de cobro. La tarifa se mostrará cuando llegue la fecha según el calendario de la academia.
          </p>
          <Btn theme={theme} kind="soft" onClick={onClose} style={{ marginTop: 16 }}>Cerrar</Btn>
        </div>
      </Modal>
    );
  }

  const canUpload = ['pendiente', 'vencido', 'rechazado', 'urgente'].includes(payment.status);
  const waitingReview = payment.status === 'en_revision' || payment.status === 'revision';
  const isPaid = payment.status === 'pagado';
  const rejectionNote = payment.adminNotes && canUpload && !waitingReview;
  const ref = `MEN-${payment.name?.toUpperCase()}-${String(studentCode).replace(/^TEC-?/i, '')}`;
  const calendarYear = payment.calendarYear || new Date().getFullYear();
  const monthIndex = payment.monthIndex;
  const concept = payment.concept
    || (typeof mensualidadConceptForMonth === 'function'
      ? mensualidadConceptForMonth(calendarYear, monthIndex)
      : `Mensualidad ${payment.name} ${calendarYear}`);
  const isRealPaymentId = payment.paymentId && !String(payment.paymentId).startsWith('demo-') && !String(payment.paymentId).startsWith('mock-');

  const handleSubmitReceipt = async () => {
    if (!file) {
      setError('Selecciona tu comprobante.');
      return;
    }
    setBusy(true);
    setError('');
    try {
      let newPaymentId = payment.paymentId;

      if (isSupabaseReady() && studentCode) {
        const result = await uploadPaymentReceiptByCode({
          studentCode,
          concept,
          file,
          year: calendarYear,
          monthIndex,
          amount: payment.amt,
        });
        newPaymentId = result.paymentId;
      } else if (isSupabaseReady() && studentUuid != null && monthIndex != null && monthIndex >= 0) {
        await ensurePaymentForBillingMonth(studentUuid, calendarYear, monthIndex, {
          studentCode,
          amount: payment.amt,
        });
      } else if (isSupabaseReady() && isRealPaymentId) {
        await uploadPaymentReceipt({ paymentId: payment.paymentId, file });
        newPaymentId = payment.paymentId;
      } else if (typeof window.pushMockComprobante === 'function') {
        window.pushMockComprobante({
          id: 'mock-' + Date.now(),
          concept,
          amount: payment.amt,
          due_date: '2026-06-05',
          receipt_path: 'mock/local',
          receipt_uploaded_at: new Date().toISOString(),
          transfer_reference: ref,
          students: { code: studentCode, full_name: 'Alumno demo' },
        });
      }

      onPaymentUpdated?.({
        ...payment,
        status: 'revision',
        paymentId: newPaymentId,
        adminNotes: null,
      });
      if (typeof notifyPaymentsChanged === 'function') notifyPaymentsChanged();
      if (typeof notifyComprobantesChanged === 'function') notifyComprobantesChanged();
      if (typeof window.dispatchNotificationsChanged === 'function') window.dispatchNotificationsChanged();
      if (typeof notifyComprobantesChanged === 'function') notifyComprobantesChanged();
      setStep(3);
    } catch (e) {
      setError(e.message || 'No se pudo subir el comprobante');
    }
    setBusy(false);
  };

  const handleDownloadPdf = async () => {
    if (typeof exportPortalCalendarMonthReceiptPdf !== 'function') {
      alert('Módulo PDF no cargado. Recarga la página (F5).');
      return;
    }
    const alumno = student || (studentCode ? { code: studentCode, name: 'Alumno' } : null);
    if (!alumno) {
      alert('No se encontraron datos del alumno para el comprobante.');
      return;
    }
    setPdfBusy(true);
    try {
      const settings = await fetchAcademySettings();
      await exportPortalCalendarMonthReceiptPdf(alumno, payment, settings, theme);
    } catch (e) {
      alert(e.message || 'No se pudo generar el PDF');
    }
    setPdfBusy(false);
  };

  return (
    <Modal open={open} onClose={onClose} theme={theme} width={520}>
      <div style={{ padding: 24, borderBottom: `1px solid ${theme.border}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h3 style={{ fontFamily: 'Bebas Neue, sans-serif', fontSize: 26, color: theme.text, letterSpacing: 1, margin: 0, fontWeight: 400 }}>
          MENSUALIDAD {payment.name?.toUpperCase()} {calendarYear}
        </h3>
        <button type="button" onClick={onClose} style={{ width: 32, height: 32, borderRadius: 8, background: theme.bgInput, border: `1px solid ${theme.border}`, color: theme.text, cursor: 'pointer', display: 'grid', placeItems: 'center' }}>
          <Icon name="x" size={14} />
        </button>
      </div>

      <div style={{ padding: 24, display: 'grid', gap: 14 }}>
        {payment.advancePay && canUpload && (
          <div style={{ padding: 12, borderRadius: 10, background: `${theme.info}15`, border: `1px solid ${theme.info}44`, fontSize: 13, fontFamily: 'Inter, sans-serif', color: theme.text }}>
            <strong>Pago anticipado:</strong>{' '}
            {payment.billingRangeLabel
              ? `tarifa base sin recargo (${payment.billingRangeLabel})`
              : 'tarifa base sin recargo'}
            . Sube tu comprobante; el administrador lo revisará en Verificar comprobantes.
          </div>
        )}

        {!payment.advancePay && canUpload && payment.billingTierLabel && (
          <div style={{ padding: 12, borderRadius: 10, background: `${theme.bgInput}`, border: `1px solid ${theme.border}`, fontSize: 13, fontFamily: 'Inter, sans-serif', color: theme.text, lineHeight: 1.5 }}>
            <strong>Tarifa hoy:</strong> día {payment.billingDayUsed} del mes — {payment.billingTierLabel}
            {payment.billingRangeLabel ? ` (${payment.billingRangeLabel})` : ''}.
            {payment.feeFormula && (
              <div style={{ fontSize: 11, color: theme.textDim, marginTop: 6 }}>{payment.feeFormula}</div>
            )}
          </div>
        )}

        {payment.prorated && payment.prorationLabel && (
          <div style={{ padding: 12, borderRadius: 10, background: `${theme.primary}12`, border: `1px solid ${theme.primary}44`, fontSize: 13, fontFamily: 'Inter, sans-serif', color: theme.text, lineHeight: 1.5 }}>
            <strong>Mes de ingreso — cobro proporcional:</strong> se cobraron <strong>{payment.prorationLabel}</strong> de este mes
            {payment.baseMonthlyFee > Number(payment.amt) && (
              <span style={{ color: theme.textDim }}> (mensualidad completa ${Number(payment.baseMonthlyFee).toLocaleString('es-MX')})</span>
            )}.
          </div>
        )}

        <div style={{ padding: 18, borderRadius: 12, background: `linear-gradient(135deg, ${theme.primary}22, ${theme.bgInput})`, border: `1px solid ${theme.primary}44`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <div style={{ fontSize: 10, color: theme.textMute, letterSpacing: 1.5, fontWeight: 700, textTransform: 'uppercase', fontFamily: 'Inter, sans-serif' }}>Monto a pagar</div>
            <div style={{ fontFamily: 'Bebas Neue, sans-serif', fontSize: 48, color: theme.text, letterSpacing: 1, lineHeight: 1, marginTop: 4 }}>
              ${Number(payment.amt).toLocaleString('es-MX')}
            </div>
            {payment.concept && (
              <div style={{ fontSize: 11, color: theme.textDim, marginTop: 6, fontFamily: 'Inter, sans-serif' }}>{payment.concept}</div>
            )}
          </div>
          <StatusPill status={waitingReview ? 'en_revision' : payment.status} theme={theme} />
        </div>

        {isPaid && (
          <>
            <p style={{ color: theme.textDim, fontSize: 13, fontFamily: 'Inter, sans-serif', margin: 0 }}>
              Pago confirmado por el administrador. ¡Gracias!
            </p>
            <Btn
              theme={theme}
              kind="soft"
              icon="download"
              onClick={handleDownloadPdf}
              disabled={pdfBusy}
              style={{ width: '100%' }}
            >
              {pdfBusy ? 'Generando PDF…' : 'Descargar comprobante PDF'}
            </Btn>
          </>
        )}

        {waitingReview && (
          <div style={{ padding: 14, borderRadius: 10, background: `${theme.warning}15`, border: `1px solid ${theme.warning}44` }}>
            <p style={{ color: theme.text, fontSize: 13, fontFamily: 'Inter, sans-serif', margin: 0 }}>
              Tu comprobante está <strong>pendiente de verificación</strong>. Te avisaremos cuando sea aceptado o si debes volver a subirlo.
            </p>
          </div>
        )}

        {(payment.status === 'rechazado' || rejectionNote) && (
          <div style={{ padding: 14, borderRadius: 10, background: `${theme.danger}12`, border: `1px solid ${theme.danger}44` }}>
            <p style={{ color: theme.danger, fontSize: 13, fontFamily: 'Inter, sans-serif', margin: 0, fontWeight: 600 }}>Comprobante no aceptado</p>
            {payment.adminNotes && (
              <p style={{ color: theme.textDim, fontSize: 13, marginTop: 6, fontFamily: 'Inter, sans-serif' }}>{payment.adminNotes}</p>
            )}
            <p style={{ color: theme.textDim, fontSize: 12, marginTop: 8, fontFamily: 'Inter, sans-serif' }}>
              La mensualidad sigue pendiente. Sube un nuevo comprobante después de transferir.
            </p>
          </div>
        )}

        {canUpload && step === 1 && (
          <>
            <TransferBankPanel theme={theme} purpose="mensualidad" reference={ref} amount={payment.amt} />
            <Btn theme={theme} icon="arrowRight" onClick={() => setStep(2)} style={{ width: '100%' }}>Ya transferí — subir comprobante</Btn>
          </>
        )}

        {canUpload && step === 2 && (
          <>
            <input ref={fileRef} type="file" accept="image/png,image/jpeg,image/webp,application/pdf" style={{ display: 'none' }}
              onChange={e => { setFile(e.target.files?.[0] || null); setError(''); }} />
            <div onClick={() => fileRef.current?.click()} style={{ border: `2px dashed ${theme.primary}55`, borderRadius: 12, padding: 32, textAlign: 'center', cursor: 'pointer', background: `${theme.primary}08` }}>
              <Icon name="upload" size={32} style={{ color: theme.primary, marginBottom: 8 }} />
              <div style={{ fontWeight: 600, fontFamily: 'Inter, sans-serif' }}>{file ? file.name : 'Seleccionar comprobante'}</div>
            </div>
            {error && <div style={{ color: theme.danger, fontSize: 13 }}>{error}</div>}
            <div style={{ display: 'flex', gap: 8 }}>
              <Btn theme={theme} kind="ghost" onClick={() => setStep(1)} disabled={busy}>Atrás</Btn>
              <Btn theme={theme} icon="upload" onClick={handleSubmitReceipt} disabled={busy} style={{ flex: 1 }}>
                {busy ? 'Enviando…' : 'Enviar comprobante'}
              </Btn>
            </div>
          </>
        )}

        {canUpload && step === 3 && (
          <div style={{ textAlign: 'center', padding: 16 }}>
            <Icon name="check" size={40} style={{ color: theme.success, marginBottom: 12 }} />
            <p style={{ fontFamily: 'Inter, sans-serif', color: theme.text }}>
              Comprobante enviado. El administrador lo revisará y confirmará tu pago.
            </p>
            <Btn theme={theme} onClick={onClose} style={{ marginTop: 16 }}>Cerrar</Btn>
          </div>
        )}
      </div>
    </Modal>
  );
};

Object.assign(window, { PaymentModal });
