/* global React, Icon, Card, Overline, Button, TextField */
// Schools.ArtemenkoCRM — Настройки (справочники CRM)

// Reusable editable chip-list for a dictionary array (mutates in place + forces re-render).
function DictEditor({ title, hint, items, onChange, color }) {
  const [val, setVal] = React.useState('');
  const [editIdx, setEditIdx] = React.useState(-1);
  const [editVal, setEditVal] = React.useState('');
  const accent = color || 'var(--brand)';

  const add = () => { const v = val.trim(); if (!v || items.includes(v)) { setVal(''); return; } onChange([...items, v]); setVal(''); };
  const remove = (i) => onChange(items.filter((_, idx) => idx !== i));
  const saveEdit = () => { const v = editVal.trim(); if (v) onChange(items.map((x, idx) => idx === editIdx ? v : x)); setEditIdx(-1); setEditVal(''); };

  return (
    <Card pad={22}>
      <Overline>{title}</Overline>
      {hint && <div style={{ fontSize: 12.5, color: 'var(--text-dim)', marginTop: 6, lineHeight: 1.45 }}>{hint}</div>}
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 16 }}>
        {items.map((it, i) => editIdx === i ? (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
            <input autoFocus value={editVal} onChange={e => setEditVal(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') saveEdit(); if (e.key === 'Escape') setEditIdx(-1); }}
              style={{ border: '1px solid var(--brand)', boxShadow: 'var(--shadow-focus)', borderRadius: 'var(--radius-sm)', padding: '5px 9px', fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--text)', outline: 'none', width: 130 }} />
            <button onClick={saveEdit} style={{ width: 28, height: 28, borderRadius: 6, border: 'none', background: 'var(--brand)', color: '#fff', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="check" size={14} strokeWidth={2.5} /></button>
          </div>
        ) : (
          <span key={i} className="om-fade-in" style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '5px 8px 5px 12px', borderRadius: 'var(--radius-pill)', background: 'var(--bg-soft)', border: '1px solid var(--border)', fontSize: 13, fontWeight: 600, color: 'var(--text)' }}>
            <span style={{ width: 7, height: 7, borderRadius: '50%', background: accent }} />{it}
            <button onClick={() => { setEditIdx(i); setEditVal(it); }} title="Изменить" style={{ border: 'none', background: 'none', cursor: 'pointer', color: 'var(--text-dim)', display: 'inline-flex', padding: 2 }}><Icon name="pencil" size={13} /></button>
            <button onClick={() => remove(i)} title="Удалить" style={{ border: 'none', background: 'none', cursor: 'pointer', color: 'var(--text-dim)', display: 'inline-flex', padding: 2 }}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M9.2 9.2l5.6 5.6M14.8 9.2l-5.6 5.6"/></svg>
            </button>
          </span>
        ))}
        {items.length === 0 && <span style={{ fontSize: 13, color: 'var(--text-dim)' }}>Список пуст</span>}
      </div>
      <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
        <input value={val} onChange={e => setVal(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') add(); }} placeholder="Новое значение…"
          style={{ flex: 1, maxWidth: 280, border: '1px solid var(--border)', borderRadius: 'var(--radius-sm)', padding: '9px 12px', fontFamily: 'var(--font-sans)', fontSize: 13.5, color: 'var(--text)', outline: 'none', background: 'var(--bg-card)' }} />
        <Button variant="secondary" icon="plus" onClick={add}>Добавить</Button>
      </div>
    </Card>
  );
}

function Settings({ focus, onToast }) {
  const D = window.CRM_DATA;
  const [, force] = React.useReducer(x => x + 1, 0);
  const [price, setPrice] = React.useState(String(D.SETTINGS.defaultLessonPrice));
  const [country, setCountry] = React.useState(D.SETTINGS.defaultCountry);
  const catRef = React.useRef(null);
  const rolesRef = React.useRef(null);
  const dirRef = React.useRef(null);
  const payRef = React.useRef(null);

  const flash = (ref) => {
    if (!ref.current) return;
    ref.current.scrollIntoView({ behavior: 'smooth', block: 'start' });
    ref.current.style.transition = 'box-shadow 300ms var(--ease)';
    ref.current.style.boxShadow = '0 0 0 3px var(--brand-soft)';
    const t = setTimeout(() => { if (ref.current) ref.current.style.boxShadow = 'none'; }, 1400);
    return () => clearTimeout(t);
  };
  React.useEffect(() => {
    if (focus === 'expense-categories') return flash(catRef);
    if (focus === 'staff-roles') return flash(rolesRef);
    if (focus === 'staff-directions') return flash(dirRef);
    if (focus === 'payment-methods') return flash(payRef);
  }, [focus]);

  // Ключ кита → имя справочника в API (что персистится на бэк).
  const DICT_API = { DIRECTIONS: 'directions', SOURCES: 'sources', PAYMENT_METHODS: 'paymentMethods', EXPENSE_CATEGORIES: 'expenseCategories', TEACHER_POSITIONS: 'teacherPositions', MANAGER_POSITIONS: 'managerPositions' };
  const mutate = (key, next) => {
    D[key] = next; force(); // оптимистично
    const name = DICT_API[key];
    if (name && window.apiCall) {
      window.apiCall('/dictionaries/' + name, { method: 'PUT', body: JSON.stringify({ items: next }) })
        .catch((e) => { if (onToast) onToast('Не удалось сохранить справочник: ' + (e.message || 'ошибка')); });
    }
  };
  // Roles are objects {value,label,kind}; editor works on labels and keeps value/kind.
  const roleLabels = (D.STAFF_ROLES || []).map(r => r.label);
  const setRoleLabels = (labels) => {
    const prev = D.STAFF_ROLES || [];
    D.STAFF_ROLES = labels.map(lb => {
      const ex = prev.find(r => r.label === lb);
      return ex || { value: 'role_' + Math.random().toString(36).slice(2, 7), label: lb, kind: 'account' };
    });
    force();
  };
  const saveDefaults = () => {
    D.SETTINGS.defaultLessonPrice = parseInt(price.replace(/\D/g, ''), 10) || 0;
    D.SETTINGS.defaultCountry = country.trim() || '+7';
    onToast('Настройки сохранены');
  };

  return (
    <div style={{ padding: '24px 32px 48px', maxWidth: 920, display: 'flex', flexDirection: 'column', gap: 20 }}>
      {/* Defaults */}
      <Card pad={22}>
        <Overline>Значения по умолчанию</Overline>
        <div style={{ display: 'flex', gap: 16, marginTop: 16, flexWrap: 'wrap' }}>
          <div style={{ width: 220 }}>
            <label style={{ display: 'block', fontSize: 13, fontWeight: 600, color: 'var(--text-secondary)', marginBottom: 6 }}>Стоимость занятия (₽)</label>
            <TextField value={price} onChange={v => setPrice(v.replace(/\D/g, ''))} placeholder="1800" mono />
            <div style={{ fontSize: 11.5, color: 'var(--text-dim)', marginTop: 5 }}>Подставляется в форму клиента и счёта</div>
          </div>
          <div style={{ width: 160 }}>
            <label style={{ display: 'block', fontSize: 13, fontWeight: 600, color: 'var(--text-secondary)', marginBottom: 6 }}>Код страны по умолчанию</label>
            <TextField value={country} onChange={setCountry} placeholder="+7" mono />
            <div style={{ fontSize: 11.5, color: 'var(--text-dim)', marginTop: 5 }}>Префикс маски телефона</div>
          </div>
          <div style={{ display: 'flex', alignItems: 'flex-end' }}>
            <Button variant="primary" icon="check" onClick={saveDefaults}>Сохранить</Button>
          </div>
        </div>
      </Card>

      <div ref={catRef}>
        <DictEditor title="Категории расходов" hint="Свои категории для раздела «Счета и Финансы → Расходы». Предприниматель управляет ими сам."
          items={D.EXPENSE_CATEGORIES} onChange={(n) => mutate('EXPENSE_CATEGORIES', n)} color="var(--coral)" />
      </div>
      <DictEditor title="Направления обучения" hint="Список предметов: подставляется в формы клиента/заявки и фильтры."
        items={D.DIRECTIONS} onChange={(n) => mutate('DIRECTIONS', n)} color="var(--brand)" />
      <DictEditor title="Источники заявок" hint="Откуда приходят клиенты — для формы и фильтров."
        items={D.SOURCES} onChange={(n) => mutate('SOURCES', n)} color="var(--green)" />
      <div ref={payRef}>
        <DictEditor title="Способы оплаты" hint="Доступные способы при выставлении счёта и расхода."
        items={D.PAYMENT_METHODS} onChange={(n) => mutate('PAYMENT_METHODS', n)} color="var(--gold)" />
      </div>

      {/* Сотрудники */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginTop: 8 }}>
        <Icon name="briefcase" size={18} style={{ color: 'var(--text-dim)' }} />
        <h2 style={{ fontSize: 16, fontWeight: 700, letterSpacing: '-0.2px', margin: 0, color: 'var(--text)' }}>Сотрудники</h2>
      </div>
      <div ref={rolesRef}>
        <DictEditor title="Роли сотрудников" hint="Роли по умолчанию для формы добавления сотрудника. «Преподаватель» — форма с направлениями, остальные — с логином."
          items={roleLabels} onChange={setRoleLabels} color="var(--brand)" />
      </div>
      <DictEditor title="Должности преподавателей" hint="Подставляются в поле «Должность» при добавлении преподавателя (напр. Стажёр, Старший, Младший)."
        items={D.TEACHER_POSITIONS || []} onChange={(n) => mutate('TEACHER_POSITIONS', n)} color="var(--brand)" />
      <DictEditor title="Должности менеджеров" hint="Подставляются в поле «Позиция» при добавлении менеджера/администратора."
        items={D.MANAGER_POSITIONS || []} onChange={(n) => mutate('MANAGER_POSITIONS', n)} color="var(--gold)" />
      <div ref={dirRef}>
        <DictEditor title="Направления обучения (преподаватели)" hint="Предметы, которые можно назначить преподавателю (тот же список, что и направления обучения)."
          items={D.DIRECTIONS} onChange={(n) => mutate('DIRECTIONS', n)} color="var(--green)" />
      </div>
    </div>
  );
}

Object.assign(window, { Settings });
