import { h, Fragment, useState, useEffect, useRef } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { Icon, Popover, TermPicker, pickImage } from './ui.jsx';
import { fmtVal } from './util.js';
import { createTerm, errMsg } from './api.js';

function TextCell({ field, value, boot, onCommit, nextCell }) {
  const [edit, setEdit] = useState(false);
  const [draft, setDraft] = useState('');
  const ref = useRef();
  useEffect(() => { if (edit && ref.current) { ref.current.focus(); ref.current.select && ref.current.select(); } }, [edit]);
  const start = () => { setDraft(value === null || value === undefined ? '' : String(value)); setEdit(true); };
  const commit = (move) => { setEdit(false); if (String(draft) !== String(value ?? '')) onCommit(draft); if (move) nextCell(); };
  if (!edit) {
    const text = fmtVal(field, value, boot);
    return <button type="button" className={`gmbpu-val ${text === '' ? 'is-empty' : ''}`} onClick={start} onFocus={start} title={text}>{text === '' ? '—' : text}</button>;
  }
  const type = field.type === 'date' ? (field.id === 'date_created' ? 'datetime-local' : 'date') : (field.type === 'price' || field.type === 'number') ? 'number' : 'text';
  const common = {
    ref, value: draft, className: 'gmbpu-input gmbpu-input--cell',
    onChange: (e) => setDraft(e.target.value), onBlur: () => commit(false),
    onKeyDown: (e) => { if (e.key === 'Enter' && !(field.type === 'html' && e.shiftKey)) { e.preventDefault(); commit(true); } if (e.key === 'Escape') { setEdit(false); } },
  };
  if (field.type === 'html') return <textarea {...common} rows={3} />;
  return <input {...common} type={type} step={field.type === 'price' ? 'any' : field.decimal ? 'any' : 1} min={field.type === 'price' ? 0 : undefined} />;
}

function Cell({ row, field, value, boot, dirty, error, onEdit, nextCell, locked }) {
  const cls = `gmbpu-cell gmbpu-cell--${field.type} ${dirty ? 'is-dirty' : ''} ${error ? 'is-error' : ''} ${locked ? 'is-locked' : ''}`;
  const attrs = { 'data-col': field.id, 'data-row': row.id };
  let body;
  if (locked || !field.editable) {
    const t = field.id === 'id' ? row.id : fmtVal(field, value, boot);
    body = <span className="gmbpu-val is-static">{locked && field.editable ? <em title={__('Not editable for this product', 'bulk-edit-product-for-woocommerce')}>—</em> : (t === '' ? '—' : t)}</span>;
  } else if (field.type === 'bool') {
    body = <label className="gmbpu-switch"><input type="checkbox" checked={!!value} onChange={(e) => onEdit(e.target.checked)} /><i /></label>;
  } else if (field.type === 'select') {
    body = <select className="gmbpu-select" value={String(value ?? '')} onChange={(e) => onEdit(e.target.value)}>{(field.options || []).map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}</select>;
  } else if (field.type === 'terms') {
    const list = field.taxonomy === 'product_tag' ? boot.tags : boot.cats;
    const names = (value || []).map((id) => (list.find((t) => t.id === id) || { name: '#' + id }).name);
    body = (
      <Popover fixed width={280} trigger={({ toggle }) => (
        <button type="button" className="gmbpu-chips" onClick={toggle}>
          {names.length ? names.slice(0, 2).map((n) => <span key={n} className="gmbpu-chip">{n}</span>) : <span className="gmbpu-val is-empty">—</span>}
          {names.length > 2 && <span className="gmbpu-chip gmbpu-chip--more">+{names.length - 2}</span>}
        </button>)}>
        {() => <TermPicker list={list} value={value} onChange={onEdit} onCreate={boot.can_create_terms ? (n) => createTerm(boot, field.taxonomy, n) : null} />}
      </Popover>
    );
  } else if (field.type === 'image') {
    body = (
      <button type="button" className="gmbpu-thumb" onClick={() => pickImage((id, url) => { row.thumb = url; onEdit(id); })} title={__('Change image', 'bulk-edit-product-for-woocommerce')}>
        {row.thumb || value ? <img src={row.thumb} alt="" /> : <Icon n="img" s={18} />}
      </button>
    );
  } else {
    body = <TextCell field={field} value={value} boot={boot} onCommit={onEdit} nextCell={nextCell} />;
  }
  return <td className={cls} {...attrs}>{body}{error && <span className="gmbpu-cell__err" role="alert">{error}</span>}</td>;
}

export default function Grid({ boot, rows, kids, expanded, cols, pending, errors, selected, setSelected, onEdit, sort, setSort, onExpand, density, loading, onDuplicate, onTrash }) {
  const allChecked = rows.length > 0 && rows.every((r) => selected.has(r.id));
  const nextCellFor = (row, field) => () => setTimeout(() => {
    const tds = [...document.querySelectorAll(`[data-col="${field.id}"][data-row]`)];
    const i = tds.findIndex((td) => td.dataset.row === String(row.id));
    for (let j = i + 1; j < tds.length; j++) { const b = tds[j].querySelector('.gmbpu-val:not(.is-static)'); if (b) { b.click(); return; } }
  }, 20);
  const toggleAll = () => { const n = new Set(selected); rows.forEach((r) => (allChecked ? n.delete(r.id) : n.add(r.id))); setSelected(n); };
  const flat = [];
  rows.forEach((r) => { flat.push({ r, child: false }); if (expanded.has(r.id)) (kids[r.id] || []).forEach((k) => flat.push({ r: k, child: true })); });
  const sortable = { name: 'title', sku: 'sku', regular_price: 'price', stock_quantity: 'stock', date_created: 'date', menu_order: 'menu_order', id: 'id' };

  const renderRow = ({ r, child }) => {
    const pend = pending[r.id] || {};
    const val = (f) => (f in pend ? pend[f] : r.values[f]);
    const nameField = boot.fieldMap.name;
    const nameDirty = 'name' in pend;
    return (
      <tr key={(child ? 'v' : 'p') + r.id} className={`${selected.has(r.id) ? 'is-selected' : ''} ${child ? 'is-child' : ''}`}>
        <td className="gmbpu-sel"><input type="checkbox" checked={selected.has(r.id)} onChange={() => { const n = new Set(selected); n.has(r.id) ? n.delete(r.id) : n.add(r.id); setSelected(n); }} aria-label={__('Select row', 'bulk-edit-product-for-woocommerce')} /></td>
        <td className={`gmbpu-namecell ${nameDirty ? 'is-dirty' : ''}`} data-col="name" data-row={r.id}>
          <div className="gmbpu-namewrap">
            {r.type === 'variable' && !child ? (
              <button type="button" className={`gmbpu-expander ${expanded.has(r.id) ? 'is-open' : ''}`} onClick={() => onExpand(r)} aria-expanded={expanded.has(r.id)} title={__('Show variations', 'bulk-edit-product-for-woocommerce')}><Icon n="chev" s={14} /></button>
            ) : <span className="gmbpu-expander-sp" />}
            {!child && <span className="gmbpu-mini">{r.thumb ? <img src={r.thumb} alt="" /> : <Icon n="img" s={14} />}</span>}
            <div className="gmbpu-namebox">
              {child || r.locked.includes('name') ? <span className="gmbpu-val is-static">{r.name}</span>
                : <TextCell field={nameField} value={val('name')} boot={boot} onCommit={(v) => onEdit(r.id, 'name', v)} nextCell={nextCellFor(r, nameField)} />}
              <div className="gmbpu-meta">
                <span className={`gmbpu-badge gmbpu-badge--${r.type}`}>{child ? __('variation', 'bulk-edit-product-for-woocommerce') : r.type}</span>
                <span>#{r.id}</span>
                {!child && <Fragment><a href={r.edit_url} target="_blank" rel="noopener">{__('Edit', 'bulk-edit-product-for-woocommerce')}</a><a href={r.view_url} target="_blank" rel="noopener">{__('View', 'bulk-edit-product-for-woocommerce')}</a>
                  <button type="button" onClick={() => onDuplicate(r.id)}>{__('Duplicate', 'bulk-edit-product-for-woocommerce')}</button>
                  {boot.can_delete && <button type="button" className="is-danger" onClick={() => onTrash(r)}>{__('Trash', 'bulk-edit-product-for-woocommerce')}</button>}</Fragment>}
              </div>
            </div>
          </div>
        </td>
        {cols.map((f) => (
          <Cell key={f.id} row={r} field={f} boot={boot} value={val(f.id)} dirty={f.id in pend} error={errors[r.id + ':' + f.id]}
            locked={r.locked.includes(f.id)} onEdit={(v) => onEdit(r.id, f.id, v)} nextCell={nextCellFor(r, f)} />
        ))}
      </tr>
    );
  };

  return (
    <div className={`gmbpu-gridwrap gmbpu-density--${density} ${loading ? 'is-loading' : ''}`}>
      <table className="gmbpu-grid">
        <thead><tr>
          <th className="gmbpu-sel"><input type="checkbox" checked={allChecked} onChange={toggleAll} aria-label={__('Select all on this page', 'bulk-edit-product-for-woocommerce')} /></th>
          <th className="gmbpu-namecell" style={{ minWidth: 300 }}><SortHead id="name" label={__('Product', 'bulk-edit-product-for-woocommerce')} sort={sort} setSort={setSort} map="title" /></th>
          {cols.map((f) => <th key={f.id} style={{ minWidth: f.width }}><SortHead id={f.id} label={f.label} sort={sort} setSort={setSort} map={sortable[f.id]} /></th>)}
        </tr></thead>
        <tbody>{flat.map(renderRow)}</tbody>
      </table>
    </div>
  );
}

function SortHead({ id, label, sort, setSort, map }) {
  if (!map) return <span className="gmbpu-th">{label}</span>;
  const on = sort.orderby === map;
  return (
    <button type="button" className={`gmbpu-th gmbpu-th--sort ${on ? 'is-on' : ''}`} onClick={() => setSort({ orderby: map, order: on && sort.order === 'asc' ? 'desc' : 'asc' })}>
      {label}<span className="gmbpu-sortarrow">{on ? (sort.order === 'asc' ? '↑' : '↓') : '↕'}</span>
    </button>
  );
}
