/* global React, Icon, Button, Overline, PickerTrigger, SlidePicker, Field, TextField, Avatar */
// Schools.ArtemenkoCRM — Выставить счёт (slide-in panel)

function AddInvoiceModal({ onClose, onCreate }) {
  const { CLIENTS, INVOICE_TYPES, PAYMENT_METHODS } = window.CRM_DATA;
  const [shown, setShown] = React.useState(false);
  const [picker, setPicker] = React.useState(null);
  const [pickerCloseReq, setPickerCloseReq] = React.useState(0);
  const openPicker = (cfg) => setPicker(cfg);

  const [clientId, setClientId] = React.useState(null);     // null = вручную
  const [type, setType] = React.useState('month');
  const [packCount, setPackCount] = React.useState('10');
  const [parent, setParent] = React.useState('');
  const [student, setStudent] = React.useState('');
  const [amount, setAmount] = React.useState('');
  const [method, setMethod] = React.useState(null);
  const [desc, setDesc] = React.useState('');
  const [touchedAmount, setTouchedAmount] = React.useState(false);

  React.useEffect(() => { const t = setTimeout(() => setShown(true), 10); return () => clearTimeout(t); }, []);
  const close = () => { setShown(false); setTimeout(onClose, 200); };

  const activeClients = CLIENTS.filter(c => !c.archived);
  const client = activeClients.find(c => c.id === clientId) || null;
  const typeObj = INVOICE_TYPES.find(t => t.value === type) || INVOICE_TYPES[0];

  // Autofill names + suggested amount when picking client / type
  const pickClient = (id) => {
    setClientId(id);
    const c = activeClients.find(x => x.id === id);
    if (c) {
      setStudent(c.child);
      setParent(c.parents && c.parents[0] ? c.parents[0].name : '');
      if (!touchedAmount && typeObj.mult) setAmount(String(c.lessonPrice * typeObj.mult));
    }
  };
  const pickType = (v) => {
    setType(v);
    const obj = INVOICE_TYPES.find(t => t.value === v);
    const price = client ? client.lessonPrice : 1800;
    if (!touchedAmount && obj && obj.mult) setAmount(String(price * obj.mult));
    if (!touchedAmount && v === 'pack') setAmount(String(price * (parseInt(packCount, 10) || 0)));
  };
  const setPack = (val) => {
    const n = val.replace(/\D/g, '');
    setPackCount(n);
    if (!touchedAmount) { const price = client ? client.lessonPrice : 1800; setAmount(String(price * (parseInt(n, 10) || 0))); }
  };

  const clientLabel = client ? client.child : '— Ввести вручную —';
  const clientOpts = [{ value: null, label: '— Ввести вручную —' }].concat(activeClients.map(c => ({ value: c.id, label: c.child + (c.parents && c.parents[0] ? ' · ' + c.parents[0].name : '') })));

  const submit = () => {
    onCreate({
      clientId, type, parent: parent.trim() || null, student: student.trim() || 'Без имени',
      amount: parseInt((amount || '0').replace(/\D/g, ''), 10) || 0, method, desc: desc.trim(),
      packCount: type === 'pack' ? (parseInt(packCount, 10) || 0) : null,
    });
  };
  const finish = () => { setPicker(null); setShown(false); setTimeout(submit, 200); };
  const canCreate = (amount && parseInt(amount.replace(/\D/g, ''), 10) > 0) && student.trim();

  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)} closeReq={pickerCloseReq} />
        </div>
        <aside style={{
          width: 440, 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)',
        }}>
          {/* Header */}
          <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(--brand-soft)', color: 'var(--brand-ink)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}>
              <Icon name="file-text" 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 }}>Клиенту из CRM или вручную</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>

          {/* Body */}
          <div style={{ flex: 1, overflowY: 'auto', padding: '20px 22px', display: 'flex', flexDirection: 'column', gap: 16 }}>
            <Field label="Клиент из CRM">
              <PickerTrigger label={client ? clientLabel : null} placeholder="— Ввести вручную —" onClick={() => openPicker({
                title: 'Клиент', value: clientId, options: clientOpts, searchable: true, onPick: pickClient,
              })} />
            </Field>

            <Field label="Тип счёта">
              <PickerTrigger label={typeObj.label} onClick={() => openPicker({
                title: 'Тип счёта', value: type, options: INVOICE_TYPES.map(t => ({ value: t.value, label: t.label })), onPick: pickType,
              })} />
            </Field>

            {type === 'pack' && (
              <div className="om-fade-in">
                <Field label="Количество занятий в пакете" required>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <button type="button" onClick={() => setPack(String(Math.max(1, (parseInt(packCount, 10) || 1) - 1)))} style={{ width: 38, height: 38, borderRadius: 'var(--radius-sm)', border: '1px solid var(--border-strong)', background: 'var(--bg-card)', cursor: 'pointer', color: 'var(--text-secondary)', fontSize: 18, fontWeight: 600, flex: 'none' }}>−</button>
                    <div style={{ flex: 1 }}><TextField value={packCount} onChange={setPack} placeholder="10" mono /></div>
                    <button type="button" onClick={() => setPack(String((parseInt(packCount, 10) || 0) + 1))} style={{ width: 38, height: 38, borderRadius: 'var(--radius-sm)', border: '1px solid var(--border-strong)', background: 'var(--bg-card)', cursor: 'pointer', color: 'var(--text-secondary)', fontSize: 18, fontWeight: 600, flex: 'none' }}>+</button>
                  </div>
                </Field>
              </div>
            )}

            <div style={{ display: 'flex', gap: 12 }}>
              <div style={{ flex: 1 }}><Field label="Имя ученика" required><TextField value={student} onChange={setStudent} placeholder="Иванов Артём" /></Field></div>
              <div style={{ flex: 1 }}><Field label="Имя родителя"><TextField value={parent} onChange={setParent} placeholder="Иванова Мария" /></Field></div>
            </div>

            <div style={{ display: 'flex', gap: 12 }}>
              <div style={{ flex: 1 }}>
                <Field label="Сумма (₽)" required><TextField value={amount} onChange={v => { setAmount(v.replace(/\D/g, '')); setTouchedAmount(true); }} placeholder="0" mono /></Field>
                {typeObj.mult > 0 && client && <div style={{ fontSize: 11.5, color: 'var(--text-dim)', marginTop: 5 }}>≈ {client.lessonPrice} ₽ × {typeObj.mult} занятий</div>}
                {type === 'pack' && <div style={{ fontSize: 11.5, color: 'var(--text-dim)', marginTop: 5 }}>≈ {client ? client.lessonPrice : 1800} ₽ × {packCount || 0} занятий</div>}
              </div>
              <div style={{ flex: 1 }}>
                <Field label="Способ оплаты"><PickerTrigger label={method} placeholder="Не указан" onClick={() => openPicker({ title: 'Способ оплаты', value: method, options: PAYMENT_METHODS.map(m => ({ value: m, label: m })), onPick: setMethod })} /></Field>
              </div>
            </div>

            <Field label="Описание"><TextField value={desc} onChange={setDesc} placeholder="Оплата за май, C++ группа" /></Field>

            <div style={{ background: 'var(--bg-soft)', borderRadius: 'var(--radius-md)', padding: 14, display: 'flex', alignItems: 'center', gap: 10 }}>
              <Icon name="info" size={16} style={{ color: 'var(--text-dim)', flex: 'none' }} />
              <span style={{ fontSize: 12.5, color: 'var(--text-secondary)', lineHeight: 1.45 }}>Счёт создаётся со статусом «Ожидает». После оплаты баланс клиента пополнится автоматически.</span>
            </div>
          </div>

          {/* Footer */}
          <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="add-student" onClick={() => canCreate && finish()} style={canCreate ? {} : { opacity: 0.5, cursor: 'not-allowed' }}>Сформировать счёт</Button>
          </div>
        </aside>
      </div>
    </div>
  );
}

Object.assign(window, { AddInvoiceModal });
