/* global React, Button, Input, Ic, VS, LoadingState, ErrorState */

// ============================================================
// NORM PICKER — modal z listą norm + podglądem opisu
// ============================================================
function NormPicker({ currentId, onPick, onClose }) {
  const [list, setList] = React.useState(null);
  const [err, setErr] = React.useState('');
  const [q, setQ] = React.useState('');
  const [previewId, setPreviewId] = React.useState(currentId || null);

  React.useEffect(() => {
    VS.norms()
      .then((r) => setList(r || []))
      .catch((e) => setErr(e.message));
  }, []);

  React.useEffect(() => {
    function onKey(e) { if (e.key === 'Escape') onClose && onClose(); }
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);

  const filtered = React.useMemo(() => {
    if (!list) return [];
    const qq = (q || '').trim().toLowerCase();
    if (!qq) return list;
    return list.filter((it) =>
      (it.numer || '').toLowerCase().includes(qq) ||
      (it.wartosci || '').toLowerCase().includes(qq) ||
      (it.opis || '').toLowerCase().includes(qq)
    );
  }, [list, q]);

  const preview = React.useMemo(
    () => (list || []).find((n) => n.id === previewId) || null,
    [list, previewId]
  );

  function confirm() {
    const item = (list || []).find((n) => n.id === previewId);
    if (!item) return;
    if (onPick) onPick(item.id, item.numer || item.wartosci || '');
    if (onClose) onClose();
  }

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 1000,
      background: 'rgba(0,0,0,0.45)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 24,
    }}
      onClick={onClose}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: 'min(1100px, 100%)',
          maxHeight: 'calc(100vh - 48px)',
          background: 'var(--bg)',
          border: '1px solid var(--border)',
          borderRadius: 'var(--r-md)',
          boxShadow: '0 20px 60px rgba(0,0,0,0.35)',
          display: 'flex', flexDirection: 'column',
          overflow: 'hidden',
        }}
      >
        {/* Header */}
        <div style={{
          padding: '14px 18px',
          borderBottom: '1px solid var(--border)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          gap: 12, flexShrink: 0,
        }}>
          <div>
            <div className="uppercase-label" style={{ marginBottom: 4 }}>Biblioteka norm</div>
            <div style={{ fontSize: 15, fontWeight: 500, letterSpacing: '-0.01em' }}>
              Wybierz normę dla protokołu
            </div>
          </div>
          <button
            onClick={onClose}
            title="Zamknij"
            style={{
              width: 28, height: 28, padding: 0,
              background: 'transparent', border: '1px solid var(--border)',
              borderRadius: 'var(--r-sm)', cursor: 'pointer',
              color: 'var(--fg-muted)', fontSize: 16, lineHeight: 1,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}
          >×</button>
        </div>

        {/* Toolbar */}
        <div style={{
          padding: '12px 18px',
          borderBottom: '1px solid var(--hairline)',
          flexShrink: 0,
        }}>
          <div style={{ maxWidth: 340 }}>
            <Input
              icon={<Ic.search size={13} />}
              placeholder="Szukaj normy…"
              value={q}
              onChange={(e) => setQ(e.target.value)}
            />
          </div>
        </div>

        {/* Body: lista (lewo) + podgląd (prawo) */}
        <div style={{
          flex: 1, overflow: 'hidden',
          display: 'grid', gridTemplateColumns: '1fr 1.3fr',
        }}>
          {/* Lista */}
          <div style={{
            overflowY: 'auto',
            borderRight: '1px solid var(--border)',
            background: 'var(--bg-elev)',
          }}>
            {err && <div style={{ padding: 18 }}><ErrorState message={err} /></div>}
            {!err && !list && <div style={{ padding: 18 }}><LoadingState /></div>}
            {!err && list && list.length === 0 && (
              <div style={{ padding: 28, textAlign: 'center', color: 'var(--fg-muted)', fontSize: 13 }}>
                Brak norm w bazie.
              </div>
            )}
            {!err && filtered.length === 0 && list && list.length > 0 && (
              <div style={{ padding: 28, textAlign: 'center', color: 'var(--fg-muted)', fontSize: 13 }}>
                Brak wyników.
              </div>
            )}
            {!err && filtered.map((it) => (
              <NormRow
                key={it.id}
                norm={it}
                selected={previewId === it.id}
                current={currentId === it.id}
                onClick={() => setPreviewId(it.id)}
                onDoubleClick={() => { if (onPick) onPick(it.id, it.numer || ''); if (onClose) onClose(); }}
              />
            ))}
          </div>

          {/* Podgląd */}
          <div style={{
            overflowY: 'auto',
            padding: '18px 22px',
            background: 'var(--bg)',
          }}>
            {!preview && (
              <div style={{
                padding: 60, textAlign: 'center', color: 'var(--fg-subtle)', fontSize: 13,
              }}>
                Wybierz normę z listy aby zobaczyć pełny opis.
              </div>
            )}
            {preview && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                <div>
                  <div className="uppercase-label" style={{ marginBottom: 6 }}>Nazwa</div>
                  <div style={{ fontSize: 16, fontWeight: 500, color: 'var(--fg)' }}>
                    {preview.numer || '—'}
                  </div>
                </div>
                <div>
                  <div className="uppercase-label" style={{ marginBottom: 6 }}>Numer normy</div>
                  <div style={{ fontSize: 13, color: 'var(--fg)', fontFamily: 'var(--font-mono)' }}>
                    {preview.wartosci || '—'}
                  </div>
                </div>
                <div>
                  <div className="uppercase-label" style={{ marginBottom: 6 }}>Opis</div>
                  <div style={{
                    fontSize: 12.5, color: 'var(--fg)',
                    lineHeight: 1.55, whiteSpace: 'pre-wrap',
                    padding: 12, background: 'var(--bg-sunken)',
                    border: '1px solid var(--hairline)', borderRadius: 'var(--r-sm)',
                  }}>
                    {preview.opis || '—'}
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Footer */}
        <div style={{
          padding: '10px 18px',
          borderTop: '1px solid var(--border)',
          background: 'var(--bg-elev)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          flexShrink: 0,
        }}>
          <span className="mono" style={{ fontSize: 11, color: 'var(--fg-subtle)', letterSpacing: '0.04em' }}>
            {list ? `${filtered.length} / ${list.length} norm` : ''}
          </span>
          <div style={{ display: 'flex', gap: 8 }}>
            <Button variant="ghost" onClick={onClose}>Anuluj</Button>
            <Button variant="primary" disabled={!preview} onClick={confirm}>Wybierz</Button>
          </div>
        </div>
      </div>
    </div>
  );
}

function NormRow({ norm, selected, current, onClick, onDoubleClick }) {
  const [hover, setHover] = React.useState(false);
  const bg = selected
    ? 'var(--bg-sunken)'
    : hover
      ? 'var(--surface)'
      : 'transparent';
  return (
    <div
      onClick={onClick}
      onDoubleClick={onDoubleClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        padding: '10px 14px',
        borderBottom: '1px solid var(--hairline)',
        cursor: 'pointer',
        background: bg,
        display: 'flex', flexDirection: 'column', gap: 3,
      }}
    >
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <div style={{
          fontSize: 12.5, fontWeight: 500, color: 'var(--fg)',
          flex: 1,
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        }} title={norm.numer || ''}>
          {norm.numer || '—'}
        </div>
        {current && (
          <span className="mono" style={{
            fontSize: 9, padding: '1px 6px',
            color: 'var(--accent)', border: '1px solid var(--accent-border)',
            borderRadius: 2, letterSpacing: '0.06em', textTransform: 'uppercase',
          }}>aktualna</span>
        )}
      </div>
      <div style={{
        fontSize: 11, color: 'var(--fg-muted)', fontFamily: 'var(--font-mono)',
        overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
      }} title={norm.wartosci || ''}>
        {norm.wartosci || '—'}
      </div>
    </div>
  );
}

Object.assign(window, { NormPicker });
