import { h, Fragment, useState } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { Drawer, Btn, Icon } from './ui.jsx';
import { api, errMsg } from './api.js';
import { parseCSV, fmtVal } from './util.js';

const norm = (s) => String(s || '').toLowerCase().replace(/[^a-z0-9]/g, '');

export default function Import({ boot, onClose, onDone }) {
  const [table, setTable] = useState(null);
  const [fileName, setFileName] = useState('');
  const [match, setMatch] = useState('sku');
  const [map, setMap] = useState({});
  const [prev, setPrev] = useState(null);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');
  const [res, setRes] = useState(null);
  const editable = boot.fields.filter((f) => f.editable);

  const guess = (head) => {
    const m = {}; const n = head.map(norm);
    head.forEach((h0, i) => {
      const hn = n[i];
      const f = editable.find((x) => norm(x.id) === hn || norm(x.label) === hn) || (hn === 'stock' ? boot.fieldMap.stock_quantity : null) || (hn === 'price' ? boot.fieldMap.regular_price : null) || (hn === 'categories' ? boot.fieldMap.category_ids : null) || (hn === 'tags' ? boot.fieldMap.tag_ids : null);
      m[i] = f ? f.id : '';
    });
    return m;
  };

  const onFile = (file) => {
    if (!file) return;
    setErr(''); setPrev(null); setRes(null); setFileName(file.name);
    const r = new FileReader();
    r.onload = () => {
      const rows = parseCSV(String(r.result));
      if (rows.length < 2) { setErr(__('That file looks empty. It needs a header row and at least one product row.', 'bulk-edit-product-for-woocommerce')); return; }
      const head = rows[0]; setTable({ head, body: rows.slice(1) });
      const g = guess(head); setMap(g);
      const hasId = head.some((x) => ['id', 'productid'].includes(norm(x))); const hasSku = head.some((x) => norm(x) === 'sku');
      setMatch(hasSku ? 'sku' : hasId ? 'id' : 'sku');
    };
    r.readAsText(file);
  };

  const keyCol = table ? table.head.findIndex((x) => (match === 'sku' ? norm(x) === 'sku' : ['id', 'productid'].includes(norm(x)))) : -1;
  const build = () => table.body.slice(0, 300).map((row) => {
    const values = {};
    Object.entries(map).forEach(([i, fid]) => { if (fid && +i !== keyCol) values[fid] = row[i]; });
    return { key: row[keyCol], values };
  });
  const usedCols = Object.entries(map).filter(([i, f]) => f && +i !== keyCol).length;
  const go = async (dry) => {
    setBusy(true); setErr('');
    try {
      const r = await api('/import', { method: 'POST', data: { match, dry_run: dry, rows: build() } });
      dry ? setPrev(r) : (setRes(r), onDone && onDone(r));
    } catch (e) { setErr(errMsg(e)); }
    setBusy(false);
  };

  return (
    <Drawer wide title={__('Import from CSV', 'bulk-edit-product-for-woocommerce')} subtitle={__('Update many products from a spreadsheet. Existing products only, nothing is created or deleted.', 'bulk-edit-product-for-woocommerce')} onClose={onClose}
      footer={!res && <Fragment><Btn onClick={onClose}>{__('Cancel', 'bulk-edit-product-for-woocommerce')}</Btn>
        {table && !prev && <Btn kind="primary" disabled={busy || keyCol < 0 || !usedCols} onClick={() => go(true)}>{busy ? __('Checking…', 'bulk-edit-product-for-woocommerce') : __('Preview changes', 'bulk-edit-product-for-woocommerce')}</Btn>}
        {prev && <Btn kind="primary" icon="bolt" disabled={busy || !prev.summary.changed} onClick={() => go(false)}>{sprintf(__('Import %d products', 'bulk-edit-product-for-woocommerce'), prev.summary.changed)}</Btn>}</Fragment>}>
      {res ? (
        <div className="gmbpu-done"><div className="gmbpu-done__ic"><Icon n="check" s={30} /></div><h3>{sprintf(__('%d values imported', 'bulk-edit-product-for-woocommerce'), res.applied)}</h3>
          {res.errors.length > 0 && <p>{sprintf(__('%d values were skipped.', 'bulk-edit-product-for-woocommerce'), res.errors.length)}</p>}
          <p className="gmbpu-muted">{__('You can undo this import from History.', 'bulk-edit-product-for-woocommerce')}</p></div>
      ) : (
        <Fragment>
          {err && <div className="gmbpu-alert" role="alert">{err}</div>}
          <section className="gmbpu-sec">
            <h3>{__('1. Choose your file', 'bulk-edit-product-for-woocommerce')}</h3>
            <label className="gmbpu-drop"><Icon n="upload" s={22} /><b>{fileName || __('Click to choose a .csv file', 'bulk-edit-product-for-woocommerce')}</b><span>{__('Tip: use Export first, edit in Excel or Google Sheets, then import it back. Up to 300 rows at a time.', 'bulk-edit-product-for-woocommerce')}</span>
              <input type="file" accept=".csv,text/csv" onChange={(e) => onFile(e.target.files[0])} /></label>
          </section>
          {table && (
            <section className="gmbpu-sec">
              <h3>{__('2. Match products and columns', 'bulk-edit-product-for-woocommerce')}</h3>
              <div className="gmbpu-op"><span className="gmbpu-muted">{__('Find each product by', 'bulk-edit-product-for-woocommerce')}</span>
                <select className="gmbpu-select gmbpu-select--lg" value={match} onChange={(e) => { setMatch(e.target.value); setPrev(null); }}><option value="sku">{__('SKU (column named SKU)', 'bulk-edit-product-for-woocommerce')}</option><option value="id">{__('Product ID (column named ID)', 'bulk-edit-product-for-woocommerce')}</option></select></div>
              {keyCol < 0 && <div className="gmbpu-alert">{__('We could not find that column in your file. Add one named SKU or ID.', 'bulk-edit-product-for-woocommerce')}</div>}
              <table className="gmbpu-map"><thead><tr><th>{__('Column in your file', 'bulk-edit-product-for-woocommerce')}</th><th>{__('Example', 'bulk-edit-product-for-woocommerce')}</th><th>{__('Update this field', 'bulk-edit-product-for-woocommerce')}</th></tr></thead>
                <tbody>{table.head.map((hd, i) => (
                  <tr key={i}><td>{hd}{i === keyCol && <span className="gmbpu-badge">{__('match key', 'bulk-edit-product-for-woocommerce')}</span>}</td><td className="gmbpu-muted">{(table.body[0] || [])[i]}</td>
                    <td>{i === keyCol ? '—' : <select className="gmbpu-select" value={map[i] || ''} onChange={(e) => { setMap({ ...map, [i]: e.target.value }); setPrev(null); }}><option value="">{__('Ignore', 'bulk-edit-product-for-woocommerce')}</option>{editable.map((f) => <option key={f.id} value={f.id}>{f.label}</option>)}</select>}</td></tr>))}</tbody></table>
            </section>
          )}
          {prev && (
            <section className="gmbpu-sec">
              <h3>{__('3. Review', 'bulk-edit-product-for-woocommerce')}</h3>
              <p>{sprintf(__('%1$d products will change, %2$d are already up to date.', 'bulk-edit-product-for-woocommerce'), prev.summary.changed, prev.summary.unchanged)}</p>
              {prev.missing_count > 0 && <div className="gmbpu-alert">{sprintf(__('%d rows were not found in your store and will be skipped.', 'bulk-edit-product-for-woocommerce'), prev.missing_count)} {prev.missing.slice(0, 5).join(', ')}</div>}
              <div className="gmbpu-preview">{prev.rows.slice(0, 15).map((r) => (
                <div key={r.id} className="gmbpu-prow"><div className="gmbpu-prow__n"><b>{r.name}</b><span>#{r.id}</span></div>
                  <div className="gmbpu-prow__c">{Object.keys(r.changes).map((k) => { const f = boot.fieldMap[k]; return <div key={k} className="gmbpu-diff"><em>{f.label}</em><s>{fmtVal(f, r.changes[k][0], boot) || '—'}</s><Icon n="chev" s={12} /><strong>{fmtVal(f, r.changes[k][1], boot) || '—'}</strong></div>; })}
                    {r.notes.map((n, i) => <div key={i} className={`gmbpu-note gmbpu-note--${n.status}`}>{(boot.fieldMap[n.field] || {}).label}: {boot.reasons[n.reason] || n.reason}</div>)}</div></div>))}</div>
            </section>
          )}
        </Fragment>
      )}
    </Drawer>
  );
}
