// contract-new.jsx — interactive "create contract" modal (quick-action target).
function addMonths(dateStr, n){
  const d = new Date(dateStr || TODAY); d.setMonth(d.getMonth() + n);
  return d.toISOString().slice(0, 10);
}

function NewContractModal({ onClose, editing }){
  const p = usePortal();
  const { t, lang } = useLang();
  const toast = useToast();
  const code = editing ? editing.code : genContractCode(p.contracts);
  const [f, setF] = React.useState(editing ? { category:editing.category, signDate:editing.signDate, customer:editing.customer, rep:editing.rep || '', termType:editing.termType, startDate:editing.startDate || TODAY, endDate:editing.endDate || addMonths(editing.startDate || TODAY, 12), remindBefore:editing.remindBefore || 30 } : { category:'mua-ban', signDate:TODAY, customer:p.customers[0] ? p.customers[0].code : '', rep:'', termType:'once', startDate:TODAY, endDate:addMonths(TODAY, 12), remindBefore:30 });
  const [items, setItems] = React.useState(editing && editing.items && editing.items.length ? editing.items.map(it => ({ name:it.name, unit:it.unit, qty:it.qty, price:it.price, vat:it.vat })) : [{ name:'', unit:'gói', qty:1, price:0, vat:8 }]);
  const [schedule, setSchedule] = React.useState(editing && editing.schedule && editing.schedule.length ? editing.schedule.map(s => ({ no:s.no, amount:s.amount, dueDate:s.dueDate, condition:s.condition, paid:s.paid, paidDate:s.paidDate })) : [{ no:1, amount:0, dueDate:TODAY, condition:lang === 'vi' ? 'Thanh toán khi ký' : 'On signing' }]);
  const [nInst, setNInst] = React.useState(2);
  const set = (k, v) => setF(s => ({ ...s, [k]: v }));

  const cust = p.customers.find(c => c.code === f.customer) || {};
  const reps = p.contacts.filter(c => c.customer === f.customer);

  const tot = items.reduce((acc, it) => { const line = (+it.qty || 0) * (+it.price || 0); acc.sub += line; acc.vat += line * (+it.vat || 0) / 100; return acc; }, { sub:0, vat:0 });
  const total = tot.sub + tot.vat;

  const upItem = (i, k, v) => setItems(s => s.map((it, j) => j === i ? { ...it, [k]:v } : it));
  const addItem = () => setItems(s => [...s, { name:'', unit:'gói', qty:1, price:0, vat:8 }]);
  const rmItem = (i) => setItems(s => s.length > 1 ? s.filter((_, j) => j !== i) : s);

  const genSchedule = () => {
    const n = Math.max(1, Math.min(12, +nInst || 1));
    const base = Math.floor(total / n / 1000) * 1000;
    const rows = [];
    for (let i = 0; i < n; i++){
      rows.push({ no:i + 1, amount:i === n - 1 ? total - base * (n - 1) : base, dueDate:addMonths(f.signDate, i), condition:i === 0 ? (lang === 'vi' ? 'Tạm ứng khi ký' : 'On signing') : (lang === 'vi' ? 'Đợt ' + (i + 1) : 'Installment ' + (i + 1)) });
    }
    setSchedule(rows);
  };
  const upSch = (i, k, v) => setSchedule(s => s.map((r, j) => j === i ? { ...r, [k]:v } : r));
  const rmSch = (i) => setSchedule(s => s.filter((_, j) => j !== i).map((r, j) => ({ ...r, no:j + 1 })));

  const create = () => {
    if (!f.customer) { toast(lang === 'vi' ? 'Chọn khách hàng' : 'Select a customer', 'error'); return; }
    if (!items.some(it => it.name.trim())) { toast(lang === 'vi' ? 'Thêm ít nhất 1 sản phẩm/dịch vụ' : 'Add at least one item', 'error'); return; }
    const rec = {
      code, category:f.category, signDate:f.signDate, customer:f.customer, rep:f.rep || null,
      termType:f.termType, startDate:f.termType === 'term' ? f.startDate : f.signDate,
      endDate:f.termType === 'term' ? f.endDate : null, remindBefore:+f.remindBefore || 30, status:editing ? editing.status : 'active',
      items:items.filter(it => it.name.trim()).map(it => ({ name:it.name, unit:it.unit, qty:+it.qty || 0, price:+it.price || 0, vat:+it.vat || 0 })),
      schedule:schedule.map(s => ({ no:s.no, amount:+s.amount || 0, dueDate:s.dueDate, condition:s.condition, paid:!!s.paid, paidDate:s.paidDate || null })),
    };
    if (editing) { p.patchContract(editing.code, rec); toast(lang === 'vi' ? 'Đã lưu hợp đồng' : 'Saved', 'success'); onClose(); return; }
    p.saveContract(rec);
    toast((lang === 'vi' ? 'Đã tạo hợp đồng ' : 'Created ') + code, 'success');
    onClose();
    p.navigate({ name:'module', module:'contracts', sub:'detail', id:code });
  };

  const cellInput = { height:26, padding:'0 6px', border:'1px solid var(--border-strong)', borderRadius:'var(--r-sm)', width:'100%', fontSize:'var(--fs-base)', background:'var(--bg)' };

  return (
    <Modal title={editing ? (lang === 'vi' ? 'Sửa hợp đồng' : 'Edit contract') : t('hd.new')} width={860} onClose={onClose}
      footer={<><div className="grow flex g8 items-center"><span className="subtle">{t('hd.total')}:</span><span className="mono" style={{ fontWeight:700, color:'var(--primary)', fontSize:'var(--fs-lg)' }}>{vnd(total)}</span></div>
        <button className="btn" onClick={onClose}>{t('c.cancel')}</button><button className="btn btn-primary" onClick={create}>{editing ? t('c.save') : t('c.create')}</button></>}>
      <div className="col g16">
        {/* section 1: contract info */}
        <div className="flex g12 items-center" style={{ padding:'2px 0' }}><span className="subtle">{t('hd.code')}:</span><span className="mono" style={{ fontWeight:600, color:'var(--primary)' }}>{code}</span>{!editing && <span className="badge badge-neutral">{lang === 'vi' ? 'tự sinh' : 'auto'}</span>}</div>
        <div className="flex g12 wrap">
          <div style={{ flex:'1 1 200px' }}><Field label={t('hd.category')}><select className="select" value={f.category} onChange={e => set('category', e.target.value)}>{CONTRACT_CATEGORIES.map(c => <option key={c.id} value={c.id}>{c[lang]}</option>)}</select></Field></div>
          <div style={{ flex:'1 1 140px' }}><Field label={t('hd.signDate')}><input type="date" className="input" value={f.signDate} onChange={e => set('signDate', e.target.value)} /></Field></div>
        </div>

        {/* section 2: parties */}
        <div className="hr"></div>
        <div style={{ fontWeight:600, fontSize:'var(--fs-md)' }}>{t('hd.parties')}</div>
        <div className="flex g12 wrap">
          <div style={{ flex:'1 1 240px' }}><Field label={t('ct.customer')}><select className="select" value={f.customer} onChange={e => { set('customer', e.target.value); set('rep', ''); }}>{p.customers.map(c => <option key={c.code} value={c.code}>{c.code} · {c.name}</option>)}</select></Field></div>
          <div style={{ flex:'1 1 240px' }}><Field label={t('hd.rep') + ' (' + (lang === 'vi' ? 'từ Liên hệ' : 'from Contacts') + ')'}><select className="select" value={f.rep} onChange={e => set('rep', e.target.value)}><option value="">— {reps.length ? (lang === 'vi' ? 'chọn' : 'select') : (lang === 'vi' ? 'không có liên hệ' : 'no contacts')} —</option>{reps.map(r => <option key={r.code} value={r.code}>{r.name} · {r.title}</option>)}</select></Field></div>
        </div>
        <div className="flex g16 wrap" style={{ fontSize:'var(--fs-base)', color:'var(--text-muted)', background:'var(--bg-subtle)', padding:'8px 10px', borderRadius:'var(--r-md)' }}>
          <span><b className="muted">{t('cust.mst')}:</b> <span className="mono">{cust.mst || '—'}</span></span>
          <span><b className="muted">{t('hd.address')}:</b> {CUSTOMER_ADDR[f.customer] || '—'}</span>
        </div>

        {/* section 3: term */}
        <div className="hr"></div>
        <div className="col g12">
          <div className="flex g12 items-center">
            <div style={{ fontWeight:600, fontSize:'var(--fs-md)' }}>{t('hd.term')}</div>
            <Segmented value={f.termType} onChange={v => set('termType', v)} options={[{ value:'once', label:TERM_TYPES.once[lang] }, { value:'term', label:TERM_TYPES.term[lang] }]} />
          </div>
          {f.termType === 'term' && (
            <div className="flex g12 wrap">
              <div style={{ flex:'1 1 150px' }}><Field label={t('hd.start')}><input type="date" className="input" value={f.startDate} onChange={e => set('startDate', e.target.value)} /></Field></div>
              <div style={{ flex:'1 1 150px' }}><Field label={t('hd.end')}><input type="date" className="input" value={f.endDate} onChange={e => set('endDate', e.target.value)} /></Field></div>
              <div style={{ flex:'1 1 150px' }}><Field label={lang === 'vi' ? 'Nhắc trước (ngày)' : 'Remind (days)'}><input type="number" className="input" value={f.remindBefore} onChange={e => set('remindBefore', e.target.value)} /></Field></div>
            </div>
          )}
        </div>

        {/* section 4: items */}
        <div className="hr"></div>
        <div className="flex justify-between items-center"><div style={{ fontWeight:600, fontSize:'var(--fs-md)' }}>{t('hd.items')}</div><button className="btn btn-sm btn-subtle" onClick={addItem}><i className="bi bi-plus-lg"></i>{t('hd.addItem')}</button></div>
        <div style={{ overflow:'auto' }}>
          <table className="tbl" style={{ minWidth:640 }}>
            <thead><tr><th>{t('hd.items')}</th><th style={{ width:64 }}>{t('hd.unit')}</th><th style={{ width:56 }} className="num">{t('hd.qty')}</th><th style={{ width:120 }} className="num">{t('hd.price')}</th><th style={{ width:64 }} className="num">{t('hd.vat')}%</th><th style={{ width:110 }} className="num">{t('hd.total')}</th><th style={{ width:30 }}></th></tr></thead>
            <tbody>
              {items.map((it, i) => { const line = (+it.qty || 0) * (+it.price || 0); const tt = line * (1 + (+it.vat || 0) / 100); return (
                <tr key={i} style={{ cursor:'default' }}>
                  <td><input style={cellInput} value={it.name} placeholder={lang === 'vi' ? 'Tên sản phẩm / dịch vụ' : 'Item name'} onChange={e => upItem(i, 'name', e.target.value)} /></td>
                  <td><input style={cellInput} value={it.unit} onChange={e => upItem(i, 'unit', e.target.value)} /></td>
                  <td><input style={{ ...cellInput, textAlign:'right' }} type="number" value={it.qty} onChange={e => upItem(i, 'qty', e.target.value)} /></td>
                  <td><input style={{ ...cellInput, textAlign:'right' }} type="number" value={it.price} onChange={e => upItem(i, 'price', e.target.value)} /></td>
                  <td><input style={{ ...cellInput, textAlign:'right' }} type="number" value={it.vat} onChange={e => upItem(i, 'vat', e.target.value)} /></td>
                  <td className="num mono" style={{ fontWeight:600 }}>{vnd(tt)}</td>
                  <td style={{ textAlign:'center' }}><button className="iconbtn" style={{ width:22, height:22 }} onClick={() => rmItem(i)}><i className="bi bi-trash" style={{ fontSize:12 }}></i></button></td>
                </tr>
              ); })}
            </tbody>
            <tfoot>
              <tr style={{ cursor:'default' }}><td colSpan="4"></td><td className="num muted">{t('hd.subtotal')}</td><td className="num mono">{vnd(tot.sub)}</td><td></td></tr>
              <tr style={{ cursor:'default' }}><td colSpan="4"></td><td className="num muted">{t('hd.vatTotal')}</td><td className="num mono">{vnd(tot.vat)}</td><td></td></tr>
              <tr style={{ cursor:'default', background:'var(--bg-subtle)' }}><td colSpan="4"></td><td className="num" style={{ fontWeight:700 }}>{t('hd.total')}</td><td className="num mono" style={{ fontWeight:700, color:'var(--primary)' }}>{vnd(total)}</td><td></td></tr>
            </tfoot>
          </table>
        </div>

        {/* section 5: schedule */}
        <div className="hr"></div>
        <div className="flex justify-between items-center wrap g8"><div style={{ fontWeight:600, fontSize:'var(--fs-md)' }}>{t('hd.schedule')}</div>
          <div className="flex g8 items-center"><span className="subtle" style={{ fontSize:'var(--fs-base)' }}>{lang === 'vi' ? 'Số lần' : 'Installments'}</span>
            <input type="number" className="input" style={{ width:64 }} value={nInst} onChange={e => setNInst(e.target.value)} min="1" max="12" />
            <button className="btn btn-sm" onClick={genSchedule}><i className="bi bi-magic"></i>{t('hd.genSchedule')}</button></div>
        </div>
        <div style={{ overflow:'auto' }}>
          <table className="tbl" style={{ minWidth:580 }}>
            <thead><tr><th style={{ width:44 }}>{t('hd.installment')}</th><th style={{ width:140 }} className="num">{lang === 'vi' ? 'Số tiền' : 'Amount'}</th><th style={{ width:150 }}>{t('hd.dueDate')}</th><th>{t('hd.condition')}</th><th style={{ width:30 }}></th></tr></thead>
            <tbody>
              {schedule.map((s, i) => (
                <tr key={i} style={{ cursor:'default' }}>
                  <td style={{ fontWeight:600 }}>{s.no}</td>
                  <td><input style={{ ...cellInput, textAlign:'right' }} type="number" value={s.amount} onChange={e => upSch(i, 'amount', e.target.value)} /></td>
                  <td><input style={cellInput} type="date" value={s.dueDate} onChange={e => upSch(i, 'dueDate', e.target.value)} /></td>
                  <td><input style={cellInput} value={s.condition} onChange={e => upSch(i, 'condition', e.target.value)} /></td>
                  <td style={{ textAlign:'center' }}><button className="iconbtn" style={{ width:22, height:22 }} onClick={() => rmSch(i)}><i className="bi bi-trash" style={{ fontSize:12 }}></i></button></td>
                </tr>
              ))}
            </tbody>
            <tfoot><tr style={{ cursor:'default', background:'var(--bg-subtle)' }}><td>Σ</td><td className="num mono" style={{ fontWeight:700, color:schedule.reduce((a, s) => a + (+s.amount || 0), 0) === Math.round(total) ? 'var(--success)' : 'var(--warning)' }}>{vnd(schedule.reduce((a, s) => a + (+s.amount || 0), 0))}</td><td colSpan="3" className="muted">{schedule.reduce((a, s) => a + (+s.amount || 0), 0) === Math.round(total) ? (lang === 'vi' ? 'Khớp tổng giá trị' : 'Matches total') : (lang === 'vi' ? 'Chưa khớp tổng' : 'Does not match total')}</td></tr></tfoot>
          </table>
        </div>
      </div>
    </Modal>
  );
}

Object.assign(window, { NewContractModal });
