// js/components/widgets/Fornecedores.jsx
// Cadastro de fornecedores — CRUD completo.
// Movido de index.html em Fase 5 do refactor (2026-04-29): L6028-L6110
// Deps runtime: Modal, SmartSelect, Icon, showConfirm, dualWrite, genIdUUID (globals)
(function() {
  'use strict';
  const {useState, useEffect, useRef, useCallback, useMemo} = React;

function Fornecedores({suppliers,setSuppliers}){
  const EMPTY_SUPP={name:'',contact:'',phone:'',email:'',country:'',currency:'USD',deliveryDays:'',notes:'',products:''};
  const[modal,setModal]=useState(null);
  const[form,setForm]=useState(EMPTY_SUPP);
  // [L2-Fornecedores 2026-05-09] Busca rápida — pagina não tinha nada antes
  const[search,setSearch]=useState('');
  const filtered=useMemo(()=>{
    const q=search.trim().toLowerCase();
    if(!q)return suppliers;
    return suppliers.filter(s=>(s.name||'').toLowerCase().includes(q)||(s.contact||'').toLowerCase().includes(q)||(s.country||'').toLowerCase().includes(q)||(s.products||'').toLowerCase().includes(q)||(s.phone||'').toLowerCase().includes(q));
  },[suppliers,search]);
  const savingRef=useRef(false);
  useEffect(()=>{savingRef.current=false;},[modal]);

  async function save(){
    if(savingRef.current)return;
    savingRef.current=true;
    const isNew=modal==='new';
    const id=isNew?genIdUUID():form.id;
    // [BUG-FIX 20260504] Antes enviava so {name} pro banco — perdia contact/phone/
    // email/country/currency/delivery_days/notes/products. Mesmo padrao buggy do
    // Clientes.jsx (60 clientes fantasma). Agora envia payload completo.
    const dbPayload={
      name:form.name?.trim()||null,
      contact:form.contact?.trim()||null,
      phone:form.phone?.trim()||null,
      email:form.email?.trim()||null,
      country:form.country?.trim()||null,
      currency:form.currency||null,
      delivery_days:form.deliveryDays?Number(form.deliveryDays):null,
      notes:form.notes?.trim()||null,
      products:form.products?.trim()||null,
    };
    const ok=await dualWrite('suppliers',id,dbPayload,isNew,()=>{
      if(isNew)setSuppliers(prev=>[...prev,{...form,id}]);
      else setSuppliers(prev=>prev.map(s=>s.id===id?form:s));
    });
    if(!ok){savingRef.current=false;return;}
    setModal(null);
  }

  async function del(s){
    if(typeof znxGuard==='function'&&!await znxGuard(['admin']))return;
    if(!await showConfirm({title:'Excluir Fornecedor',message:`Excluir o fornecedor "${s.name}"?\nEsta ação não pode ser desfeita.`,confirmText:'Excluir',confirmColor:'#DC2626'}))return;
    try{
      const{error}=await sb.from('suppliers').update({deleted_at:new Date().toISOString()}).eq('id',s.id);
      if(error){toast('❌ Erro ao excluir fornecedor: '+error.message);if(typeof Sentry!=='undefined')Sentry.captureException(new Error(error.message),{extra:{context:'deleteSupplier',supplierId:s.id}});return;}
      setSuppliers(prev=>prev.filter(x=>x.id!==s.id));
      toast('✅ Fornecedor excluído.');
    }catch(e){
      console.error('[ZNX] deleteSupplier error:',e);
      if(typeof Sentry!=='undefined')Sentry.captureException(e,{extra:{context:'deleteSupplier',supplierId:s.id}});
      toast('❌ Erro inesperado ao excluir fornecedor.');
    }
  }

  return(
    <div>
      <div className="page-header">
        {/* [L2-Fornecedores 2026-05-09] Title com contador adaptativo */}
        <div className="page-title">
          Fornecedores
          {search
            ? <span style={{fontSize:13,color:'#B89840',fontWeight:600,marginLeft:8}}>({filtered.length} de {suppliers.length})</span>
            : <span style={{fontSize:13,color:'#9CA3AF',fontWeight:400,marginLeft:8}}>({suppliers.length})</span>}
        </div>
        <div style={{display:'flex',gap:10,flexWrap:'wrap'}}>
          {/* [L2-Fornecedores] Busca rápida — antes não existia */}
          <input style={{width:280,padding:'8px 12px',border:'1px solid #D1D5DB',borderRadius:6,fontSize:13}}
            placeholder="🔍 Buscar nome, contato, país, produto..." value={search} onChange={e=>setSearch(e.target.value)}/>
          <button className="btn-gold" onClick={()=>{setForm(EMPTY_SUPP);setModal('new')}} style={{display:'flex',alignItems:'center',gap:6}}><Icon n="plus" size={14}/>Novo Fornecedor</button>
        </div>
      </div>
      <div className="card" style={{padding:0}}>
        <table>
          <thead><tr><th>Nome/Razão Social</th><th>Contato</th><th>WhatsApp/Tel</th><th>País</th><th>Moeda</th><th>Prazo (dias)</th><th>Ações</th></tr></thead>
          <tbody>
            {filtered.map(s=>(
              <tr key={s.id}>
                <td style={{fontWeight:500}}>{s.name}</td>
                <td>{s.contact||'—'}</td>
                <td className="dim">{s.phone||'—'}</td>
                <td className="dim">{s.country||'—'}</td>
                <td><span style={{fontSize:11,color:'#2563EB'}}>{s.currency||'—'}</span></td>
                <td className="dim">{s.deliveryDays||'—'}</td>
                <td>
                  <div style={{display:'flex',gap:6}}>
                    <button className="btn-outline btn-sm" onClick={()=>{setForm({...EMPTY_SUPP,...s});setModal('edit')}}><Icon n="edit" size={12}/></button>
                    <button className="btn-danger btn-sm" onClick={()=>del(s)}><Icon n="trash" size={12}/></button>
                  </div>
                </td>
              </tr>
            ))}
            {/* [L2-Fornecedores 2026-05-09] Empty state inteligente */}
            {filtered.length===0&&(
              <tr><td colSpan={7} style={{textAlign:'center',padding:50}}>
                {search?(
                  <>
                    <div style={{fontSize:38,marginBottom:10}}>🔍</div>
                    <div style={{fontSize:15,fontWeight:600,color:'#374151',marginBottom:6}}>Nenhum fornecedor bate com "{search}"</div>
                    <button onClick={()=>setSearch('')}
                      style={{padding:'9px 22px',background:'#1B2A4A',color:'#fff',border:'none',borderRadius:6,fontSize:12,fontWeight:600,cursor:'pointer',marginTop:10}}>
                      ↻ Limpar busca
                    </button>
                  </>
                ):(
                  <>
                    <div style={{fontSize:38,marginBottom:10}}>🏭</div>
                    <div style={{fontSize:15,fontWeight:600,color:'#374151',marginBottom:6}}>Nenhum fornecedor cadastrado</div>
                    <div style={{fontSize:12,color:'#6B7280',marginBottom:14}}>Cadastre seus fornecedores (Lattafa, Maison Alhambra, etc) pra rastrear compras + prazos.</div>
                    <button onClick={()=>{setForm(EMPTY_SUPP);setModal('new')}}
                      style={{padding:'9px 22px',background:'#B89840',color:'#fff',border:'none',borderRadius:6,fontSize:12,fontWeight:600,cursor:'pointer'}}>
                      ➕ Cadastrar primeiro fornecedor
                    </button>
                  </>
                )}
              </td></tr>
            )}
          </tbody>
        </table>
      </div>
      {modal&&(
        <Modal title={modal==='new'?'Novo Fornecedor':'Editar Fornecedor'} onClose={()=>setModal(null)}>
          <div className="form-grid">
            <div className="form-group full"><label>Nome / Razão Social</label><input value={form.name} onChange={e=>setForm(f=>({...f,name:e.target.value}))}/></div>
            <div className="form-group"><label>Nome do Contato</label><input value={form.contact||''} onChange={e=>setForm(f=>({...f,contact:e.target.value}))} placeholder="Responsável"/></div>
            <div className="form-group"><label>WhatsApp / Telefone</label><input value={form.phone||''} onChange={e=>setForm(f=>({...f,phone:e.target.value}))} placeholder="+971..."/></div>
            <div className="form-group full"><label>E-mail</label><input type="email" value={form.email||''} onChange={e=>setForm(f=>({...f,email:e.target.value}))}/></div>
            <div className="form-group"><label>País de Origem</label>
              <input list="countries-list" value={form.country||''} onChange={e=>setForm(f=>({...f,country:e.target.value}))} placeholder="Emirados Árabes..."/>
              <datalist id="countries-list">
                {['Emirados Árabes','Arábia Saudita','França','Brasil','EUA','China','Turquia','Marrocos'].map(c=><option key={c} value={c}/>)}
              </datalist>
            </div>
            <div className="form-group"><label>Moeda de Compra</label>
              <SmartSelect value={form.currency||'USD'} onChange={val=>setForm(f=>({...f,currency:val}))} options={['BRL','USD','AED','SAR','EUR'].map(c=>({value:c,label:c}))}/>
            </div>
            <div className="form-group"><label>Prazo de Entrega (dias)</label><input type="number" min="0" value={form.deliveryDays||''} onChange={e=>setForm(f=>({...f,deliveryDays:e.target.value}))}/></div>
            <div className="form-group full"><label>Produtos Fornecidos</label><input value={form.products||''} onChange={e=>setForm(f=>({...f,products:e.target.value}))} placeholder="Lattafa, Armaf, Al Haramain..."/></div>
            <div className="form-group full"><label>Observações</label><textarea value={form.notes||''} onChange={e=>setForm(f=>({...f,notes:e.target.value}))} rows={3} style={{resize:'vertical'}} placeholder="Condições de pagamento, informações adicionais..."/></div>
          </div>
          <div style={{display:'flex',gap:10,marginTop:20,justifyContent:'flex-end'}}>
            <button className="btn-outline" onClick={()=>setModal(null)}>Cancelar</button>
            <button className="btn-gold" onClick={save}>Salvar</button>
          </div>
        </Modal>
      )}
    </div>
  );
}

// ══════════════════════════════════════════════════════════════
// COMPRAS
// ══════════════════════════════════════════════════════════════
const COMPRA_STATUSES=['Aguardando Confirmação','Em aberto','Em trânsito','Parcialmente Entregue','Entregue'];

  window.ZNX = window.ZNX || {};
  window.ZNX.components = window.ZNX.components || {};
  window.ZNX.components.Fornecedores = Fornecedores;
  window.Fornecedores = Fornecedores;

  window.ZNX.refactor_phase_5_loaded = window.ZNX.refactor_phase_5_loaded || {};
  window.ZNX.refactor_phase_5_loaded.Fornecedores = true;

})();
