/* Detalle de orden del alumno + re-subir comprobante si fue rechazada */

const AlumnoOrderModal = ({ open, onClose, order, theme, onOrderUpdated, studentCode, studentName }) => {
  const [file, setFile] = React.useState(null);
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState('');
  const fileRef = React.useRef(null);

  React.useEffect(() => {
    if (open) { setFile(null); setError(''); }
  }, [open, order?.id]);

  if (!order) return null;

  const uploadCode = studentCode || order.studentCode || '';
  const canReupload = ['rechazado', 'pendiente'].includes(order.s)
    && order.orderId
    && (order.phone || uploadCode);
  const waiting = order.s === 'en_revision';
  const confirmed = order.s === 'confirmado' || order.s === 'entregado';

  const handleReupload = async () => {
    if (!file) { setError('Selecciona el comprobante.'); return; }
    setBusy(true);
    setError('');
    try {
      if (isSupabaseReady() && order.orderId && !String(order.orderId).startsWith('mock-') && !String(order.orderId).startsWith('local-')) {
        await uploadOrderReceipt({
          orderId: order.orderId,
          phone: order.phone || '',
          studentCode: uploadCode,
          file,
        });
        if (typeof notifyComprobantesChanged === 'function') notifyComprobantesChanged();
        if (typeof notifyOrdersChanged === 'function') notifyOrdersChanged();
        window.dispatchNotificationsChanged?.();
      } else if (typeof window.pushMockOrdenTienda === 'function') {
        window.pushMockOrdenTienda({
          id: 'mock-ord-' + Date.now(),
          order_number: order.n,
          total: order.a,
          receipt_uploaded_at: new Date().toISOString(),
          guest_student_code: studentCode || '',
          guest_student_name: studentName || '',
          guest_phone: order.phone,
          order_items: [{ product_name: order.p, qty: 1, unit_price: order.a }],
        });
      }
      onOrderUpdated?.({ ...order, s: 'en_revision', adminNotes: null, phone: order.phone });
      onClose();
    } catch (e) {
      setError(e.message || 'Error al subir');
    }
    setBusy(false);
  };

  return (
    <Modal open={open} onClose={onClose} theme={theme} width={500}>
      <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, margin: 0, letterSpacing: 1 }}>ORDEN {order.n}</h3>
        <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 }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
          <div style={{ width: 56, height: 56, borderRadius: 10, background: `${theme.primary}22`, color: theme.primary, display: 'grid', placeItems: 'center' }}>
            <Icon name={order.i || 'cart'} size={24} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 700, fontFamily: 'Inter, sans-serif' }}>{order.p}</div>
            <div style={{ fontSize: 12, color: theme.textMute, marginTop: 4 }}>{order.d}</div>
          </div>
          <StatusPill status={order.s} theme={theme} />
        </div>
        <div style={{ fontFamily: 'Bebas Neue, sans-serif', fontSize: 36, color: theme.primary }}>${order.a} MXN</div>

        {waiting && (
          <p style={{ color: theme.textDim, fontSize: 13, fontFamily: 'Inter, sans-serif', margin: 0 }}>
            Tu comprobante está <strong>Pendiente</strong> de verificación por el administrador.
          </p>
        )}
        {confirmed && (
          <p style={{ color: theme.success, fontSize: 13, fontFamily: 'Inter, sans-serif', margin: 0 }}>
            Orden confirmada. Te contactaremos para la entrega.
          </p>
        )}
        {(order.s === 'rechazado' || order.s === 'pendiente') && (
          <div style={{ padding: 14, borderRadius: 10, background: `${order.s === 'rechazado' ? theme.danger : theme.warning}12`, border: `1px solid ${order.s === 'rechazado' ? theme.danger : theme.warning}44` }}>
            <p style={{ color: order.s === 'rechazado' ? theme.danger : theme.warning, fontWeight: 600, margin: 0, fontSize: 13 }}>
              {order.s === 'rechazado' ? 'Comprobante rechazado o orden declinada' : 'Pendiente de comprobante'}
            </p>
            {order.adminNotes && <p style={{ color: theme.textDim, fontSize: 13, marginTop: 6 }}>{order.adminNotes}</p>}
            <p style={{ color: theme.textDim, fontSize: 12, marginTop: 8 }}>
              {order.s === 'rechazado'
                ? 'Sube un nuevo comprobante después de transferir.'
                : 'Realiza la transferencia y sube tu comprobante aquí.'}
            </p>
          </div>
        )}

        {canReupload && (
          <>
            <TransferBankPanel theme={theme} purpose="tienda" reference={order.transferRef || order.n} amount={order.a} />
            <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(''); }} />
            <Btn theme={theme} icon="upload" onClick={() => fileRef.current?.click()} kind="soft" style={{ width: '100%' }}>
              {file ? file.name : 'Elegir nuevo comprobante'}
            </Btn>
            {error && <div style={{ color: theme.danger, fontSize: 13 }}>{error}</div>}
            <Btn theme={theme} icon="check" onClick={handleReupload} disabled={busy} style={{ width: '100%' }}>
              {busy ? 'Enviando…' : 'Enviar comprobante'}
            </Btn>
          </>
        )}
      </div>
    </Modal>
  );
};

Object.assign(window, { AlumnoOrderModal });
