// js/components/widgets/clientes/CreditRefundModal.jsx
// [v224.112 2026-06-02] Modal "Estornar crédito" — devolução de dinheiro REAL.
// Chama refund_client_credit_v1 (admin only): decrementa credit_balance (via movement='estorno')
// + INSERT gastos (categoria "Estorno crédito cliente") + admin_audit_log. Idempotente.
// Distinto do "− Remover" (correção cadastro · sem reflexo contábil).
// Props: refundModal ({clientId, clientName, maxValue}), setRefundModal, setClients, setCreditHistory
// Deps runtime: window.Modal, window.sb, window.fmt, window.toast, window.Sentry, window.genIdempotencyKey
(function(){
  'use strict';
  const {useState, useRef} = React;

  // Alinhado ao CHECK gastos_payment_method_check (NAO incluir 'Outro')
  const PAYMENT_METHODS = ['Pix','Dinheiro','Transferência','Cartão','Boleto'];

  function CreditRefundModal(props){
    const refundModal = props.refundModal;
    const setRefundModal = props.setRefundModal || function(){};
    const setClients = props.setClients || function(){};
    const setCreditHistory = props.setCreditHistory || function(){};

    const Modal = window.Modal;
    if (!Modal) {
      console.error('[CreditRefundModal] Modal faltando');
      if (window.Sentry) try{ window.Sentry.captureMessage('[v224.112 CreditRefundModal] Modal missing', 'error'); }catch(_){}
      return null;
    }

    const [value, setValue] = useState('');
    const [reason, setReason] = useState('');
    const [paymentMethod, setPaymentMethod] = useState('Pix');
    const [saving, setSaving] = useState(false);
    const inFlightRef = useRef(false);

    if (!refundModal) return null;

    const fmt = (typeof window.fmt === 'function') ? window.fmt : function(v){ return 'R$ '+Number(v||0).toFixed(2); };
    const toast = (typeof window.toast === 'function') ? window.toast : function(m){ console.log('[toast]', m); };
    const maxValue = Number(refundModal.maxValue || 0);

    async function handleSave(){
      if (inFlightRef.current) return;
      const val = Number(value);
      if (!val || val <= 0) { toast('⚠ Valor inválido'); return; }
      if (val > maxValue + 0.001) { toast('⚠ Valor maior que saldo disponível ('+fmt(maxValue)+')'); return; }
      if (!reason || reason.trim().length < 3) { toast('⚠ Motivo obrigatório (mín 3 caracteres)'); return; }
      if (!confirm('Confirmar estorno de '+fmt(val)+' pra '+refundModal.clientName+' via '+paymentMethod+'?\n\nIsso gera um GASTO REAL no caixa e decrementa o crédito do cliente.')) return;

      inFlightRef.current = true;
      setSaving(true);
      try {
        const idemKey = (typeof window.genIdempotencyKey === 'function')
          ? window.genIdempotencyKey()
          : (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function' ? crypto.randomUUID() : null);

        const { data, error } = await window.sb.rpc('refund_client_credit_v1', {
          p_client_id: refundModal.clientId,
          p_value: val,
          p_reason: reason.trim(),
          p_payment_method: paymentMethod,
          p_idem_key: idemKey
        });

        if (error) {
          toast('❌ '+error.message);
          if (window.Sentry) window.Sentry.captureException(new Error(error.message), { extra: { context: 'refund_credit', clientId: refundModal.clientId, value: val } });
          return;
        }
        if (data && data.status === 'duplicate') {
          toast('ℹ Estorno já registrado (idempotency).');
          setRefundModal(null);
          return;
        }

        // Reload histórico + saldo do cliente
        const { data: hist } = await window.sb.from('client_credit_history')
          .select('*').eq('client_id', refundModal.clientId)
          .order('created_at', { ascending: false }).limit(50);
        setCreditHistory(Array.isArray(hist) ? hist : []);
        const newBal = (data && typeof data.new_balance !== 'undefined') ? Number(data.new_balance) : 0;
        setClients(function(prev){
          return prev.map(function(c){
            return c.id === refundModal.clientId
              ? Object.assign({}, c, { creditBalance: newBal, credit_balance: newBal })
              : c;
          });
        });
        toast('💸 Estornado '+fmt(val)+' · novo saldo '+fmt(newBal));
        setRefundModal(null);
      } catch(e) {
        toast('❌ '+(e.message || 'Erro'));
        if (window.Sentry) window.Sentry.captureException(e, { extra: { context: 'refund_credit_exception', clientId: refundModal.clientId } });
      } finally {
        inFlightRef.current = false;
        setSaving(false);
      }
    }

    return (
      <Modal title={'💸 Estornar Crédito — '+refundModal.clientName} onClose={function(){ setRefundModal(null); }}>
        <div style={{display:'flex',flexDirection:'column',gap:12}}>
          <div style={{background:'#FEF3C7',border:'1px solid #F59E0B',borderRadius:6,padding:'8px 12px',fontSize:12,color:'#92400E'}}>
            ⚠️ Estornar gera um <strong>GASTO REAL</strong> no caixa (categoria "Estorno crédito cliente") + decrementa o saldo do cliente. Use só ao devolver dinheiro de verdade. Pra corrigir cadastro errado, use o botão "− Remover" (sem reflexo contábil).
          </div>
          <div className="form-group">
            <label>Valor a estornar (R$) · máx {fmt(maxValue)}</label>
            <input type="number" min="0.01" step="0.01" max={maxValue} value={value}
              onChange={function(e){ setValue(e.target.value); }}
              placeholder="0,00" autoFocus/>
          </div>
          <div className="form-group">
            <label>Forma de pagamento ao cliente</label>
            <select value={paymentMethod} onChange={function(e){ setPaymentMethod(e.target.value); }}>
              {PAYMENT_METHODS.map(function(m){ return <option key={m} value={m}>{m}</option>; })}
            </select>
          </div>
          <div className="form-group">
            <label>Motivo (obrigatório · mín 3 chars)</label>
            <input type="text" value={reason}
              onChange={function(e){ setReason(e.target.value); }}
              placeholder="Ex: cliente pediu devolução · não vai usar mais"/>
          </div>
          <div style={{display:'flex',gap:10,marginTop:8,justifyContent:'flex-end'}}>
            <button className="btn-outline" onClick={function(){ setRefundModal(null); }} disabled={saving}>Cancelar</button>
            <button className="btn-danger" disabled={saving} onClick={handleSave}>
              {saving ? '⏳ Processando...' : '💸 Confirmar estorno'}
            </button>
          </div>
        </div>
      </Modal>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.widgets = window.ZNX.widgets || {};
  window.ZNX.widgets.clientes = window.ZNX.widgets.clientes || {};
  window.ZNX.widgets.clientes.CreditRefundModal = CreditRefundModal;
})();
