/* screens-customer-submit.jsx — Customer Submission Form (US-01..03).
   Khách hàng pilot submit forecast 7 ngày tới. Validate lead time + period window. */

function CustomerSubmitScreen({ warehouseId, navigate, addToast }) {
  const P = window.WFP_POINTS;
  const W = window.WFP;
  const CUSTOMERS_DB = W.CUSTOMER_BASE || {};

  const customerOpts = Object.entries(CUSTOMERS_DB).map(([code, c]) => ({
    value: code, label: `${c.name} (${code})`,
  }));
  const fcOpts = P.BRANCHES.map(b => ({ value: b.id, label: b.label + (b.active ? '' : ' — inactive'), disabled: !b.active }));
  const typeOpts = P.SUBMISSION_TYPES.map(s => ({ value: s.id, label: `${s.label} — lead ≥${s.leadTime}d` }));

  const TODAY = '2026-05-26';
  const [customerCode, setCustomerCode] = React.useState('CUST-00234');
  const [fc, setFc] = React.useState('LMX');
  const [type, setType] = React.useState('Mega Sale');
  const [periodStart, setPeriodStart] = React.useState('2026-06-05');
  const [periodEnd, setPeriodEnd] = React.useState('2026-06-08');
  const [rows, setRows] = React.useState([]);
  const [submitted, setSubmitted] = React.useState(null);
  const [errors, setErrors] = React.useState([]);

  // Recompute date rows when type/start changes
  React.useEffect(() => {
    const st = P.getSubmissionType(type);
    if (!st) return;
    const start = new Date(periodStart + 'T00:00:00Z');
    let dates = [];
    if (st.rowSpec === 'pair') {
      dates = [
        new Date(start.getTime() - 86400000).toISOString().slice(0, 10),
        periodStart,
      ];
      setPeriodEnd(periodStart);
    } else if (st.rowSpec === 'window4') {
      dates = [-1, 0, 1, 2].map(off => new Date(start.getTime() + off * 86400000).toISOString().slice(0, 10));
      setPeriodEnd(dates[3]);
    } else { // free / BAU — default 7 days
      dates = Array.from({ length: 7 }, (_, i) => new Date(start.getTime() + i * 86400000).toISOString().slice(0, 10));
      setPeriodEnd(dates[6]);
    }
    setRows(dates.map(d => {
      const bq = W.BQ_BASELINE_LOOKUP ? W.BQ_BASELINE_LOOKUP(customerCode, fc, d) : 0;
      return { forecast_date: d, expected_orders: Math.round(bq * 1.05), bq_reference_orders: bq };
    }));
  }, [type, periodStart, customerCode, fc]);

  function validate() {
    const errs = [];
    const lead = P.validateLeadTime(type, periodStart, TODAY);
    if (!lead.ok) errs.push(`Lead time không đủ: cần ≥${lead.need} ngày, hiện ${lead.got} ngày trước period_start.`);
    const win = P.validatePeriodWindow(type, rows);
    if (!win.ok) errs.push(`Số ngày forecast không hợp lệ: cần ${win.need}, có ${win.got}.`);
    if (!customerCode) errs.push('Thiếu customer_code.');
    if (rows.some(r => !r.expected_orders || r.expected_orders < 0)) errs.push('Giá trị expected_orders phải > 0.');
    return errs;
  }

  function onSubmit() {
    const errs = validate();
    setErrors(errs);
    if (errs.length) {
      if (addToast) addToast({ kind: 'ERROR', title: 'Validation thất bại', body: errs[0] });
      return;
    }
    const total = rows.reduce((s, r) => s + (+r.expected_orders || 0), 0);
    const bqTotal = rows.reduce((s, r) => s + (r.bq_reference_orders || 0), 0);
    const v = P.classifyVariance(total, bqTotal);
    const submissionId = 'CFS-' + String(Math.floor(Math.random() * 9000) + 1000);
    const result = {
      submission_id: submissionId,
      customer_code: customerCode,
      customer: (CUSTOMERS_DB[customerCode] || {}).name || '',
      fc,
      submission_type: type,
      total_orders_submitted: total,
      bq_baseline_total: bqTotal,
      variance_pct: v.pct,
      variance_flag: v.flag,
      account_manager: (CUSTOMERS_DB[customerCode] || {}).am || P.SETTINGS.default_fallback_am,
      lead_time_days: P.validateLeadTime(type, periodStart, TODAY).leadTimeDays,
      submitted_at: new Date().toISOString(),
      daily_forecasts: rows.slice(),
      workflow_state: 'Open',
    };
    setSubmitted(result);
    if (addToast) addToast({ kind: 'SUCCESS', title: 'Đã submit', body: `${submissionId} → AM ${result.account_manager}` });
  }

  function updateRow(idx, val) {
    const v = Math.max(0, parseInt(val, 10) || 0);
    const next = rows.slice();
    next[idx] = Object.assign({}, next[idx], { expected_orders: v });
    setRows(next);
  }

  const st = P.getSubmissionType(type);
  const lead = P.validateLeadTime(type, periodStart, TODAY);

  return (
    <div style={{ padding: 20, overflowY: 'auto', maxWidth: 960, margin: '0 auto' }}>
      <PageHeader title="Customer Submission Form" subtitle="Khách hàng tự khai forecast — Boxme Workforce Planner v3"/>

      <Card title="1. Thông tin khách hàng" padding={16} style={{ marginBottom: 12 }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
          <Field label="Customer" required>
            <Select value={customerCode} onChange={setCustomerCode} options={customerOpts}/>
          </Field>
          <Field label="Fulfillment Center" required>
            <Select value={fc} onChange={setFc} options={fcOpts}/>
          </Field>
          <Field label="Submission Type" required hint={st ? st.desc : ''}>
            <Select value={type} onChange={setType} options={typeOpts}/>
          </Field>
        </div>
      </Card>

      <Card title="2. Period" padding={16} style={{ marginBottom: 12 }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, alignItems: 'flex-end' }}>
          <Field label="Period start (ngày promo / ngày đầu BAU)" required
                 hint={`Lead time cần ≥${st ? st.leadTime : 7} ngày`}
                 error={!lead.ok ? `Hiện ${lead.got} ngày, cần ${lead.need} ngày` : null}>
            <Input type="date" value={periodStart} onChange={setPeriodStart}/>
          </Field>
          <Field label="Period end" hint="Auto theo loại submission">
            <Input type="date" value={periodEnd} onChange={() => {}} disabled/>
          </Field>
          <div style={{ fontSize: 12, color: 'var(--bx-text-muted)', padding: '8px 4px' }}>
            Today: <strong>{TODAY}</strong><br/>
            Lead: <strong style={{ color: lead.ok ? 'var(--bx-color-green)' : 'var(--bx-color-red)' }}>{lead.ok ? '✓' : '✗'} {lead.got} ngày</strong>
          </div>
        </div>
      </Card>

      <Card title={`3. Daily forecasts (${rows.length} ngày)`} padding={16} style={{ marginBottom: 12 }}>
        <table style={{ width: '100%', fontSize: 13 }}>
          <thead>
            <tr style={{ color: 'var(--bx-text-muted)', textAlign: 'left' }}>
              <th style={{ padding: '6px 8px' }}>Forecast date</th>
              <th style={{ padding: '6px 8px' }}>BQ baseline</th>
              <th style={{ padding: '6px 8px' }}>Expected orders</th>
              <th style={{ padding: '6px 8px' }}>Δ vs baseline</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((r, i) => {
              const d = r.expected_orders - r.bq_reference_orders;
              return (
                <tr key={r.forecast_date}>
                  <td style={{ padding: '6px 8px', borderTop: '1px solid var(--bx-border-soft)' }}>{r.forecast_date}</td>
                  <td style={{ padding: '6px 8px', borderTop: '1px solid var(--bx-border-soft)', color: 'var(--bx-text-muted)' }}>{r.bq_reference_orders.toLocaleString('vi-VN')}</td>
                  <td style={{ padding: '6px 8px', borderTop: '1px solid var(--bx-border-soft)' }}>
                    <Input type="number" value={r.expected_orders} onChange={v => updateRow(i, v)} style={{ width: 120 }}/>
                  </td>
                  <td style={{ padding: '6px 8px', borderTop: '1px solid var(--bx-border-soft)', color: d >= 0 ? 'var(--bx-color-green)' : 'var(--bx-color-red)' }}>
                    {d >= 0 ? '+' : ''}{d.toLocaleString('vi-VN')}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </Card>

      {errors.length > 0 && (
        <Card padding={12} style={{ marginBottom: 12, background: 'var(--bx-color-red-soft)' }}>
          <div style={{ fontWeight: 600, color: 'var(--bx-color-red)' }}>Validation lỗi:</div>
          <ul style={{ margin: '6px 0 0 18px', fontSize: 13 }}>
            {errors.map((e, i) => <li key={i}>{e}</li>)}
          </ul>
        </Card>
      )}

      <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginBottom: 16 }}>
        <Button variant="ghost" onClick={() => setSubmitted(null)}>Reset</Button>
        <Button variant="primary" icon="check" onClick={onSubmit}>Submit forecast</Button>
      </div>

      {submitted && (
        <Card title={`✓ Submitted: ${submitted.submission_id}`} padding={16} style={{ background: 'var(--bx-color-green-soft)' }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, fontSize: 13 }}>
            <div><div style={{ color: 'var(--bx-text-muted)', fontSize: 11 }}>Customer</div><strong>{submitted.customer}</strong></div>
            <div><div style={{ color: 'var(--bx-text-muted)', fontSize: 11 }}>Total orders</div><strong>{submitted.total_orders_submitted.toLocaleString('vi-VN')}</strong></div>
            <div><div style={{ color: 'var(--bx-text-muted)', fontSize: 11 }}>Variance</div><strong>{submitted.variance_pct.toFixed(1)}% — {submitted.variance_flag}</strong></div>
            <div><div style={{ color: 'var(--bx-text-muted)', fontSize: 11 }}>AM</div><strong>{submitted.account_manager}</strong></div>
          </div>
          <div style={{ marginTop: 10, fontSize: 12, color: 'var(--bx-text-muted)' }}>
            State: <Badge kind="info">Open</Badge> · AM sẽ review trong 24h.
          </div>
        </Card>
      )}
    </div>
  );
}

window.CustomerSubmitScreen = CustomerSubmitScreen;
