/* screens-history-import-manual.jsx — manual entry matrix for history data */

function HiManualEntry({ warehouseId, addToast, navigate }) {
  const { vw, isMobile } = useViewport();
  const [whId, setWhId] = React.useState(warehouseId);
  const [note, setNote] = React.useState('Nhập tay · đối soát thiếu vài ngày');
  const [dates, setDates] = React.useState(['2026-04-12', '2026-04-13', '2026-04-14']);
  const [rows, setRows] = React.useState([
    { customerId: 'cus-001', qty: { '2026-04-12': 1180, '2026-04-13': 1240, '2026-04-14': 1100 } },
    { customerId: 'cus-002', qty: { '2026-04-12': 940,  '2026-04-13': 0,    '2026-04-14': 980 } },
  ]);
  const [submitted, setSubmitted] = React.useState(false);

  function addCustomer(id) {
    if (rows.find(r => r.customerId === id)) return;
    setRows(prev => [...prev, { customerId: id, qty: {} }]);
  }
  function removeCustomer(id) { setRows(prev => prev.filter(r => r.customerId !== id)); }
  function setQty(id, date, value) {
    setRows(prev => prev.map(r => r.customerId === id ? { ...r, qty: { ...r.qty, [date]: value } } : r));
  }
  function addDate(d) {
    if (dates.includes(d)) return;
    setDates([...dates, d].sort());
  }
  function removeDate(d) {
    if (dates.length <= 1) return;
    setDates(dates.filter(x => x !== d));
    setRows(prev => prev.map(r => { const q = { ...r.qty }; delete q[d]; return { ...r, qty: q }; }));
  }

  let totalRows = 0, totalOrders = 0;
  rows.forEach(r => {
    dates.forEach(d => {
      const v = parseInt(r.qty[d], 10);
      if (!isNaN(v)) { totalRows++; totalOrders += v; }
    });
  });

  function submit() {
    setSubmitted(true);
    addToast({ kind: 'FULFILLED', title: 'Đã nhập dữ liệu lịch sử', body: totalRows + ' dòng đã ghi vào kho dữ liệu lịch sử.' });
    setTimeout(() => { setSubmitted(false); }, 1200);
  }

  const valid = totalRows > 0 && note.length >= 4 && !submitted;
  const availableCustomers = WFP.CUSTOMERS.filter(c => !rows.find(r => r.customerId === c.id));

  return (
    <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 14 }}>
      <Card title="Nhập tay · bảng khách hàng × ngày"
        subtitle="Chọn kho, thêm ngày, thêm khách hàng và điền số đơn đã giao. Tab sang phải →, Enter xuống dưới ↓.">
        <div style={{ display: 'grid', gridTemplateColumns: vw < 900 ? '1fr' : '1fr 2fr', gap: 14 }}>
          <Field label="Kho" required>
            <Select value={whId} onChange={e => setWhId(e.target.value)}
              options={WFP.WAREHOUSES.map(w => ({ value: w.id, label: w.code + ' · ' + w.name }))}/>
          </Field>
          <Field label="Ghi chú · áp dụng cho mọi dòng" required hint="Sẽ ghi vào nhật ký.">
            <Input value={note} onChange={e => setNote(e.target.value)} placeholder="VD: Đối soát đơn tháng 4 từ TMS"/>
          </Field>
        </div>
      </Card>

      <Card title="Cột ngày" subtitle="Mỗi cột là một ngày trong quá khứ." padding={12}
        actions={<HiDateAdder onAdd={addDate} existing={dates}/>}>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {dates.map(d => (
            <div key={d} style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              padding: '6px 4px 6px 10px', borderRadius: 9999,
              background: '#eef2ff', color: 'var(--bx-primary)',
              fontSize: 12, fontWeight: 600,
            }}>
              <span style={{ fontFamily: 'var(--bx-font-mono)' }}>{fmt.shortDate(d)}</span>
              <span style={{ fontSize: 10, fontWeight: 500, opacity: 0.7 }}>{hiVnWeekday(d)}</span>
              <IconBtn name="x" size={20} onClick={() => removeDate(d)} title="Xóa ngày" style={{ marginLeft: 2 }}/>
            </div>
          ))}
        </div>
      </Card>

      <Card title={'Khách hàng · ' + rows.length + ' dòng'} subtitle="Mỗi ô là số đơn đã giao trong ngày đó."
        padding={0}>
        <div style={{ padding: 14, borderBottom: '1px solid var(--bx-border-muted)', display: 'flex', flexWrap: 'wrap', gap: 6, alignItems: 'center' }}>
          <span style={{ fontSize: 11, color: 'var(--bx-text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 700, marginRight: 4 }}>Thêm khách hàng</span>
          {availableCustomers.length === 0 ? (
            <span style={{ fontSize: 12, color: 'var(--bx-text-muted)' }}>Đã thêm tất cả khách hàng.</span>
          ) : availableCustomers.map(c => (
            <button key={c.id} onClick={() => addCustomer(c.id)} style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              padding: '6px 10px', borderRadius: 9999,
              background: '#fff', border: '1px dashed var(--bx-border)',
              fontFamily: 'var(--bx-font-sans)', fontSize: 12, color: 'var(--bx-text-dark)',
              cursor: 'pointer',
            }}>
              <Icon name="plus" size={10} style={{ color: 'var(--bx-primary)' }}/>
              <span style={{ fontFamily: 'var(--bx-font-mono)', fontWeight: 600 }}>{c.code}</span>
              <span style={{ color: 'var(--bx-text-muted)' }}>{c.name}</span>
            </button>
          ))}
        </div>

        {rows.length === 0 ? (
          <Empty icon="layers" title="Chưa có khách hàng" subtitle="Bấm một khách hàng ở trên để thêm dòng."/>
        ) : (
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'separate', borderSpacing: 0, fontSize: 13, minWidth: 700 }}>
              <thead>
                <tr>
                  <th style={hiMth({ left: true })}>Khách hàng</th>
                  {dates.map(d => (
                    <th key={d} style={hiMth()}>
                      <div style={{ fontFamily: 'var(--bx-font-mono)' }}>{fmt.shortDate(d)}</div>
                      <div style={{ fontSize: 10, fontWeight: 500, color: 'var(--bx-text-muted)' }}>{hiVnWeekday(d)}</div>
                    </th>
                  ))}
                  <th style={{ ...hiMth({ right: true }), textAlign: 'right' }}>Tổng dòng</th>
                  <th style={{ ...hiMth(), width: 36 }}></th>
                </tr>
              </thead>
              <tbody>
                {rows.map((r) => {
                  const cust = WFP.CUSTOMERS.find(c => c.id === r.customerId);
                  const rowTotal = dates.reduce((s, d) => s + (parseInt(r.qty[d], 10) || 0), 0);
                  return (
                    <tr key={r.customerId}>
                      <td style={hiMtd({ left: true })}>
                        <div style={{ fontFamily: 'var(--bx-font-mono)', fontSize: 12, fontWeight: 600, color: 'var(--bx-text-dark)' }}>{cust.code}</div>
                        <div style={{ fontSize: 11.5, color: 'var(--bx-text-muted)', marginTop: 2 }}>{cust.name}</div>
                      </td>
                      {dates.map(d => {
                        const v = r.qty[d];
                        const num = parseInt(v, 10);
                        const hasVal = !isNaN(num);
                        return (
                          <td key={d} style={hiMtd()}>
                            <input
                              type="text" inputMode="numeric" pattern="[0-9]*"
                              value={v ?? ''}
                              onChange={e => setQty(r.customerId, d, e.target.value.replace(/[^0-9]/g, ''))}
                              placeholder="0"
                              style={{
                                width: '100%', height: 34, padding: '0 8px',
                                border: '1px solid ' + (hasVal ? 'var(--bx-primary)' : 'var(--bx-border-muted)'),
                                borderRadius: 8, outline: 'none',
                                fontFamily: 'var(--bx-font-mono)', fontSize: 13, fontWeight: 600,
                                textAlign: 'right', color: 'var(--bx-text-dark)',
                                background: hasVal ? '#eef2ff' : '#fff',
                              }}
                              onFocus={e => { e.target.style.boxShadow = '0 0 0 3px rgba(11,67,234,0.18)'; e.target.style.borderColor = 'var(--bx-primary)'; }}
                              onBlur={e => { e.target.style.boxShadow = 'none'; if (!hasVal) e.target.style.borderColor = 'var(--bx-border-muted)'; }}
                            />
                          </td>
                        );
                      })}
                      <td style={{ ...hiMtd({ right: true }), textAlign: 'right' }}>
                        <span style={{ fontFamily: 'var(--bx-font-mono)', fontWeight: 700, fontSize: 13 }}>{rowTotal > 0 ? fmt.int(rowTotal) : <span style={{ color: 'var(--bx-text-muted)' }}>—</span>}</span>
                      </td>
                      <td style={hiMtd()}>
                        <IconBtn name="x" onClick={() => removeCustomer(r.customerId)} title="Xóa khách hàng"/>
                      </td>
                    </tr>
                  );
                })}
                <tr>
                  <td style={{ ...hiMtd({ left: true }), background: 'var(--bx-surface-2)', fontWeight: 700, fontSize: 12, color: 'var(--bx-text-dark)' }}>
                    Tổng cột
                  </td>
                  {dates.map(d => {
                    const colTotal = rows.reduce((s, r) => s + (parseInt(r.qty[d], 10) || 0), 0);
                    return (
                      <td key={d} style={{ ...hiMtd(), background: 'var(--bx-surface-2)', textAlign: 'right' }}>
                        <span style={{ fontFamily: 'var(--bx-font-mono)', fontWeight: 700, fontSize: 13, color: 'var(--bx-text-dark)' }}>{colTotal > 0 ? fmt.int(colTotal) : <span style={{ color: 'var(--bx-text-muted)' }}>—</span>}</span>
                      </td>
                    );
                  })}
                  <td style={{ ...hiMtd({ right: true }), background: 'var(--bx-surface-2)', textAlign: 'right' }}>
                    <span style={{ fontFamily: 'var(--bx-font-mono)', fontWeight: 700, fontSize: 14, color: 'var(--bx-primary)' }}>{fmt.int(totalOrders)}</span>
                  </td>
                  <td style={{ ...hiMtd(), background: 'var(--bx-surface-2)' }}></td>
                </tr>
              </tbody>
            </table>
          </div>
        )}
      </Card>

      <Card>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', gap: 18, alignItems: 'center', flexWrap: 'wrap' }}>
            <HiStat label="Số dòng" value={totalRows} sub="ô đã nhập"/>
            <HiStat label="Tổng số đơn" value={fmt.int(totalOrders)} sub="đơn"/>
          </div>
          <div style={{ flex: 1 }}/>
          <div style={{ display: 'flex', gap: 8 }}>
            <Button variant="outline" onClick={() => setRows([])}>Làm lại</Button>
            <Button variant="primary" icon="check" disabled={!valid} onClick={submit}>
              {submitted ? 'Đã nhập' : 'Nhập ' + totalRows + ' dòng'}
            </Button>
          </div>
        </div>
        {totalRows === 0 && (
          <div style={{ marginTop: 10, fontSize: 12, color: 'var(--bx-text-muted)' }}>
            <Icon name="info" size={11} style={{ marginRight: 4 }}/>
            Thêm ít nhất một khách hàng và nhập số đơn để có thể lưu.
          </div>
        )}
      </Card>
    </div>
  );
}

function HiDateAdder({ onAdd, existing }) {
  const [d, setD] = React.useState('2026-04-15');
  return (
    <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
      <input type="date" value={d} onChange={e => setD(e.target.value)} style={{
        height: 32, padding: '0 8px', border: '1px solid var(--bx-border)', borderRadius: 8,
        fontFamily: 'var(--bx-font-mono)', fontSize: 12, color: 'var(--bx-text-dark)', outline: 'none',
      }}/>
      <Button size="sm" variant="outline" icon="plus" disabled={existing.includes(d)} onClick={() => onAdd(d)}>Thêm ngày</Button>
    </div>
  );
}

function HiStat({ label, value, sub, tone }) {
  const c = tone === 'down' ? 'var(--bx-error)' : tone === 'up' ? 'var(--bx-success)' : 'var(--bx-text-dark)';
  return (
    <div>
      <div style={{ fontSize: 10.5, color: 'var(--bx-text-muted)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600 }}>{label}</div>
      <div style={{ fontFamily: 'var(--bx-font-mono)', fontSize: 18, fontWeight: 700, color: c, lineHeight: 1.2 }}>{value}</div>
      {sub && <div style={{ fontSize: 11, color: 'var(--bx-text-muted)' }}>{sub}</div>}
    </div>
  );
}

function hiMth(opts = {}) {
  return {
    textAlign: 'center', padding: '10px 8px', fontSize: 11,
    color: 'var(--bx-text-muted)', textTransform: 'uppercase',
    letterSpacing: '0.04em', fontWeight: 700,
    borderBottom: '1px solid var(--bx-border)',
    background: 'var(--bx-surface-2)',
    position: opts.left || opts.right ? 'sticky' : 'static',
    left: opts.left ? 0 : 'auto',
    right: opts.right ? 0 : 'auto',
    zIndex: opts.left || opts.right ? 1 : 0,
    minWidth: opts.left ? 180 : opts.right ? 100 : 110,
  };
}
function hiMtd(opts = {}) {
  return {
    padding: '8px 8px', borderBottom: '1px solid var(--bx-border-muted)',
    background: '#fff',
    position: opts.left || opts.right ? 'sticky' : 'static',
    left: opts.left ? 0 : 'auto',
    right: opts.right ? 0 : 'auto',
    zIndex: opts.left || opts.right ? 1 : 0,
  };
}
function hiVnWeekday(d) {
  const m = ['CN','T2','T3','T4','T5','T6','T7'];
  return m[new Date(d).getDay()];
}

Object.assign(window, { HiManualEntry });
