// Settlement Policy Master — OM Group ERP
// Configuration-driven settlement rules. No hardcoded vehicles, companies, or margins.
// Policies are assigned to vehicles; the settlement engine reads them dynamically.
const { useState: spSt, useEffect: spEf, useContext: spCtx, useMemo: spMemo } = React;

const SP_MODES    = ['Direct Transporter Payment', 'Internal Company Settlement'];
const SP_MARGINS  = ['Per Ton', 'Fixed Amount', 'Percentage'];
const SP_STATUSES = ['Active', 'Inactive'];

function SpModeBadge({ mode }) {
  if (mode === 'Internal Company Settlement')
    return <span style={{fontSize:10.5,fontWeight:700,padding:'2px 9px',borderRadius:3,background:'#EDE9FE',color:'#6D28D9'}}>{mode}</span>;
  return <span style={{fontSize:10.5,fontWeight:700,padding:'2px 9px',borderRadius:3,background:'#DCFCE7',color:'#15803D'}}>{mode}</span>;
}
function SpStatusBadge({ status }) {
  return <span className={`bdg ${status==='Active'?'bg-gn':'bg-gy'}`}>{status||'Active'}</span>;
}

// ── Policy Form Modal ─────────────────────────────────────────────────────────
function SettlementPolicyModal({ item, session, onSaved, onClose }) {
  const todayStr = new Date().toISOString().slice(0,10);
  const blank = {
    policyName:'', description:'',
    settlementMode:'Direct Transporter Payment',
    receivingCompanyId:'',
    marginType:'Per Ton', marginValue:'',
    status:'Active',
    effectiveFrom:todayStr, effectiveTo:'',
    notes:'',
  };
  const [form, setF0] = spSt(item ? {...item, marginValue: item.marginValue !== undefined ? String(item.marginValue) : '' } : {...blank});
  const sf = (k,v) => setF0(p=>({...p,[k]:v}));
  const companies = Store.all('companies');
  const isInternal = form.settlementMode === 'Internal Company Settlement';

  function handleSave(e) {
    e.preventDefault();
    if (!form.policyName.trim()) { window.toast&&window.toast('Policy name is required','er'); return; }
    if (isInternal && !form.receivingCompanyId) { window.toast&&window.toast('Select a receiving company for Internal Settlement','er'); return; }
    if (isInternal && (parseFloat(form.marginValue)||0) <= 0) { window.toast&&window.toast('Enter a valid margin value greater than 0','er'); return; }
    const now = new Date().toISOString().slice(0,16).replace('T',' ');
    const auditEntry = { changedBy:session?.userName||'System', changedAt:now, action:item?'UPDATE':'CREATE',
      snapshot:{ settlementMode:form.settlementMode, marginType:form.marginType, marginValue:form.marginValue,
        receivingCompanyId:form.receivingCompanyId, status:form.status } };
    const data = {
      ...form,
      marginValue: parseFloat(form.marginValue)||0,
      auditHistory: [...(item?.auditHistory||[]), auditEntry],
      createdAt: item?.createdAt||todayStr,
      createdBy: item?.createdBy||(session?.userName||'System'),
      updatedAt: now,
      updatedBy: session?.userName||'System',
    };
    if (!isInternal) { data.receivingCompanyId=''; data.marginValue=0; }
    if (item) {
      Store.update('settlementPolicies', item.id, data);
      Store.addLog('UPDATE','Settlement Policy','Updated: '+form.policyName);
      window.toast&&window.toast('Policy updated','ok');
    } else {
      Store.add('settlementPolicies', data);
      Store.addLog('CREATE','Settlement Policy','Created: '+form.policyName);
      window.toast&&window.toast('Policy created','ok');
    }
    onSaved();
  }

  const mv = parseFloat(form.marginValue)||0;

  return (
    <div className="mbg">
      <div className="mod mod-lg">
        <div className="mod-hd"><h2>{item?'Edit':'New'} Settlement Policy</h2><button className="mod-x" onClick={onClose}>×</button></div>
        <form onSubmit={handleSave}>
          <div className="mod-bd">
            {/* Core policy fields */}
            <div style={{marginBottom:16}}>
              <div style={{fontWeight:700,fontSize:11,color:'var(--or)',textTransform:'uppercase',letterSpacing:'.06em',marginBottom:10,paddingBottom:6,borderBottom:'2px solid #FEF3E8'}}>Policy Details</div>
              <div className="fg">
                <div className="fld full"><label>Policy Name <span className="req">*</span></label>
                  <input className="inp" value={form.policyName} onChange={e=>sf('policyName',e.target.value)} required placeholder="e.g. Standard Direct Payment" /></div>
                <div className="fld full"><label>Description</label>
                  <textarea className="tarea" value={form.description} onChange={e=>sf('description',e.target.value)} placeholder="Brief description of this settlement policy…" style={{minHeight:52}}/></div>
                <div className="fld"><label>Settlement Mode <span className="req">*</span></label>
                  <window.FormSelect value={form.settlementMode} onChange={v=>sf('settlementMode',v)} options={SP_MODES.map(m=>({value:m,label:m}))}/></div>
                <div className="fld"><label>Status</label>
                  <window.FormSelect value={form.status} onChange={v=>sf('status',v)} options={SP_STATUSES.map(s=>({value:s,label:s}))}/></div>
                <div className="fld"><label>Effective From</label>
                  <input className="inp" type="date" value={form.effectiveFrom} onChange={e=>sf('effectiveFrom',e.target.value)}/></div>
                <div className="fld"><label>Effective To <span style={{fontSize:10,color:'var(--txt3)',fontWeight:400}}>(leave blank for open-ended)</span></label>
                  <input className="inp" type="date" value={form.effectiveTo} onChange={e=>sf('effectiveTo',e.target.value)}/></div>
              </div>
            </div>

            {/* Internal Settlement config — only visible when mode is Internal */}
            {isInternal && (
              <div style={{marginBottom:16,background:'#F5F3FF',border:'1.5px solid #DDD6FE',borderRadius:8,padding:'12px 14px'}}>
                <div style={{fontWeight:700,fontSize:11,color:'#6D28D9',textTransform:'uppercase',letterSpacing:'.06em',marginBottom:10,paddingBottom:6,borderBottom:'1px solid #DDD6FE'}}>Internal Settlement Configuration</div>
                <div className="fg">
                  <div className="fld">
                    <label>Receiving Company <span className="req">*</span></label>
                    <window.FormSelect placeholder="Select Company…" value={form.receivingCompanyId} onChange={v=>sf('receivingCompanyId',v)} options={companies.map(c=>({value:c.id,label:c.name}))}/>
                    <span style={{fontSize:10.5,color:'#7C3AED',marginTop:3,display:'block'}}>Net settlement amount is transferred to this company — not paid to the transporter directly</span>
                  </div>
                  <div className="fld">
                    <label>Margin Type <span className="req">*</span></label>
                    <window.FormSelect value={form.marginType} onChange={v=>sf('marginType',v)} options={SP_MARGINS.map(t=>({value:t,label:t}))}/>
                  </div>
                  <div className="fld">
                    <label>Margin Value <span className="req">*</span>
                      <span style={{fontSize:10,color:'var(--txt3)',fontWeight:400,marginLeft:5}}>
                        {form.marginType==='Per Ton'?'₹ per MT':form.marginType==='Percentage'?'%':'₹ fixed per trip'}
                      </span>
                    </label>
                    <input className="inp" type="number" value={form.marginValue} onChange={e=>sf('marginValue',e.target.value)}
                      placeholder={form.marginType==='Per Ton'?'30':form.marginType==='Percentage'?'5':'1000'}
                      min="0" step="0.01" required={isInternal}/>
                  </div>
                </div>
                {mv > 0 && (
                  <div style={{marginTop:10,background:'#EDE9FE',border:'1px solid #DDD6FE',borderRadius:6,padding:'8px 12px',fontSize:12}}>
                    <span style={{fontWeight:700,color:'#6D28D9'}}>Formula Preview: </span>
                    <span style={{color:'#5B21B6'}}>
                      Adjusted Rate = Actual Rate
                      {form.marginType==='Per Ton'?` + ₹${mv}/MT` : form.marginType==='Percentage'?` + ${mv}% of Gross` : ` + ₹${mv} fixed`}
                    </span>
                    <span style={{color:'#7C3AED',marginLeft:8}}>→ Diesel deducted → Net to Receiving Company</span>
                  </div>
                )}
              </div>
            )}

            <div className="fld"><label>Notes</label>
              <textarea className="tarea" value={form.notes} onChange={e=>sf('notes',e.target.value)} placeholder="Internal notes about this policy…" style={{minHeight:48}}/></div>
          </div>
          <div className="mod-ft">
            <button type="button" className="btn btn-wh" onClick={onClose}>Cancel</button>
            <button type="submit" className="btn btn-or">{item?'Update Policy':'Create Policy'}</button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ── Audit Trail Modal ─────────────────────────────────────────────────────────
function SpAuditModal({ item, onClose }) {
  const hist = [...(item?.auditHistory||[])].reverse();
  return (
    <div className="mbg">
      <div className="mod mod-md">
        <div className="mod-hd"><h2>Audit Trail — {item?.policyName}</h2><button className="mod-x" onClick={onClose}>×</button></div>
        <div className="mod-bd">
          {!hist.length
            ? <div style={{textAlign:'center',padding:40,color:'var(--txt3)'}}>No audit history recorded yet.</div>
            : <div style={{display:'flex',flexDirection:'column',gap:8}}>
                {hist.map((h,i)=>(
                  <div key={i} style={{background:'#FAFAF8',border:'1px solid var(--bdr)',borderRadius:8,padding:'10px 14px'}}>
                    <div style={{display:'flex',justifyContent:'space-between',marginBottom:4}}>
                      <span style={{fontWeight:700,fontSize:12,color:h.action==='CREATE'?'var(--ok)':'var(--or)'}}>{h.action}</span>
                      <span style={{fontSize:11,color:'var(--txt3)'}}>{h.changedAt}</span>
                    </div>
                    <div style={{fontSize:11.5,color:'var(--txt2)'}}>By: <strong>{h.changedBy}</strong></div>
                    {h.snapshot && (
                      <div style={{marginTop:6,fontSize:11,color:'var(--txt3)'}}>
                        Mode: {h.snapshot.settlementMode} · Margin: {h.snapshot.marginType} @ {h.snapshot.marginValue||0}
                        {h.snapshot.status&&<> · Status: {h.snapshot.status}</>}
                      </div>
                    )}
                  </div>
                ))}
              </div>
          }
        </div>
        <div className="mod-ft"><button className="btn btn-wh" onClick={onClose}>Close</button></div>
      </div>
    </div>
  );
}

// ── Main Page ─────────────────────────────────────────────────────────────────
function SettlementPolicyPage() {
  window.useStoreSync();
  const { session } = spCtx(window.AppCtx);
  const [items,    setItems]    = spSt([]);
  const [modal,    setModal]    = spSt(false);
  const [editItem, setEditItem] = spSt(null);
  const [auditItem,setAuditItem]= spSt(null);
  const [delId,    setDelId]    = spSt(null);
  const [search,   setSearch]   = spSt('');
  const [fMode,    setFMode]    = spSt('');
  const [fStatus,  setFStatus]  = spSt('');

  spEf(()=>{ load(); return Store.on(load); },[]);
  function load(){ setItems(Store.all('settlementPolicies','group')||[]); }

  const companies = Store.all('companies');

  const filtered = spMemo(()=>items.filter(p=>{
    if (fMode   && p.settlementMode!==fMode)   return false;
    if (fStatus && p.status!==fStatus)          return false;
    if (search) {
      const q=search.toLowerCase();
      return ['policyName','description','notes'].some(k=>String(p[k]||'').toLowerCase().includes(q));
    }
    return true;
  }),[items,fMode,fStatus,search]);

  const kpi = spMemo(()=>({
    total:    items.length,
    active:   items.filter(p=>p.status==='Active').length,
    direct:   items.filter(p=>p.settlementMode==='Direct Transporter Payment').length,
    internal: items.filter(p=>p.settlementMode==='Internal Company Settlement').length,
  }),[items]);

  function getVehCount(policyId) {
    return (Store.all('vehicleMaster','group')||[]).filter(v=>v.settlementPolicyId===policyId).length;
  }

  function handleDelete() {
    const vehsUsing = (Store.all('vehicleMaster','group')||[]).filter(v=>v.settlementPolicyId===delId);
    if (vehsUsing.length>0) {
      window.toast&&window.toast('Cannot delete — '+vehsUsing.length+' vehicle(s) use this policy. Reassign them first.','er');
      setDelId(null); return;
    }
    Store.del('settlementPolicies',delId);
    Store.addLog('DELETE','Settlement Policy','Deleted policy');
    setDelId(null); load();
    window.toast&&window.toast('Policy deleted','ok');
  }

  return (
    <div>
      <div className="ph">
        <div>
          <h1>Settlement Policy Master</h1>
          <p>Configuration-driven settlement rules</p>
        </div>
        <div className="ph-act">
          <button className="btn btn-or" onClick={()=>{setEditItem(null);setModal(true);}}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg> New Policy
          </button>
        </div>
      </div>

      {/* Admin notice */}
      <div style={{background:'#FFF7ED',border:'1px solid var(--or-bdr)',borderRadius:8,padding:'9px 14px',marginBottom:14,display:'flex',alignItems:'center',gap:8,fontSize:12,color:'var(--or2)'}}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{flexShrink:0}}><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
        <span><strong>Admin-only configuration.</strong> Assign policies to vehicles in Transporter Master → Vehicles. The settlement engine applies the policy automatically — normal users only select the transporter and dates.</span>
      </div>

      {/* KPI strip */}
      <div className="kpi-grid" style={{marginBottom:12}}>
        {[['Total Policies',kpi.total,'var(--txt)'],['Active',kpi.active,'var(--ok)'],['Direct Payment',kpi.direct,'var(--info)'],['Internal Settlement',kpi.internal,'#6D28D9']].map(([l,v,c])=>(
          <div key={l} className="kpi"><div className="kpi-val" style={{color:c}}>{v}</div><div className="kpi-lbl">{l}</div></div>
        ))}
      </div>

      {/* Filter row */}
      <div className="frow">
        <div className="fs"><svg className="fs-ic" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/></svg>
          <input value={search} onChange={e=>setSearch(e.target.value)} placeholder="Search policy name, description…"/></div>
        <window.FiltSelect placeholder="All Modes" value={fMode} onChange={v=>setFMode(v)} options={SP_MODES.map(m=>({value:m,label:m}))}/>
        <window.FiltSelect placeholder="All Status" value={fStatus} onChange={v=>setFStatus(v)} options={SP_STATUSES.map(s=>({value:s,label:s}))}/>
        {(search||fMode||fStatus)&&<button className="btn btn-gh btn-sm" onClick={()=>{setSearch('');setFMode('');setFStatus('');}}>Clear</button>}
        <span className="f-cnt">{filtered.length} polic{filtered.length!==1?'ies':'y'}</span>
      </div>

      {/* Table */}
      <div className="card">
        <div className="tbl-w">
          <table className="tbl">
            <thead><tr>
              <th>POLICY NAME</th>
              <th>SETTLEMENT MODE</th>
              <th>RECEIVING COMPANY</th>
              <th>MARGIN TYPE</th>
              <th style={{textAlign:'right'}}>MARGIN VALUE</th>
              <th>STATUS</th>
              <th>EFFECTIVE FROM</th>
              <th>EFFECTIVE TO</th>
              <th style={{textAlign:'center'}}>VEHICLES</th>
              <th>ACTIONS</th>
            </tr></thead>
            <tbody>
              {!filtered.length
                ? <tr className="empty"><td colSpan={10} style={{textAlign:'center',padding:56,color:'var(--txt3)'}}>
                    No settlement policies yet. Click "+ New Policy" to create one.<br/>
                    <span style={{fontSize:11,marginTop:4,display:'block'}}>Create a "Standard Direct Payment" policy first — assign it as the default for all vehicles.</span>
                  </td></tr>
                : filtered.map(p=>{
                    const isInternal = p.settlementMode === 'Internal Company Settlement';
                    const rcName = isInternal && p.receivingCompanyId ? (companies.find(c=>c.id===p.receivingCompanyId)?.name||'—') : '—';
                    const vc = getVehCount(p.id);
                    return (
                      <tr key={p.id}>
                        <td style={{fontWeight:600}}>
                          {p.policyName}
                          {p.description&&<div style={{fontSize:11,color:'var(--txt3)',fontWeight:400,marginTop:1}}>{p.description}</div>}
                        </td>
                        <td><SpModeBadge mode={p.settlementMode}/></td>
                        <td style={{fontSize:12,color:isInternal?'var(--txt)':'var(--txt3)',fontStyle:isInternal?'normal':'italic'}}>{rcName}</td>
                        <td style={{fontSize:12,color:isInternal?'var(--txt)':'var(--txt3)'}}>{isInternal?p.marginType:'—'}</td>
                        <td style={{textAlign:'right',fontWeight:isInternal?700:400,color:isInternal?'#6D28D9':'var(--txt3)'}}>
                          {isInternal ? (p.marginType==='Per Ton'?`₹${p.marginValue}/MT`:p.marginType==='Percentage'?`${p.marginValue}%`:`₹${p.marginValue}`) : '—'}
                        </td>
                        <td><SpStatusBadge status={p.status}/></td>
                        <td style={{fontSize:12}}>{p.effectiveFrom?window.fmtDate(p.effectiveFrom):'—'}</td>
                        <td style={{fontSize:12,color:'var(--txt3)'}}>{p.effectiveTo?window.fmtDate(p.effectiveTo):'Open'}</td>
                        <td style={{textAlign:'center'}}>
                          <span style={{background:vc>0?'#DBEAFE':'#F3F4F6',color:vc>0?'#1D4ED8':'#6B7280',fontSize:11,fontWeight:700,padding:'2px 8px',borderRadius:3}}>
                            {vc} vehicle{vc!==1?'s':''}
                          </span>
                        </td>
                        <td>
                          <div className="ra">
                            <button className="btn btn-wh btn-sm" onClick={()=>{setEditItem(p);setModal(true);}}>Edit</button>
                            <button className="btn btn-wh btn-sm" onClick={()=>setAuditItem(p)} title="Audit trail">
                              <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11"/></svg>
                            </button>
                            <button className="btn btn-rd btn-sm" onClick={()=>setDelId(p.id)}>Delete</button>
                          </div>
                        </td>
                      </tr>
                    );
                  })
              }
            </tbody>
          </table>
        </div>
      </div>

      {modal&&<SettlementPolicyModal item={editItem} session={session} onSaved={()=>{setModal(false);load();}} onClose={()=>setModal(false)}/>}
      {auditItem&&<SpAuditModal item={auditItem} onClose={()=>setAuditItem(null)}/>}
      {delId&&(
        <div className="mbg"><div className="mod mod-sm">
          <div className="mod-hd"><h2>Delete Policy</h2><button className="mod-x" onClick={()=>setDelId(null)}>×</button></div>
          <div className="mod-bd"><p style={{fontSize:13,lineHeight:1.6}}>Delete this settlement policy? Vehicles assigned to this policy will fall back to Direct Transporter Payment. This cannot be undone.</p></div>
          <div className="mod-ft">
            <button className="btn btn-wh" onClick={()=>setDelId(null)}>Cancel</button>
            <button className="btn btn-rd" onClick={handleDelete}>Delete</button>
          </div>
        </div></div>
      )}
    </div>
  );
}

window.SettlementPolicyPage = SettlementPolicyPage;
