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

const TYPES = () => [['text', __('Text', 'bulk-edit-product-for-woocommerce')], ['html', __('Long text', 'bulk-edit-product-for-woocommerce')], ['number', __('Number', 'bulk-edit-product-for-woocommerce')], ['bool', __('Yes / No', 'bulk-edit-product-for-woocommerce')], ['date', __('Date', 'bulk-edit-product-for-woocommerce')]];
const keyOk = (k) => /^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(k);

export default function CustomFields({ onClose, onSaved }) {
  const [data, setData] = useState(null);
  const [on, setOn] = useState({}); // key -> {key,label,type}
  const [q, setQ] = useState('');
  const [manual, setManual] = useState('');
  const [err, setErr] = useState('');
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    api('/custom-fields').then((r) => {
      setData(r); const m = {}; r.enabled.forEach((e) => { m[e.key] = { key: e.key, label: e.label, type: e.type }; }); setOn(m);
    }).catch((e) => setErr(errMsg(e)));
  }, []);

  const avail = data ? data.available : [];
  const extra = Object.values(on).filter((o) => !avail.some((a) => a.key === o.key)).map((o) => ({ key: o.key, label: o.label, type: o.type, source: 'meta', group: __('Custom fields', 'bulk-edit-product-for-woocommerce') }));
  const all = [...avail, ...extra].filter((a) => (a.label + a.key).toLowerCase().includes(q.toLowerCase()));
  const groups = {}; all.forEach((a) => { (groups[a.group || 'Other'] = groups[a.group || 'Other'] || []).push(a); });

  const toggle = (a) => { const n = { ...on }; n[a.key] ? delete n[a.key] : (n[a.key] = { key: a.key, label: a.label, type: a.type }); setOn(n); };
  const addManual = () => {
    const k = manual.trim();
    if (!keyOk(k)) { setErr(__('Use letters, numbers, dashes or underscores, starting with a letter. Keys beginning with an underscore are private and cannot be used.', 'bulk-edit-product-for-woocommerce')); return; }
    setErr(''); setOn({ ...on, [k]: { key: k, label: k, type: 'text' } }); setManual('');
  };
  const save = async () => {
    setBusy(true); setErr('');
    try { const r = await api('/custom-fields', { method: 'POST', data: { fields: Object.values(on) } }); await onSaved(r.enabled); }
    catch (e) { setErr(errMsg(e)); setBusy(false); }
  };

  return (
    <Drawer wide title={__('Custom fields & ACF', 'bulk-edit-product-for-woocommerce')} subtitle={__('Choose extra fields to show as columns. They work with bulk edit, history, undo and CSV import/export.', 'bulk-edit-product-for-woocommerce')} onClose={onClose}
      footer={<Fragment><span className="gmbpu-foot-note">{sprintf(__('%d fields selected', 'bulk-edit-product-for-woocommerce'), Object.keys(on).length)}</span><Btn onClick={onClose}>{__('Cancel', 'bulk-edit-product-for-woocommerce')}</Btn><Btn kind="primary" icon="check" disabled={busy || !data} onClick={save}>{busy ? __('Saving…', 'bulk-edit-product-for-woocommerce') : __('Save fields', 'bulk-edit-product-for-woocommerce')}</Btn></Fragment>}>
      {err && <div className="gmbpu-alert" role="alert">{err}</div>}
      {!data && !err && <p className="gmbpu-muted"><span className="gmbpu-spin" /> {__('Looking for custom fields…', 'bulk-edit-product-for-woocommerce')}</p>}
      {data && (
        <Fragment>
          <p className="gmbpu-muted">{data.acf ? __('Advanced Custom Fields detected. Its text, number, select and yes/no fields are listed with their proper names.', 'bulk-edit-product-for-woocommerce') : __('These are custom fields already saved on your products. If you use ACF, install and activate it to see its fields here with proper labels.', 'bulk-edit-product-for-woocommerce')}</p>
          <input className="gmbpu-input gmbpu-cf-search" type="search" placeholder={__('Find a field…', 'bulk-edit-product-for-woocommerce')} value={q} onChange={(e) => setQ(e.target.value)} />
          {Object.keys(groups).map((g) => (
            <section key={g} className="gmbpu-sec">
              <h3>{g}</h3>
              <ul className="gmbpu-cflist">{groups[g].map((a) => (
                <li key={a.key} className={on[a.key] ? 'is-on' : ''}>
                  <label className="gmbpu-check"><input type="checkbox" checked={!!on[a.key]} onChange={() => toggle(a)} /><span><b>{a.label}</b>{a.label !== a.key && <em>{a.key}</em>}</span></label>
                  {on[a.key] && a.source !== 'acf' && (
                    <select className="gmbpu-select" value={on[a.key].type} onChange={(e) => setOn({ ...on, [a.key]: { ...on[a.key], type: e.target.value } })} aria-label={__('Field type', 'bulk-edit-product-for-woocommerce')}>{TYPES().map(([v, l]) => <option key={v} value={v}>{l}</option>)}</select>
                  )}
                  {a.source === 'acf' && <span className="gmbpu-badge">ACF</span>}
                </li>))}</ul>
            </section>
          ))}
          {!all.length && <p className="gmbpu-muted">{__('No matching fields. You can add one by its key below.', 'bulk-edit-product-for-woocommerce')}</p>}
          <section className="gmbpu-sec">
            <h3>{__('Add a field by key', 'bulk-edit-product-for-woocommerce')}</h3>
            <div className="gmbpu-op"><input className="gmbpu-input" placeholder="my_custom_field" value={manual} onChange={(e) => setManual(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && (e.preventDefault(), addManual())} /><Btn kind="soft" icon="plus" onClick={addManual}>{__('Add', 'bulk-edit-product-for-woocommerce')}</Btn></div>
          </section>
        </Fragment>
      )}
    </Drawer>
  );
}
