/* global React, Icon, Button, PickerTrigger, SlidePicker, Field, TextField, RangeCalendar */
// Schools.ArtemenkoCRM — Добавить расход (slide-in)

const RECUR_PERIODS = [
  { value: 'day', label: 'Каждый день' },
  { value: 'week', label: 'Каждую неделю' },
  { value: 'month', label: 'Каждый месяц' },
  { value: 'year', label: 'Каждый год' },
];
const MON_SHORT = ['янв', 'фев', 'мар', 'апр', 'мая', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек'];
const isoToday = () => { const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; };
const fmtDate = (s) => { if (!s) return '—'; const [y, m, d] = s.split('-'); return `${+d} ${MON_SHORT[+m - 1]} ${y}`; };

function AddExpenseModal({ onClose, onCreate, onNavSettings }) {
  const { EXPENSE_CATEGORIES, PAYMENT_METHODS } = window.CRM_DATA;
  const [shown, setShown] = React.useState(false);
  const [picker, setPicker] = React.useState(null);
  const [category, setCategory] = React.useState(EXPENSE_CATEGORIES[0] || null);
  const [title, setTitle] = React.useState('');
  const [description, setDescription] = React.useState('');
  const [amount, setAmount] = React.useState('');
  const [method, setMethod] = React.useState(PAYMENT_METHODS[0] || null);
  const [date, setDate] = React.useState(isoToday());
  const [dateCal, setDateCal] = React.useState(false);
  const [recurring, setRecurring] = React.useState(false);
  const [recurPeriod, setRecurPeriod] = React.useState('month');
  const [recurEnd, setRecurEnd] = React.useState(null);
  const [recurEndCal, setRecurEndCal] = React.useState(false);
  const dateRef = React.useRef(null);
  const endRef = React.useRef(null);

  React.useEffect(() => { const t = setTimeout(() => setShown(true), 10); return () => clearTimeout(t); }, []);
  React.useEffect(() => {
    const h = (e) => {
      if (dateRef.current && !dateRef.current.contains(e.target)) setDateCal(false);
      if (endRef.current && !endRef.current.contains(e.target)) setRecurEndCal(false);
    };
    document.addEventListener('mousedown', h); return () => document.removeEventListener('mousedown', h);
  }, []);
  const close = () => { setShown(false); setTimeout(onClose, 200); };
  const canSave = title.trim() && amount && parseInt(amount.replace(/\D/g, ''), 10) > 0;
  const recurLabel = (RECUR_PERIODS.find(p => p.value === recurPeriod) || {}).label;
  const submit = () => onCreate({
    category, title: title.trim(), description: description.trim(), amount: parseInt(amount.replace(/\D/g, ''), 10) || 0, method, date,
    recurring, recurPeriod: recurring ? recurPeriod : null, recurEnd: recurring ? recurEnd : null,
  });
  const finish = () => { setPicker(null); setShown(false); setTimeout(submit, 200); };

  const dateBtn = (label, onClick, active) => (
    <button onClick={onClick}
      onMouseEnter={e => { if (!active) e.currentTarget.style.borderColor = 'var(--border-strong)'; }}
      onMouseLeave={e => { if (!active) e.currentTarget.style.borderColor = 'var(--border)'; }}
      style={{ display: 'inline-flex', alignItems: 'center', gap: 8, width: '100%', justifyContent: 'flex-start', padding: '10px 13px', cursor: 'pointer', background: 'var(--bg-card)', border: '1px solid ' + (active ? 'var(--brand)' : 'var(--border)'), borderRadius: 'var(--radius-sm)', boxShadow: active ? 'var(--shadow-focus)' : 'none', fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 500, color: 'var(--text)', transition: 'border-color var(--dur-fast) var(--ease)' }}>
      <Icon name="calendar" size={15} style={{ color: 'var(--text-dim)' }} />{label}
    </button>
  );

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 50 }}>
      <div onClick={close} style={{ position: 'absolute', inset: 0, background: 'rgba(21,28,46,0.45)', backdropFilter: 'blur(2px)', opacity: shown ? 1 : 0, transition: 'opacity var(--dur) var(--ease)' }} />
      <div style={{ position: 'absolute', top: 0, right: 0, bottom: 0, display: 'flex' }}>
        <div style={{ position: 'relative', width: 0, zIndex: 0 }}>
          <SlidePicker cfg={picker} onClose={() => setPicker(null)} />
        </div>
        <aside style={{
          width: 400, maxWidth: '100vw', background: 'var(--bg-card)', boxShadow: 'var(--shadow-lg)', position: 'relative', zIndex: 2,
          display: 'flex', flexDirection: 'column', height: '100%',
          transform: shown ? 'translateX(0)' : 'translateX(100%)', transition: 'transform 280ms cubic-bezier(0.22, 1, 0.36, 1)',
        }}>
          <div style={{ padding: '18px 22px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 12 }}>
            <span style={{ width: 40, height: 40, borderRadius: 'var(--radius-md)', background: 'var(--coral-bg)', color: 'var(--coral)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}>
              <Icon name="receipt" size={20} />
            </span>
            <div style={{ flex: 1 }}>
              <h2 style={{ fontSize: 18, fontWeight: 700, letterSpacing: '-0.3px', margin: 0, color: 'var(--text)' }}>Добавить расход</h2>
              <div style={{ fontSize: 13, color: 'var(--text-dim)', marginTop: 1 }}>Расход школы</div>
            </div>
            <button onClick={close} title="Закрыть" style={{ width: 34, height: 34, borderRadius: 6, border: '1px solid var(--border)', background: 'var(--bg-card)', cursor: 'pointer', color: 'var(--text-secondary)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round"><path d="M9.2 9.2l5.6 5.6M14.8 9.2l-5.6 5.6"/></svg>
            </button>
          </div>

          <div style={{ flex: 1, overflowY: 'auto', padding: '20px 22px', display: 'flex', flexDirection: 'column', gap: 16 }}>
            <Field label="Категория">
              <PickerTrigger label={category} placeholder="Выберите" onClick={() => setPicker({
                title: 'Категория расхода', value: category,
                options: EXPENSE_CATEGORIES.map(c => ({ value: c, label: c })).concat([{ value: '__add', label: '+ Добавить новую категорию…' }]),
                allowCustom: true, customPlaceholder: 'Разовое название (не сохранится)',
                onPick: (v) => { if (v === '__add') { close(); if (onNavSettings) onNavSettings('expense-categories'); } else setCategory(v); },
              })} />
              <div style={{ fontSize: 11.5, color: 'var(--text-dim)', marginTop: 5 }}>Можно вписать <b style={{ color: 'var(--text-secondary)', fontWeight: 600 }}>разовое название</b> (для одноразового расхода — не сохранится). Для постоянных категорий — «Добавить новую категорию» (сохранится в Настройках).</div>
            </Field>
            <Field label="Назначение" required><TextField value={title} onChange={setTitle} placeholder="Например, Офис, аренда за май" autoFocus /></Field>
            <Field label="Описание">
              <textarea value={description} onChange={e => setDescription(e.target.value)} placeholder="Подробности расхода — раскрываются по кнопке «Подробнее»" rows={2} style={{ width: '100%', boxSizing: 'border-box', resize: 'vertical', border: '1px solid var(--border)', borderRadius: 'var(--radius-sm)', padding: '10px 12px', fontFamily: 'var(--font-sans)', fontSize: 14, color: 'var(--text)', outline: 'none', background: 'var(--bg-card)' }} />
              <div style={{ fontSize: 11.5, color: 'var(--text-dim)', marginTop: 5 }}>Под назначением покажется кратко; полностью — при раскрытии расхода.</div>
            </Field>
            <Field label="Сумма (₽)" required><TextField value={amount} onChange={v => setAmount(v.replace(/\D/g, ''))} placeholder="0" mono /></Field>

            <Field label="Дата расхода">
              <div ref={dateRef} style={{ position: 'relative' }}>
                {dateBtn(fmtDate(date), () => setDateCal(o => !o), dateCal)}
                {dateCal && <RangeCalendar single value={{ start: date, end: date }} onApply={(r) => setDate(r.start)} onClose={() => setDateCal(false)} />}
              </div>
            </Field>

            <Field label="Способ оплаты">
              <PickerTrigger label={method} placeholder="Не указан" onClick={() => setPicker({
                title: 'Способ оплаты', value: method,
                options: PAYMENT_METHODS.map(m => ({ value: m, label: m })).concat([{ value: '__settings', label: '+ Настроить способы оплаты…' }]),
                onPick: (v) => { if (v === '__settings') { close(); if (onNavSettings) onNavSettings('payment-methods'); } else setMethod(v); },
              })} />
            </Field>

            {/* Recurring */}
            <div style={{ borderTop: '1px solid var(--border)', paddingTop: 16 }}>
              <label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}>
                <span onClick={() => setRecurring(r => !r)} style={{ position: 'relative', width: 38, height: 22, borderRadius: 999, background: recurring ? 'var(--brand)' : 'var(--border-strong)', transition: 'background var(--dur) var(--ease)', flex: 'none' }}>
                  <span style={{ position: 'absolute', top: 2, left: recurring ? 18 : 2, width: 18, height: 18, borderRadius: '50%', background: '#fff', transition: 'left var(--dur) var(--ease)', boxShadow: 'var(--shadow-xs)' }} />
                </span>
                <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)' }}>Повторяющийся расход</span>
              </label>
              {recurring && (
                <div className="om-fade-in" style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 14 }}>
                  <Field label="Периодичность">
                    <PickerTrigger label={recurLabel} onClick={() => setPicker({ title: 'Периодичность', value: recurPeriod, options: RECUR_PERIODS, onPick: setRecurPeriod })} />
                  </Field>
                  <Field label="Дата окончания (необязательно)">
                    <div ref={endRef} style={{ position: 'relative' }}>
                      {dateBtn(recurEnd ? fmtDate(recurEnd) : 'Бессрочно', () => setRecurEndCal(o => !o), recurEndCal)}
                      {recurEndCal && <RangeCalendar single value={recurEnd ? { start: recurEnd, end: recurEnd } : null} onApply={(r) => setRecurEnd(r.start)} onClose={() => setRecurEndCal(false)} />}
                    </div>
                    {recurEnd && <button onClick={() => setRecurEnd(null)} style={{ marginTop: 6, border: 'none', background: 'none', cursor: 'pointer', color: 'var(--brand-ink)', fontSize: 12, fontWeight: 600 }}>Сделать бессрочным</button>}
                  </Field>
                  <div style={{ background: 'var(--bg-soft)', borderRadius: 'var(--radius-sm)', padding: '10px 12px', fontSize: 12.5, color: 'var(--text-secondary)', display: 'flex', alignItems: 'center', gap: 8 }}>
                    <Icon name="repeat" size={15} style={{ color: 'var(--text-dim)', flex: 'none' }} />
                    {recurLabel.toLowerCase()}, с {fmtDate(date)}{recurEnd ? ` до ${fmtDate(recurEnd)}` : ', бессрочно'}
                  </div>
                </div>
              )}
            </div>
          </div>

          <div style={{ padding: '14px 22px', borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
            <Button variant="ghost" onClick={close}>Отмена</Button>
            <Button variant="primary" icon="plus" onClick={() => canSave && finish()} style={canSave ? {} : { opacity: 0.5, cursor: 'not-allowed' }}>Добавить расход</Button>
          </div>
        </aside>
      </div>
    </div>
  );
}

Object.assign(window, { AddExpenseModal });
