/* global React, Icon, Pill, DirChip, Avatar, Balance, Dropdown */
// Schools.ArtemenkoCRM — Clients table (раздел «Клиенты»), redesigned from the real product

const CL_MON = ['янв', 'фев', 'мар', 'апр', 'мая', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек'];
// Parse a client's arrival label («сегодня» / «вчера» / «5 апр, 23:02») into a sortable timestamp.
function clientArrivalTs(c) {
  const d = String(c.date || '').toLowerCase().trim();
  const now = Date.now();
  if (d.startsWith('сегодня')) return now;
  if (d.startsWith('вчера')) return now - 86400000;
  const m = d.match(/(\d{1,2})\s+([а-я]+)(?:,\s*(\d{1,2}):(\d{2}))?/);
  if (m) {
    const mon = CL_MON.findIndex(x => m[2].startsWith(x));
    if (mon >= 0) return new Date(2026, mon, +m[1], m[3] ? +m[3] : 0, m[4] ? +m[4] : 0).getTime();
  }
  return typeof c.id === 'number' ? c.id : 0;
}

function Clients({ onOpenClient, onAddClient, removingId }) {
  const { CLIENTS, TEACHERS, DIRECTIONS, SOURCES } = window.CRM_DATA;
  const [tab, setTab] = React.useState('active');        // active | archive
  const [q, setQ] = React.useState('');
  const [status, setStatus] = React.useState(null);
  const [teacher, setTeacher] = React.useState(null);
  const [source, setSource] = React.useState(null);
  const [balance, setBalance] = React.useState(null);
  const [direction, setDirection] = React.useState(null);
  const [sort, setSort] = React.useState(null);          // null | recent | old

  const opt = (arr) => [{ value: null, label: arr.allLabel }].concat(arr.items.map(v => ({ value: v, label: v })));
  const statusOpts = [{ value: null, label: 'Все статусы' },
    { value: 'new', label: 'Новая' }, { value: 'call', label: 'Созвон' }, { value: 'trial', label: 'Пробное' },
    { value: 'payment', label: 'Оплата' }, { value: 'active', label: 'Активный' }, { value: 'refusal', label: 'Отказ' }];
  const balanceOpts = [{ value: null, label: 'Все балансы' },
    { value: 'pos', label: 'С балансом' }, { value: 'zero', label: 'Нулевой' }, { value: 'neg', label: 'Долг' }];
  const sortOpts = [{ value: null, label: 'Без сортировки' },
    { value: 'recent', label: 'Сначала недавние' }, { value: 'old', label: 'Сначала давние' }];

  const rows = CLIENTS.filter(c => {
    if (tab === 'active' ? c.archived : !c.archived) return false;
    if (q && !(`${c.child} ${(c.parents||[]).map(p=>p.name).join(' ')} ${(c.contacts||[]).map(x=>x.value).join(' ')} ${(c.parents||[]).flatMap(p=>(p.contacts||[]).map(x=>x.value)).join(' ')}`.toLowerCase().includes(q.toLowerCase()))) return false;
    if (status && c.status !== status) return false;
    if (teacher && c.teacher !== teacher) return false;
    if (source && c.source !== source) return false;
    if (direction && !((c.directions && c.directions.length ? c.directions : (c.direction ? [c.direction] : [])).includes(direction))) return false;
    if (balance === 'pos' && !(c.balance > 0)) return false;
    if (balance === 'zero' && c.balance !== 0) return false;
    if (balance === 'neg' && !(c.balance < 0)) return false;
    return true;
  });
  const sortedRows = sort === 'recent' ? rows.slice().sort((a, b) => clientArrivalTs(b) - clientArrivalTs(a))
    : sort === 'old' ? rows.slice().sort((a, b) => clientArrivalTs(a) - clientArrivalTs(b)) : rows;

  const th = { textAlign: 'left', fontSize: 11.5, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--text-dim)', padding: '0 18px 13px', whiteSpace: 'nowrap' };
  const td = { padding: '13px 18px', borderTop: '1px solid var(--border)', fontSize: 14, color: 'var(--text)', verticalAlign: 'middle' };
  const dim = { color: 'var(--text-dim)' };

  return (
    <div style={{ padding: '24px 32px 40px' }}>
      {/* Tabs + add */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 18 }}>
        <div style={{ display: 'inline-flex', background: 'var(--bg-soft)', borderRadius: 'var(--radius-sm)', padding: 3, gap: 2 }}>
          {[{ id: 'active', label: 'Активные' }, { id: 'archive', label: 'Архив' }].map(t => (
            <button key={t.id} onClick={() => setTab(t.id)}
              onMouseEnter={e => { if (tab !== t.id) { e.currentTarget.style.background = 'var(--bg-card)'; e.currentTarget.style.color = 'var(--text-secondary)'; } }}
              onMouseLeave={e => { if (tab !== t.id) { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--text-dim)'; } }}
              style={{
              padding: '6px 16px', border: 'none', borderRadius: 5, cursor: 'pointer',
              fontFamily: 'var(--font-sans)', fontSize: 13.5, fontWeight: 600,
              background: tab === t.id ? 'var(--bg-card)' : 'transparent',
              color: tab === t.id ? 'var(--brand-ink)' : 'var(--text-dim)',
              boxShadow: tab === t.id ? 'var(--shadow-xs)' : 'none',
              transition: 'background var(--dur-fast) var(--ease), color var(--dur-fast) var(--ease)',
            }}>{t.label}</button>
          ))}
        </div>
        <span style={{ fontSize: 13, color: 'var(--text-dim)' }}>{rows.length} клиентов</span>
        <div style={{ flex: 1 }} />
        <Button icon="add-student" onClick={onAddClient}>Добавить</Button>
      </div>

      {/* Filters */}
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, marginBottom: 18, alignItems: 'center' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, background: 'var(--bg-card)', border: '1px solid var(--border)', borderRadius: 'var(--radius-sm)', padding: '8px 12px', width: 220 }}>
          <Icon name="search" size={16} style={{ color: 'var(--text-dim)' }} />
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Поиск…" style={{ border: 'none', outline: 'none', background: 'transparent', flex: 1, fontFamily: 'var(--font-sans)', fontSize: 13.5, color: 'var(--text)' }} />
        </div>
        <Dropdown value={status} onChange={setStatus} options={statusOpts} placeholder="Все статусы" width={150} />
        <Dropdown value={teacher} onChange={setTeacher} options={opt({ allLabel: 'Все преподаватели', items: TEACHERS })} placeholder="Все преподаватели" width={232} />
        <Dropdown value={source} onChange={setSource} options={opt({ allLabel: 'Все источники', items: SOURCES })} placeholder="Все источники" width={168} />
        <Dropdown value={balance} onChange={setBalance} options={balanceOpts} placeholder="Все балансы" width={150} />
        <Dropdown value={direction} onChange={setDirection} options={opt({ allLabel: 'Все направления', items: DIRECTIONS })} placeholder="Все направления" width={180} />
        <div style={{ flex: 1 }} />
        <Dropdown value={sort} onChange={setSort} options={sortOpts} placeholder="Сортировка" width={188} />
      </div>

      {/* Table */}
      <Card pad={0} style={{ overflow: 'hidden' }}>
        {rows.length > 0 ? (
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 1040 }}>
            <thead><tr>
              <th style={{ ...th, paddingTop: 16 }}>Ученик</th>
              <th style={{ ...th, paddingTop: 16 }}>Родитель</th>
              <th style={{ ...th, paddingTop: 16 }}>Статус</th>
              <th style={{ ...th, paddingTop: 16 }}>Преподаватель</th>
              <th style={{ ...th, paddingTop: 16, textAlign: 'right' }}>Баланс</th>
              <th style={{ ...th, paddingTop: 16 }}>Направление</th>
              <th style={{ ...th, paddingTop: 16 }}>Источник</th>
              <th style={{ ...th, paddingTop: 16 }}>Менеджер</th>
              <th style={{ ...th, paddingTop: 16 }}>Дата</th>
            </tr></thead>
            <tbody key={`${tab}|${q}|${status}|${teacher}|${source}|${balance}|${direction}|${sort}`}>
              {sortedRows.map((c, ri) => (
                <tr key={c.id} className={'row-hover ' + (c.id === removingId ? 'om-fly-right' : 'om-row-in')} style={{ cursor: 'pointer', animationDelay: c.id === removingId ? '0ms' : Math.min(ri * 25, 300) + 'ms' }} onClick={() => onOpenClient(c)}>
                  <td style={td}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
                      <Avatar animal={c.animal} tone={c.tone} size={32} />
                      <span style={{ fontWeight: 600, maxWidth: 320, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={c.child}>{c.child.length > 36 ? c.child.slice(0, 36) + '…' : c.child}</span>
                      {c.self && <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--gold-ink)', background: 'var(--gold-soft)', border: '1px solid #D8C291', borderRadius: 3, padding: '1px 5px' }}>сам.</span>}
                    </div>
                  </td>
                  <td style={{ ...td, ...((c.parents && c.parents.length) ? {} : dim) }}>
                    {c.parents && c.parents.length
                      ? <span>{c.parents[0].name}{c.parents.length > 1 && <span style={{ color: 'var(--text-dim)', fontWeight: 600 }}> +{c.parents.length - 1}</span>}</span>
                      : '—'}
                  </td>
                  <td style={td}><Pill kind={c.status} /></td>
                  <td style={{ ...td, ...(c.teacher ? { color: 'var(--text-secondary)' } : dim), fontSize: 13.5 }}>{(() => {
                    const ts = (c.teachers && c.teachers.length) ? c.teachers : (c.teacher ? [c.teacher] : []);
                    if (!ts.length) return '—';
                    return <span>{ts[0]}{ts.length > 1 && <span style={{ color: 'var(--brand-ink)', fontWeight: 700 }}> +{ts.length - 1}</span>}</span>;
                  })()}</td>
                  <td style={{ ...td, textAlign: 'right' }}><Balance value={c.balance} /></td>
                  <td style={td}>{(() => { const dirs = (c.directions && c.directions.length) ? c.directions : (c.direction ? [c.direction] : []); return dirs.length ? <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>{dirs.map(d => <DirChip key={d}>{d}</DirChip>)}</div> : <DirChip>{null}</DirChip>; })()}</td>
                  <td style={{ ...td, color: 'var(--text-secondary)', fontSize: 13.5 }}>{c.source}</td>
                  <td style={{ ...td, ...dim, fontFamily: 'var(--font-mono)', fontSize: 12.5 }}>{c.manager || '—'}</td>
                  <td style={{ ...td, ...dim, fontSize: 13, whiteSpace: 'nowrap' }}>{c.date}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        ) : (
          <div style={{ padding: '48px 24px', textAlign: 'center', color: 'var(--text-dim)', fontSize: 14 }}>
            {tab === 'archive' ? 'В архиве пока нет клиентов' : 'По заданным фильтрам клиентов нет'}
          </div>
        )}
      </Card>
    </div>
  );
}

Object.assign(window, { Clients });
