// Products — list + edit/create/delete via WooCommerce REST.

function ProductThumb({ src, kind }) {
  if (src) {
    return <img src={src} alt="" style={{width:40, height:40, objectFit:'cover', borderRadius:6, border:'1px solid var(--border)'}}/>;
  }
  const bgs = {
    panel:    'repeating-linear-gradient(135deg, #1a3f6b 0 8px, #3a6da0 8px 16px)',
    inverter: 'linear-gradient(180deg, #cbd5e1, #94a3b8)',
    battery:  'linear-gradient(135deg, #0b1a2e, #23507f)',
    default:  'linear-gradient(135deg, #cbd5e1, #94a3b8)',
  };
  return <div style={{width:40, height:40, borderRadius:6, background:bgs[kind] || bgs.default}}/>;
}

function ProductEditModal({ productId = null, cats = [], onClose, onSaved, onCatsChanged, notify }) {
  const isNew = !productId;
  const [form, setForm] = React.useState(null);
  const [loading, setLoading] = React.useState(!isNew);
  const [busy, setBusy] = React.useState(null);
  const [catFilter, setCatFilter] = React.useState('');
  const [showNewCat, setShowNewCat] = React.useState(false);
  const [newCatName, setNewCatName] = React.useState('');
  const [newCatParent, setNewCatParent] = React.useState('');
  const [uploading, setUploading] = React.useState(false);
  const fileInputRef = React.useRef(null);

  React.useEffect(() => {
    if (isNew) {
      setForm({
        name: '', sku: '', status: 'publish',
        regular_price: '', sale_price: '',
        stock_status: 'instock', manage_stock: false, stock_quantity: '',
        short_description: '', description: '',
        voc_cena: '', nakupna_cena: '', min_quantity: '',
        pallet_quantity: '', pallet_price: '',
        category_ids: [],
        images: [],
      });
      return;
    }
    (async () => {
      setLoading(true);
      const r = await API.getProduct(productId);
      setLoading(false);
      if (r.ok) {
        const p = r.body.product;
        setForm({
          name: p.name || '',
          sku: p.sku || '',
          status: p.status || 'publish',
          regular_price: p.regular_price || '',
          sale_price: p.sale_price || '',
          stock_status: p.stock_status || 'instock',
          manage_stock: !!p.manage_stock,
          stock_quantity: p.stock_quantity == null ? '' : String(p.stock_quantity),
          short_description: p.short_description || '',
          description: p.description || '',
          voc_cena: p.voc_cena || '',
          nakupna_cena: p.nakupna_cena || '',
          min_quantity: p.min_quantity || '',
          pallet_quantity: p.pallet_quantity || '',
          pallet_price: p.pallet_price || '',
          category_ids: (p.categories || []).map(c => typeof c === 'object' ? c.id : null).filter(Boolean),
          images: (p.images || []).map(i => ({ id: i.id, src: i.src, alt: i.alt || '', name: i.name || '' })),
        });
      } else {
        notify('error', 'Nepodarilo sa načítať produkt.');
        onClose();
      }
    })();
    // eslint-disable-next-line
  }, [productId]);

  function set(k, v) { setForm(prev => ({ ...prev, [k]: v })); }

  function toggleCat(id) {
    const cur = form.category_ids || [];
    set('category_ids', cur.includes(id) ? cur.filter(x => x !== id) : [...cur, id]);
  }

  async function createCategory() {
    if (!newCatName.trim()) return;
    setBusy('cat');
    const r = await API.createProductCategory({
      name: newCatName.trim(),
      parent: newCatParent ? parseInt(newCatParent, 10) : 0,
    });
    setBusy(null);
    if (r.ok || r.status === 201) {
      const cat = r.body.category;
      onCatsChanged && onCatsChanged(cat);
      // auto-select the new one
      set('category_ids', [...(form.category_ids || []), cat.id]);
      setNewCatName('');
      setNewCatParent('');
      setShowNewCat(false);
      notify('success', 'Kategória vytvorená.');
    } else {
      notify('error', r.body.message || 'Nepodarilo sa vytvoriť kategóriu.');
    }
  }

  async function onFilesPicked(files) {
    if (!files || !files.length) return;
    setUploading(true);
    const newImages = [];
    for (const f of files) {
      const r = await API.uploadMedia(f);
      if (r.ok && r.body.ok) {
        newImages.push({ id: r.body.id, src: r.body.url, alt: '', name: f.name });
      } else {
        notify('error', `Upload ${f.name} zlyhal: ` + (r.body.message || r.body.error));
      }
    }
    setUploading(false);
    if (newImages.length) set('images', [...(form.images || []), ...newImages]);
    if (fileInputRef.current) fileInputRef.current.value = '';
  }

  function removeImage(idx) {
    const arr = [...(form.images || [])];
    arr.splice(idx, 1);
    set('images', arr);
  }

  function moveImage(idx, dir) {
    const arr = [...(form.images || [])];
    const target = idx + dir;
    if (target < 0 || target >= arr.length) return;
    [arr[idx], arr[target]] = [arr[target], arr[idx]];
    set('images', arr);
  }

  async function save() {
    setBusy('save');
    const payload = { ...form };
    if (payload.stock_quantity === '') payload.stock_quantity = null;
    const r = isNew ? await API.createProduct(payload) : await API.updateProduct(productId, payload);
    setBusy(null);
    if (r.ok || r.status === 201) {
      notify('success', isNew ? 'Produkt vytvorený.' : 'Uložené.');
      onSaved();
      onClose();
    } else {
      notify('error', r.body.message || r.body.error || 'Nepodarilo sa uložiť.');
    }
  }

  if (loading || !form) {
    return (
      <Modal title={isNew ? 'Nový produkt' : 'Upraviť produkt'} width={820} onClose={onClose}>
        <div className="muted" style={{padding:10}}>Načítavam…</div>
      </Modal>
    );
  }

  const filteredCats = cats.filter(c => !catFilter || c.name.toLowerCase().includes(catFilter.toLowerCase()));

  return (
    <Modal
      title={isNew ? 'Nový produkt' : `Upraviť produkt #${productId}`}
      width={860}
      onClose={onClose}
      footer={
        <>
          <button className="btn" onClick={onClose} disabled={!!busy}>Zrušiť</button>
          <button className="btn btn-primary" onClick={save} disabled={!!busy || !form.name}>
            {busy === 'save' ? 'Ukladám…' : (isNew ? 'Vytvoriť' : 'Uložiť')}
          </button>
        </>
      }
    >
      <div style={{display:'grid', gridTemplateColumns:'1.4fr 1fr', gap:18}}>
        {/* ── Left column ───────────────────────────── */}
        <div className="vstack" style={{gap:12}}>
          <div className="field">
            <label>Názov produktu *</label>
            <input className="input" value={form.name} onChange={e => set('name', e.target.value)} autoFocus/>
          </div>

          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:10}}>
            <div className="field">
              <label>SKU</label>
              <input className="input mono" value={form.sku} onChange={e => set('sku', e.target.value)}/>
            </div>
            <div className="field">
              <label>Stav</label>
              <select className="select" value={form.status} onChange={e => set('status', e.target.value)}>
                <option value="publish">Publikovaný</option>
                <option value="draft">Koncept</option>
                <option value="pending">Čaká na schválenie</option>
                <option value="private">Súkromný</option>
              </select>
            </div>
          </div>

          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:10}}>
            <div className="field">
              <label>Bežná cena (€)</label>
              <input className="input" value={form.regular_price} onChange={e => set('regular_price', e.target.value)} placeholder="0.00" inputMode="decimal"/>
            </div>
            <div className="field">
              <label>Zľavnená cena (€)</label>
              <input className="input" value={form.sale_price} onChange={e => set('sale_price', e.target.value)} placeholder="—" inputMode="decimal"/>
            </div>
          </div>

          <div className="field">
            <label>Krátky popis</label>
            <textarea className="textarea" value={form.short_description} onChange={e => set('short_description', e.target.value)} rows={3} placeholder="Jeden-dva riadky zhrnutia pre vyhľadávanie a kartu produktu."/>
          </div>

          <div className="field">
            <label>Dlhý popis</label>
            <textarea className="textarea" value={form.description} onChange={e => set('description', e.target.value)} rows={8} placeholder="Plný HTML popis. Akceptuje <p>, <ul>, <strong>…"/>
            <div className="small muted" style={{marginTop:2}}>Môžete vkladať HTML (napr. <code>&lt;p&gt;</code>, <code>&lt;ul&gt;</code>). Pre vizuálny editor použite WordPress admin.</div>
          </div>

          {/* Obrázky */}
          <div className="card" style={{padding:12}}>
            <div className="hstack" style={{marginBottom:8}}>
              <div className="small muted" style={{textTransform:'uppercase', letterSpacing:'0.08em', fontWeight:600, flex:1}}>Obrázky</div>
              <button
                type="button"
                className="btn btn-sm"
                onClick={() => fileInputRef.current && fileInputRef.current.click()}
                disabled={uploading}
              >
                {uploading ? 'Nahrávam…' : <><Ico.upload/>Pridať obrázok</>}
              </button>
              <input
                ref={fileInputRef}
                type="file"
                accept="image/jpeg,image/png,image/webp,image/gif"
                multiple
                style={{display:'none'}}
                onChange={e => onFilesPicked(Array.from(e.target.files || []))}
              />
            </div>
            {(form.images || []).length === 0 ? (
              <div className="small muted" style={{padding:'14px', textAlign:'center', border:'1px dashed var(--border-strong)', borderRadius:8}}>
                Žiadne obrázky. Prvý nahratý obrázok bude hlavný (náhľad).
              </div>
            ) : (
              <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(90px, 1fr))', gap:8}}>
                {form.images.map((img, i) => (
                  <div key={img.id || img.src || i} style={{position:'relative', border:'1px solid var(--border)', borderRadius:8, overflow:'hidden', background:'#fff'}}>
                    <img src={img.src} alt={img.alt || ''} style={{width:'100%', height:90, objectFit:'cover', display:'block'}}/>
                    {i === 0 && <span className="chip amber" style={{position:'absolute', top:4, left:4, fontSize:9, padding:'1px 5px'}}>HLAVNÝ</span>}
                    <div style={{position:'absolute', top:4, right:4, display:'flex', gap:2}}>
                      {i > 0 && <button type="button" className="btn btn-xs" style={{padding:'0 4px', height:18, minWidth:18}} onClick={() => moveImage(i, -1)} title="Posunúť vľavo">←</button>}
                      {i < form.images.length - 1 && <button type="button" className="btn btn-xs" style={{padding:'0 4px', height:18, minWidth:18}} onClick={() => moveImage(i, 1)} title="Posunúť vpravo">→</button>}
                      <button type="button" className="btn btn-xs btn-danger" style={{padding:'0 4px', height:18, minWidth:18}} onClick={() => removeImage(i)} title="Odstrániť">×</button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* ── Right column ────────────────────────── */}
        <div className="vstack" style={{gap:12}}>
          {/* Kategórie */}
          <div className="card" style={{padding:12}}>
            <div className="hstack" style={{marginBottom:8}}>
              <div className="small muted" style={{textTransform:'uppercase', letterSpacing:'0.08em', fontWeight:600, flex:1}}>Kategórie</div>
              <button type="button" className="btn btn-xs" onClick={() => setShowNewCat(v => !v)}>
                {showNewCat ? 'Zrušiť' : <><Ico.plus/>Nová</>}
              </button>
            </div>
            {showNewCat && (
              <div className="card" style={{padding:8, marginBottom:8, background:'var(--blue-50)'}}>
                <div className="field">
                  <label>Názov novej kategórie</label>
                  <input className="input" value={newCatName} onChange={e => setNewCatName(e.target.value)} autoFocus/>
                </div>
                <div className="field" style={{marginTop:6}}>
                  <label>Rodič</label>
                  <select className="select" value={newCatParent} onChange={e => setNewCatParent(e.target.value)}>
                    <option value="">— Bez rodiča —</option>
                    {cats.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                  </select>
                </div>
                <button type="button" className="btn btn-sm btn-primary btn-block" style={{marginTop:8}} onClick={createCategory} disabled={busy === 'cat' || !newCatName.trim()}>
                  {busy === 'cat' ? 'Vytváram…' : 'Vytvoriť kategóriu'}
                </button>
              </div>
            )}
            <div className="field">
              <input className="input" placeholder="Filtrovať…" value={catFilter} onChange={e => setCatFilter(e.target.value)}/>
            </div>
            <div style={{maxHeight:200, overflow:'auto', border:'1px solid var(--border)', borderRadius:6, marginTop:6, padding:6, background:'#fff'}}>
              {filteredCats.length === 0 && <div className="small muted" style={{padding:10}}>Žiadne kategórie.</div>}
              {filteredCats.map(c => (
                <label key={c.id} className="checkbox" style={{display:'flex', padding:'3px 4px', borderRadius:4, cursor:'pointer'}}>
                  <input type="checkbox" checked={(form.category_ids || []).includes(c.id)} onChange={() => toggleCat(c.id)}/>
                  <span style={{flex:1}}>{c.name}</span>
                  <span className="small muted">({c.count})</span>
                </label>
              ))}
            </div>
            {(form.category_ids || []).length > 0 && (
              <div className="small muted" style={{marginTop:6}}>Vybrané: <b>{form.category_ids.length}</b></div>
            )}
          </div>

          {/* Sklad */}
          <div className="card" style={{padding:12, background:'var(--blue-50)'}}>
            <div className="small muted" style={{textTransform:'uppercase', letterSpacing:'0.08em', fontWeight:600}}>Sklad</div>
            <div className="field" style={{marginTop:6}}>
              <label className="checkbox">
                <input type="checkbox" checked={!!form.manage_stock} onChange={e => set('manage_stock', e.target.checked)}/>
                <span>Spravovať sklad (kusy)</span>
              </label>
            </div>
            {form.manage_stock && (
              <div className="field">
                <label>Kusy</label>
                <input className="input" value={form.stock_quantity} onChange={e => set('stock_quantity', e.target.value)} inputMode="numeric"/>
              </div>
            )}
            <div className="field">
              <label>Stav skladu</label>
              <select className="select" value={form.stock_status} onChange={e => set('stock_status', e.target.value)}>
                <option value="instock">Skladom</option>
                <option value="outofstock">Vypredané</option>
                <option value="onbackorder">Na objednávku</option>
              </select>
            </div>
          </div>

          {/* DD Energy polia */}
          <div className="card" style={{padding:12, background:'#fff8e4'}}>
            <div className="small muted" style={{textTransform:'uppercase', letterSpacing:'0.08em', fontWeight:600}}>DD Energy polia</div>
            <div className="field" style={{marginTop:6}}>
              <label>VOC (B2B) cena</label>
              <input className="input" value={form.voc_cena} onChange={e => set('voc_cena', e.target.value)} inputMode="decimal"/>
            </div>
            <div className="field">
              <label>Nákupná cena</label>
              <input className="input" value={form.nakupna_cena} onChange={e => set('nakupna_cena', e.target.value)} inputMode="decimal"/>
            </div>
            <div className="field">
              <label>Min. množstvo</label>
              <input className="input" value={form.min_quantity} onChange={e => set('min_quantity', e.target.value)} inputMode="numeric"/>
            </div>
            <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:6}}>
              <div className="field">
                <label>Ks v palete</label>
                <input className="input" value={form.pallet_quantity} onChange={e => set('pallet_quantity', e.target.value)} inputMode="numeric"/>
              </div>
              <div className="field">
                <label>Cena palety</label>
                <input className="input" value={form.pallet_price} onChange={e => set('pallet_price', e.target.value)} inputMode="decimal"/>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Modal>
  );
}

function Products() {
  const [data, setData] = React.useState(null);
  const [cats, setCats] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [search, setSearch] = React.useState('');
  const [category, setCategory] = React.useState('');
  const [stockFilter, setStockFilter] = React.useState('');
  const [page, setPage] = React.useState(1);
  const [editingId, setEditingId] = React.useState(null);   // number = edit, 'new' = create, null = closed
  const [toast, setToast] = React.useState(null);
  const [busyId, setBusyId] = React.useState(null);

  const canEdit = window.hasPerm ? window.hasPerm('products.edit') : false;
  const canCreate = window.hasPerm ? window.hasPerm('products.create') : false;
  const canDelete = window.hasPerm ? window.hasPerm('products.delete') : false;

  async function reload() {
    setLoading(true);
    const r = await API.listProducts({
      search, category, stock_status: stockFilter, page, per_page: 25,
    });
    setLoading(false);
    if (r.status === 503 && r.body.error === 'woocommerce_not_configured') { setError('not_configured'); return; }
    if (!r.ok) { setError(r.body.message || 'Chyba.'); return; }
    setError(null);
    setData(r.body);
  }

  React.useEffect(() => {
    (async () => {
      const r = await API.listProductCategories();
      if (r.ok) setCats(r.body.categories || []);
    })();
  }, []);

  React.useEffect(() => { reload(); /* eslint-disable-next-line */ }, [category, stockFilter, page]);

  React.useEffect(() => {
    const id = setTimeout(() => { setPage(1); reload(); }, 350);
    return () => clearTimeout(id);
    // eslint-disable-next-line
  }, [search]);

  async function onDelete(p) {
    const force = confirm(`Zmazať "${p.name}"?\n\nOK = presunúť do koša.\nZrušiť = ponechať.\n\n(Pre trvalé zmazanie použite WC admin.)`);
    if (!force) return;
    setBusyId(p.id);
    const r = await API.deleteProduct(p.id, false);
    setBusyId(null);
    if (r.ok) { setToast({ kind:'success', text: 'Produkt v koši.' }); reload(); }
    else      { setToast({ kind:'error',   text: 'Nepodarilo sa zmazať: ' + (r.body.message || r.body.error) }); }
  }

  if (error === 'not_configured') {
    return (
      <AppShell active="products" crumbs={['CRM','Produkty']}>
        <div className="page-head"><div><h1>Produkty</h1></div></div>
        <NotConnected/>
      </AppShell>
    );
  }

  const products = data?.products || [];
  const total = data?.total || 0;
  const totalPages = data?.totalPages || 1;

  return (
    <AppShell active="products" crumbs={['CRM','Produkty']}>
      {toast && <Toast kind={toast.kind} onClose={() => setToast(null)}>{toast.text}</Toast>}
      {editingId !== null && (
        <ProductEditModal
          productId={editingId === 'new' ? null : editingId}
          cats={cats}
          onClose={() => setEditingId(null)}
          onSaved={reload}
          onCatsChanged={(newCat) => setCats(prev => [...prev, newCat].sort((a,b) => a.name.localeCompare(b.name)))}
          notify={(kind, text) => setToast({ kind, text })}
        />
      )}

      <div className="page-head">
        <div>
          <h1>Produkty</h1>
          <p>{total} produktov · WooCommerce sync</p>
        </div>
        <div className="page-head-actions">
          <button className="btn" onClick={reload}><Ico.upload/>Obnoviť</button>
          {canCreate && <button className="btn btn-primary" onClick={() => setEditingId('new')}><Ico.plus/>Nový produkt</button>}
        </div>
      </div>

      <div className="filters">
        <div style={{position:'relative', flex:1, maxWidth:300}}>
          <Ico.search style={{position:'absolute', left:10, top:9, color:'var(--ink-400)'}}/>
          <input className="input" placeholder="SKU, názov…" style={{paddingLeft:30, width:'100%'}} value={search} onChange={e => setSearch(e.target.value)}/>
        </div>
        <select className="select" value={category} onChange={e => { setCategory(e.target.value); setPage(1); }}>
          <option value="">Všetky kategórie</option>
          {cats.map(c => <option key={c.id} value={c.id}>{c.name} ({c.count})</option>)}
        </select>
        <select className="select" value={stockFilter} onChange={e => { setStockFilter(e.target.value); setPage(1); }}>
          <option value="">Všetky sklady</option>
          <option value="instock">Skladom</option>
          <option value="outofstock">Vypredané</option>
          <option value="onbackorder">Na objednávku</option>
        </select>
      </div>

      <div className="card" style={{overflow:'hidden'}}>
        {loading && <div style={{padding:20}} className="muted">Načítavam…</div>}
        {!loading && (
          <div style={{overflow:'auto'}}>
            <table className="tbl">
              <thead><tr>
                <th></th><th>SKU</th><th>Názov</th><th>Kategória</th>
                <th style={{textAlign:'right'}}>Cena</th><th style={{textAlign:'right'}}>VOC (B2B)</th>
                <th style={{textAlign:'right'}}>Sklad</th><th>Stav</th>
                <th style={{textAlign:'right'}}>Akcie</th>
              </tr></thead>
              <tbody>
                {products.length === 0 && (
                  <tr><td colSpan={9} style={{textAlign:'center', padding:30, color:'var(--ink-500)'}}>Žiadne produkty.</td></tr>
                )}
                {products.map(p => {
                  const stockChip =
                    p.stock_status === 'instock' ? <span className="chip green dot">Skladom</span> :
                    p.stock_status === 'outofstock' ? <span className="chip red dot">Vypredané</span> :
                    <span className="chip amber dot">Na obj.</span>;
                  return (
                    <tr key={p.id} style={busyId === p.id ? { opacity: 0.5 } : {}}>
                      <td><ProductThumb src={p.image}/></td>
                      <td className="mono small">{p.sku || '—'}</td>
                      <td>
                        <div style={{fontWeight:500}}>{p.name}</div>
                        {p.min_quantity && p.min_quantity > 1 && <div className="small muted">min. {p.min_quantity} ks</div>}
                      </td>
                      <td className="small">{(p.categories || []).slice(0, 2).map(c => (c && c.name) || c).join(', ')}</td>
                      <td style={{textAlign:'right', fontWeight:600}}>{p.price ? formatCurrency(parseFloat(p.price)) : '—'}</td>
                      <td style={{textAlign:'right'}} className="small">{p.voc_cena ? formatCurrency(parseFloat(p.voc_cena)) : '—'}</td>
                      <td style={{textAlign:'right'}}>{p.stock_quantity != null ? p.stock_quantity + ' ks' : '—'}</td>
                      <td>{stockChip}</td>
                      <td style={{textAlign:'right', whiteSpace:'nowrap'}}>
                        {canEdit && <button className="btn btn-xs" onClick={() => setEditingId(p.id)} title="Upraviť">Upraviť</button>}
                        {canDelete && <button className="btn btn-xs btn-danger" style={{marginLeft:4}} onClick={() => onDelete(p)} disabled={busyId === p.id} title="Zmazať"><Ico.x/></button>}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
        {totalPages > 1 && (
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', padding:'10px 14px', borderTop:'1px solid var(--border)', fontSize:12}}>
            <span className="muted">Strana {page} z {totalPages} · {total} záznamov</span>
            <div className="hstack">
              <button className="btn btn-xs" disabled={page <= 1} onClick={() => setPage(p => Math.max(1, p - 1))}>← Prev</button>
              <button className="btn btn-xs" disabled={page >= totalPages} onClick={() => setPage(p => Math.min(totalPages, p + 1))}>Next →</button>
            </div>
          </div>
        )}
      </div>
    </AppShell>
  );
}

Object.assign(window, { Products, ProductThumb });
