// RMC Plants Master Module
const { useState: rSt, useEffect: rEf, useContext: rCtx, useMemo: rMemo } = React;

const PLANT_TYPES = ['RMC Plant','Batching Plant','Wet Mix Plant','Crushing + RMC Plant','Other'];
const PLANT_STATUSES = ['Active','Inactive'];

function RMCPlantsPage() {
  window.useStoreSync();
  const { companyId, session } = rCtx(window.AppCtx);
  const [items,   setItems]   = rSt([]);
  const [search,  setSearch]  = rSt('');
  const [fStatus, setFStatus] = rSt('');
  const [fComp,   setFComp]   = rSt('');
  const [page,    setPage]    = rSt(1);
  const [modal,   setModal]   = rSt(false);
  const [editId,  setEditId]  = rSt(null);
  const [delId,   setDelId]   = rSt(null);
  const [form,    setForm]    = rSt({});
  const PER = 50;

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

  rEf(() => { load(); }, [companyId]);
  function load() { setItems(Store.all('rmcPlants') || []); }
  const setF = (k,v) => setForm(p => ({ ...p, [k]: v }));

  function plantMatchesCompany(it, cid) {
    if (it.useAllCompanies) return true;
    const ids = it.companyIds || (it.companyId ? [it.companyId] : []);
    return ids.includes(cid);
  }
  const filtered = rMemo(() => items.filter(it => {
    if (search) { const q = search.toLowerCase(); if (![it.name,it.location,it.fullAddress].some(v=>String(v||'').toLowerCase().includes(q))) return false; }
    if (fStatus && it.status !== fStatus) return false;
    if (fComp && !plantMatchesCompany(it, fComp)) return false;
    if (companyId && companyId !== 'group' && !plantMatchesCompany(it, companyId)) return false;
    return true;
  }), [items, search, fStatus, fComp, companyId]);

  const totalPgs = Math.ceil(filtered.length / PER);
  const paged    = filtered.slice((page-1)*PER, page*PER);

  function openAdd() { setForm({ status:'Active', useAllCompanies:false, companyIds: companyId!=='group'?[companyId]:[], companyId:companyId!=='group'?companyId:'' }); setEditId(null); setModal(true); }
  function openEdit(it) { setForm({...it, useAllCompanies:it.useAllCompanies||false, companyIds:it.companyIds||(it.companyId?[it.companyId]:[])}); setEditId(it.id); setModal(true); }

  function handleSave(e) {
    e.preventDefault();
    if (!form.useAllCompanies && (!form.companyIds || form.companyIds.length===0)) { window.toast&&window.toast('Assign to at least one company or enable \'Use Across All Companies\'.','er'); return; }
    const saveData = { ...form, companyId: form.useAllCompanies ? '' : (form.companyIds?.[0]||'') };
    if (editId) { Store.update('rmcPlants', editId, saveData); Store.addLog('UPDATE','RMC Plant',`Updated: ${form.name}`); }
    else        { Store.add('rmcPlants', saveData);             Store.addLog('CREATE','RMC Plant',`Created: ${form.name}`); }
    setModal(false); load(); window.toast&&window.toast(editId?'Plant updated':'Plant created','ok');
  }
  function handleDelete() { Store.del('rmcPlants', delId); Store.addLog('DELETE','RMC Plant','Deleted plant'); setDelId(null); load(); window.toast&&window.toast('Deleted','ok'); }

  function exportCSV() {
    const hdr = 'Plant Name,Company,Location,Plant Type,Capacity,Status';
    const rows = filtered.map(it => `"${it.name}","${Store.name('companies',it.companyId)}","${it.location||''}","${it.plantType||''}","${it.capacity||''}","${it.status}"`).join('\n');
    const blob = new Blob([hdr+'\n'+rows],{type:'text/csv'}); const a=document.createElement('a'); a.href=URL.createObjectURL(blob); a.download='rmc_plants.csv'; a.click();
    window.toast&&window.toast('Exported','ok');
  }

  const activeCount    = items.filter(i=>i.status==='Active').length;
  const inactiveCount  = items.filter(i=>i.status==='Inactive').length;

  return (
    <div>
      <div className="ph">
        <div><h1>RMC Plants</h1><p>Ready-Mix Concrete &amp; Batching Plant Master</p></div>
        <div className="ph-act">
          <button className="btn btn-wh btn-sm" onClick={exportCSV}><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg> Export CSV</button>
          <button className="btn btn-or" onClick={openAdd}><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> Add RMC Plant</button>
        </div>
      </div>

      {/* KPI strip */}
      <div className="rg-3kpi" style={{marginBottom:12}}>
        <div className="kpi"><div className="kpi-val">{items.length}</div><div className="kpi-lbl">Total Plants</div></div>
        <div className="kpi"><div className="kpi-val" style={{color:'var(--ok)'}}>{activeCount}</div><div className="kpi-lbl">Active</div></div>
        <div className="kpi"><div className="kpi-val" style={{color:'var(--txt2)'}}>{inactiveCount}</div><div className="kpi-lbl">Inactive</div></div>
      </div>

      <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);setPage(1);}} placeholder="Search plant name, location…"/></div>
        <window.FiltSelect placeholder="All Companies" value={fComp} onChange={v=>{setFComp(v);setPage(1);}} options={companies.map(c=>({value:c.id,label:c.name}))}/>
        <window.FiltSelect placeholder="All Status" value={fStatus} onChange={v=>{setFStatus(v);setPage(1);}} options={PLANT_STATUSES.map(s=>({value:s,label:s}))}/>
        {(search||fComp||fStatus)&&<button className="btn btn-gh btn-sm" onClick={()=>{setSearch('');setFComp('');setFStatus('');setPage(1);}}>Clear</button>}
        <span className="f-cnt">{filtered.length} plants</span>
      </div>

      <div className="card"><div className="tbl-w"><table className="tbl">
        <thead><tr>
          <th style={{width:50,textAlign:'center'}}>SR.NO</th>
          <th>PLANT NAME</th><th>COMPANY</th><th>LOCATION</th>
          <th>PLANT TYPE</th><th>CAPACITY</th><th>STATUS</th><th>ACTIONS</th>
        </tr></thead>
        <tbody>
          {paged.length===0
            ? <tr className="empty"><td colSpan="8" style={{textAlign:'center',padding:40,color:'var(--txt2)'}}>No plants found. Add your first RMC Plant.</td></tr>
            : paged.map((it,idx)=>(
              <tr key={it.id}>
                <td style={{textAlign:'center',color:'var(--txt2)',fontWeight:500}}>{(page-1)*PER+idx+1}</td>
                <td style={{fontWeight:600}}>{it.name}</td>
                <td>
                  {it.useAllCompanies
                    ? <span className="bdg bg-gn" style={{fontSize:10,padding:'1px 6px'}}>All Companies</span>
                    : (it.companyIds||(it.companyId?[it.companyId]:[])).slice(0,2).map(cid=>(
                        <span key={cid} className="bdg bg-or" style={{fontSize:10,padding:'1px 5px',marginRight:2}}>{Store.name('companies',cid)||'—'}</span>
                      ))
                  }
                  {!it.useAllCompanies&&(it.companyIds||(it.companyId?[it.companyId]:[])).length>2&&(
                    <span className="bdg bg-gy" style={{fontSize:10,padding:'1px 5px'}}>+{(it.companyIds||[it.companyId].filter(Boolean)).length-2}</span>
                  )}
                </td>
                <td>{it.location||'—'}</td>
                <td style={{fontSize:11.5,color:'var(--txt2)'}}>{it.plantType||'—'}{it.plantType==='Other'&&it.plantTypeOther?` (${it.plantTypeOther})`:''}</td>
                <td style={{fontSize:11.5,color:'var(--txt2)'}}>{it.capacity||'—'}</td>
                <td><window.Badge v={it.status}/></td>
                <td><div className="ra">
                  <button className="btn btn-wh btn-sm" onClick={()=>openEdit(it)}>Edit</button>
                  <button className="btn btn-rd btn-sm" onClick={()=>setDelId(it.id)}>Delete</button>
                </div></td>
              </tr>
            ))}
        </tbody>
      </table></div></div>

      {totalPgs>1&&<div className="pag"><button className="pg-b" onClick={()=>setPage(1)} disabled={page===1}>«</button><button className="pg-b" onClick={()=>setPage(p=>p-1)} disabled={page===1}>‹</button><span className="pg-inf">Page {page} of {totalPgs}</span><button className="pg-b" onClick={()=>setPage(p=>p+1)} disabled={page===totalPgs}>›</button><button className="pg-b" onClick={()=>setPage(totalPgs)} disabled={page===totalPgs}>»</button></div>}

      {/* Add/Edit Modal */}
      {modal&&(
        <div className="mbg">
          <div className="mod mod-lg" style={{maxHeight:'92vh'}}>
            <div className="mod-hd"><h2>{editId?'Edit':'Add'} RMC Plant</h2><button className="mod-x" onClick={()=>setModal(false)}>×</button></div>
            <form onSubmit={handleSave}>
              <div className="mod-bd" style={{display:'flex',flexDirection:'column',gap:14}}>
                {/* Basic Info */}
                <div style={{color:'var(--or)',fontWeight:700,fontSize:13,paddingBottom:6,borderBottom:'2px solid #FEF3E8'}}>Basic Information</div>
                <div className="fld"><label>Plant Name <span className="req">*</span></label><input className="inp" value={form.name||''} onChange={e=>setF('name',e.target.value)} required placeholder="e.g. Verna RMC Plant"/></div>
                {/* Location Info */}
                <div style={{color:'var(--or)',fontWeight:700,fontSize:13,paddingBottom:6,borderBottom:'2px solid #FEF3E8'}}>Location Information</div>
                <div className="fg">
                  <div className="fld"><label>Location <span className="req">*</span></label><input className="inp" value={form.location||''} onChange={e=>setF('location',e.target.value)} required placeholder="e.g. Verna, Goa"/></div>
                  <div className="fld"><label>Full Address</label><input className="inp" value={form.fullAddress||''} onChange={e=>setF('fullAddress',e.target.value)} placeholder="Survey No, Village, Taluka, Goa"/></div>
                </div>
                <div className="fld"><label>Google Maps Link <span style={{fontSize:11,color:'var(--txt2)'}}>(Optional)</span></label><input className="inp" value={form.mapsLink||''} onChange={e=>setF('mapsLink',e.target.value)} placeholder="https://maps.google.com/..."/></div>
                {/* Plant Info */}
                <div style={{color:'var(--or)',fontWeight:700,fontSize:13,paddingBottom:6,borderBottom:'2px solid #FEF3E8'}}>Plant Information</div>
                <div className="fg">
                  <div className="fld"><label>Plant Type <span className="req">*</span></label>
                    <window.FormSelect placeholder="— Select Type —" value={form.plantType||''} onChange={v=>setF('plantType',v)} options={PLANT_TYPES.map(t=>({value:t,label:t}))}/>
                    {form.plantType==='Other'&&<input className="inp" style={{marginTop:6}} value={form.plantTypeOther||''} onChange={e=>setF('plantTypeOther',e.target.value)} placeholder="Specify plant type…"/>}
                  </div>
                  <div className="fld"><label>Plant Capacity <span style={{fontSize:11,color:'var(--txt2)'}}>(Optional)</span></label><input className="inp" value={form.capacity||''} onChange={e=>setF('capacity',e.target.value)} placeholder="e.g. 60 m³/hr"/></div>
                </div>
                <div className="fld" style={{maxWidth:200}}><label>Status <span className="req">*</span></label>
                  <window.FormSelect value={form.status||'Active'} onChange={v=>setF('status',v)} options={PLANT_STATUSES.map(s=>({value:s,label:s}))}/>
                </div>
                {/* Availability & Company Assignment */}
                <div style={{color:'var(--or)',fontWeight:700,fontSize:13,paddingBottom:6,borderBottom:'2px solid #FEF3E8',marginTop:4}}>Availability &amp; Company Assignment</div>
                <div className="fld full">
                  <label style={{display:'flex',alignItems:'center',gap:8,cursor:'pointer',userSelect:'none',fontWeight:600,fontSize:12.5}}>
                    <input type="checkbox" checked={form.useAllCompanies||false} onChange={e=>setF('useAllCompanies',e.target.checked)} style={{width:16,height:16,accentColor:'var(--or)',cursor:'pointer',flexShrink:0}}/>
                    Use Across All Companies
                  </label>
                  <div style={{fontSize:11,color:'var(--txt2)',marginTop:4,marginLeft:24}}>When enabled, this plant is available to every company — including any future companies added to the system.</div>
                </div>
                {!form.useAllCompanies&&(
                  <div className="fld full">
                    <label>Assign to Specific Companies <span className="req">*</span></label>
                    <div style={{border:'1px solid var(--bdr2)',borderRadius:6,padding:'8px 14px',background:'#FAFAFA',display:'grid',gridTemplateColumns:'1fr 1fr',gap:'6px 16px',maxHeight:200,overflowY:'auto'}}>
                      {companies.map(c=>(
                        <label key={c.id} style={{display:'flex',alignItems:'center',gap:7,cursor:'pointer',fontSize:12,userSelect:'none',padding:'3px 0'}}>
                          <input type="checkbox"
                            checked={(form.companyIds||[]).includes(c.id)}
                            onChange={e=>{
                              const ids=form.companyIds||[];
                              setF('companyIds',e.target.checked?[...ids,c.id]:ids.filter(id=>id!==c.id));
                            }}
                            style={{width:14,height:14,accentColor:'var(--or)',cursor:'pointer',flexShrink:0}}/>
                          <span style={{overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{c.name}</span>
                        </label>
                      ))}
                    </div>
                    {(!form.companyIds||form.companyIds.length===0)&&<div style={{fontSize:11,color:'var(--err)',marginTop:4}}>Select at least one company to proceed.</div>}
                  </div>
                )}
              </div>
              <div className="mod-ft"><button type="button" className="btn btn-wh" onClick={()=>setModal(false)}>Cancel</button><button type="submit" className="btn btn-or">{editId?'Update Plant':'Create Plant'}</button></div>
            </form>
          </div>
        </div>
      )}
      {delId&&<window.Confirm onOk={handleDelete} onCancel={()=>setDelId(null)}/>}
    </div>
  );
}
window.RMCPlantsPage = RMCPlantsPage;
