import { h, Fragment, useState, useEffect, useRef } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

const P = {
  search: 'M11 4a7 7 0 105.2 11.7l4 4 1.4-1.4-4-4A7 7 0 0011 4zm0 2a5 5 0 110 10 5 5 0 010-10z',
  filter: 'M3 5h18l-7 8v6l-4-2v-4L3 5z',
  columns: 'M4 4h5v16H4V4zm7 0h5v16h-5V4zm7 0h2v16h-2V4z',
  history: 'M13 3a9 9 0 100 18 9 9 0 000-18zm-1 4h2v5l4 2-1 1.7-5-2.7V7zM3 12H1l3-3 3 3H5',
  upload: 'M5 20h14v-2H5v2zM12 4l-6 6h4v6h4v-6h4l-6-6z',
  download: 'M5 20h14v-2H5v2zM12 16l6-6h-4V4h-4v6H6l6 6z',
  bolt: 'M13 2L4 14h6l-1 8 9-12h-6l1-8z',
  check: 'M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z',
  x: 'M18.3 5.7L12 12l6.3 6.3-1.4 1.4L10.6 13.4 4.3 19.7 2.9 18.3 9.2 12 2.9 5.7 4.3 4.3l6.3 6.3 6.3-6.3 1.4 1.4z',
  chev: 'M8.6 5.6L15 12l-6.4 6.4-1.4-1.4L12.2 12 7.2 7l1.4-1.4z',
  plus: 'M11 5h2v6h6v2h-6v6h-2v-6H5v-2h6V5z',
  trash: 'M6 19a2 2 0 002 2h8a2 2 0 002-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z',
  copy: 'M16 1H4a2 2 0 00-2 2v14h2V3h12V1zm3 4H8a2 2 0 00-2 2v14a2 2 0 002 2h11a2 2 0 002-2V7a2 2 0 00-2-2zm0 16H8V7h11v14z',
  help: 'M12 2a10 10 0 100 20 10 10 0 000-20zm1 17h-2v-2h2v2zm2-7.5c-.7.6-1.3 1-1.5 1.5-.2.3-.2.7-.2 1H11c0-1 .1-1.6.5-2.2.4-.6 1.2-1.1 1.5-1.4.3-.3.5-.7.5-1.1 0-.8-.7-1.5-1.5-1.5S10.5 9.7 10.5 10.5H8.5C8.5 8.6 10 7 12 7s3.5 1.6 3.5 3.5c0 .4-.2.7-.5 1z',
  img: 'M21 19V5a2 2 0 00-2-2H5a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2zM8.5 13.5l2.5 3 3.5-4.5 4.5 6H5l3.5-4.5z',
  undo: 'M12.5 8c-2.7 0-5.1 1-7 2.6L2 7v9h9l-3.6-3.6A8 8 0 0120 15l1.9-.6A10 10 0 0012.5 8z',
  ext: 'M14 3v2h3.6l-9.8 9.8 1.4 1.4L19 6.4V10h2V3h-7zM5 5h6V3H5a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-6h-2v6H5V5z',
  star: 'M12 17.3l6.2 3.7-1.6-7L22 9.2l-7.2-.6L12 2 9.2 8.6 2 9.2 7.4 14l-1.6 7z',
  bookmark: 'M17 3H7a2 2 0 00-2 2v16l7-3 7 3V5a2 2 0 00-2-2z',
  alert: 'M12 2L1 21h22L12 2zm1 15h-2v-2h2v2zm0-4h-2V9h2v4z',
  rows: 'M3 5h18v3H3V5zm0 5.5h18v3H3v-3zM3 16h18v3H3v-3z',
};
export const Icon = ({ n, s = 16 }) => (
  <svg className="gmbpu-ic" width={s} height={s} viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d={P[n] || P.help} /></svg>
);

export const Btn = ({ kind = 'ghost', icon, children, className = '', ...rest }) => (
  <button type="button" className={`gmbpu-btn gmbpu-btn--${kind} ${className}`} {...rest}>
    {icon && <Icon n={icon} />}{children && <span>{children}</span>}
  </button>
);

export function useOutside(ref, cb, active = true) {
  useEffect(() => {
    if (!active) return;
    const f = (e) => { if (ref.current && !ref.current.contains(e.target)) cb(); };
    const k = (e) => { if (e.key === 'Escape') cb(); };
    document.addEventListener('mousedown', f); document.addEventListener('keydown', k);
    return () => { document.removeEventListener('mousedown', f); document.removeEventListener('keydown', k); };
  }, [active]);
}

export function Popover({ trigger, children, align = 'left', width, fixed }) {
  const [open, setOpen] = useState(false);
  const [pos, setPos] = useState(null);
  const ref = useRef();
  useOutside(ref, () => setOpen(false), open);
  const toggle = () => {
    if (!open && fixed && ref.current) {
      const r = ref.current.getBoundingClientRect(); const w = width || 260;
      const left = Math.max(8, Math.min(r.left, window.innerWidth - w - 8));
      const below = window.innerHeight - r.bottom > 300;
      setPos({ left, top: below ? r.bottom + 6 : undefined, bottom: below ? undefined : window.innerHeight - r.top + 6 });
    }
    setOpen(!open);
  };
  const style = Object.assign({}, width ? { width } : null, fixed && pos ? { position: 'fixed', left: pos.left, top: pos.top, bottom: pos.bottom, right: 'auto' } : null);
  return (
    <span className="gmbpu-pop" ref={ref}>
      {trigger({ open, toggle })}
      {open && <div className={`gmbpu-pop__panel gmbpu-pop__panel--${align}`} style={style} role="dialog">{children({ close: () => setOpen(false) })}</div>}
    </span>
  );
}

export function Drawer({ title, subtitle, onClose, children, footer, wide }) {
  useEffect(() => { const k = (e) => e.key === 'Escape' && onClose(); document.addEventListener('keydown', k); return () => document.removeEventListener('keydown', k); }, []);
  return (
    <div className="gmbpu-overlay" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
      <aside className={`gmbpu-drawer ${wide ? 'is-wide' : ''}`} role="dialog" aria-modal="true" aria-label={title}>
        <header className="gmbpu-drawer__head">
          <div><h2>{title}</h2>{subtitle && <p>{subtitle}</p>}</div>
          <button type="button" className="gmbpu-iconbtn" onClick={onClose} aria-label={__('Close', 'bulk-edit-product-for-woocommerce')}><Icon n="x" s={18} /></button>
        </header>
        <div className="gmbpu-drawer__body">{children}</div>
        {footer && <footer className="gmbpu-drawer__foot">{footer}</footer>}
      </aside>
    </div>
  );
}

export function Modal({ title, onClose, children, footer }) {
  return (
    <div className="gmbpu-overlay gmbpu-overlay--center" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
      <div className="gmbpu-modal" role="dialog" aria-modal="true" aria-label={title}>
        <h2>{title}</h2>
        <div className="gmbpu-modal__body">{children}</div>
        {footer && <div className="gmbpu-modal__foot">{footer}</div>}
      </div>
    </div>
  );
}

export const Toasts = ({ items, dismiss }) => (
  <div className="gmbpu-toasts" role="status" aria-live="polite">
    {items.map((t) => (
      <div key={t.id} className={`gmbpu-toast gmbpu-toast--${t.kind || 'info'}`}>
        <Icon n={t.kind === 'error' ? 'alert' : 'check'} />
        <span>{t.text}</span>
        {t.action && <button type="button" onClick={() => { t.action.run(); dismiss(t.id); }}>{t.action.label}</button>}
        <button type="button" className="gmbpu-toast__x" onClick={() => dismiss(t.id)} aria-label={__('Dismiss', 'bulk-edit-product-for-woocommerce')}><Icon n="x" s={14} /></button>
      </div>
    ))}
  </div>
);

export const Field = ({ label, hint, children }) => (
  <label className="gmbpu-field"><span className="gmbpu-field__l">{label}</span>{children}{hint && <span className="gmbpu-field__h">{hint}</span>}</label>
);

export const Empty = ({ icon = 'search', title, children }) => (
  <div className="gmbpu-empty"><div className="gmbpu-empty__ic"><Icon n={icon} s={28} /></div><h3>{title}</h3><p>{children}</p></div>
);

/** Autocomplete multi-select of terms. Enter picks the highlighted match; with onCreate, Enter on new text creates it. */
export function TermPicker({ list, value, onChange, single, onCreate }) {
  const [q, setQ] = useState('');
  const [active, setActive] = useState(0);
  const [busy, setBusy] = useState(false);
  const sel = new Set(value || []);
  const needle = q.trim().toLowerCase();
  const shown = list.filter((t) => t.name.toLowerCase().includes(needle)).sort((a, b) => (b.name.toLowerCase().startsWith(needle) ? 1 : 0) - (a.name.toLowerCase().startsWith(needle) ? 1 : 0)).slice(0, 200);
  const exact = list.some((t) => t.name.toLowerCase() === needle);
  const canCreate = onCreate && needle && !exact;
  useEffect(() => { setActive(0); }, [q]);
  const toggle = (id) => { if (single) { onChange([id]); return; } const n = new Set(sel); n.has(id) ? n.delete(id) : n.add(id); onChange([...n]); };
  const create = async () => {
    if (busy) return; setBusy(true);
    try { const id = await onCreate(q.trim()); toggle(id); setQ(''); } catch (e) { /* shown by caller */ }
    setBusy(false);
  };
  const onKey = (e) => {
    const max = shown.length + (canCreate ? 1 : 0) - 1;
    if (e.key === 'ArrowDown') { e.preventDefault(); setActive(Math.min(max, active + 1)); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); setActive(Math.max(0, active - 1)); }
    else if (e.key === 'Enter') {
      e.preventDefault();
      if (active < shown.length && shown[active]) { toggle(shown[active].id); setQ(''); }
      else if (canCreate) create();
    }
  };
  useEffect(() => { const el = document.querySelector('.gmbpu-terms li.is-active'); el && el.scrollIntoView && el.scrollIntoView({ block: 'nearest' }); }, [active]);
  return (
    <div className="gmbpu-terms">
      <input type="search" className="gmbpu-input" placeholder={onCreate ? __('Search or type to add…', 'bulk-edit-product-for-woocommerce') : __('Search…', 'bulk-edit-product-for-woocommerce')} value={q} onChange={(e) => setQ(e.target.value)} onKeyDown={onKey} autoFocus />
      <ul>
        {shown.map((t, i) => (
          <li key={t.id} className={i === active ? 'is-active' : ''}>
            <label><input type={single ? 'radio' : 'checkbox'} checked={sel.has(t.id)} onChange={() => toggle(t.id)} /> <span>{t.name}</span><em>{t.count}</em></label>
          </li>
        ))}
        {canCreate && <li className={shown.length === active ? 'is-active' : ''}><button type="button" className="gmbpu-terms__add" onClick={create} disabled={busy}>{__('Add', 'bulk-edit-product-for-woocommerce')} “{q.trim()}”<kbd>Enter</kbd></button></li>}
        {!shown.length && !canCreate && <li className="gmbpu-terms__none">{__('Nothing found', 'bulk-edit-product-for-woocommerce')}</li>}
      </ul>
      <p className="gmbpu-terms__hint">{__('Type, then press Enter to select. ↑ ↓ to move.', 'bulk-edit-product-for-woocommerce')}</p>
    </div>
  );
}

export function pickImage(cb) {
  if (!window.wp || !window.wp.media) return;
  const frame = window.wp.media({ title: __('Choose product image', 'bulk-edit-product-for-woocommerce'), multiple: false, library: { type: 'image' } });
  frame.on('select', () => { const a = frame.state().get('selection').first().toJSON(); cb(a.id, (a.sizes && a.sizes.thumbnail ? a.sizes.thumbnail.url : a.url)); });
  frame.open();
}
