/* screens-workforce-plan.jsx — Workforce Plan generator (US-06,07,08).
   Planner LMX chọn FC + plan_date → tổng hợp accepted submissions + BQ fallback,
   compute required_hc per designation, hiển thị gap & action. */

function WorkforcePlanScreen({ warehouseId, navigate, addToast }) {
  const P = window.WFP_POINTS;
  const W = window.WFP;
  const SUBS = (W && W.CUSTOMER_FORECAST_SUBMISSIONS) || [];
  const CUSTOMER_BASE = W.CUSTOMER_BASE || {};

  const fcOpts = P.BRANCHES.map(b => ({ value: b.id, label: b.label + (b.active ? '' : ' — inactive'), disabled: !b.active }));
  const [fc, setFc] = React.useState('LMX');
  const [planDate, setPlanDate] = React.useState('2026-06-06');
  const [plan, setPlan] = React.useState(null);
  const [planState, setPlanState] = React.useState('Draft');

  function generate() {
    const fInputs = [];
    // 1) Accepted submissions covering plan_date
    SUBS.filter(s => s.fulfillment_center === fc && s.workflow_state === 'Plan Accepted'
                   && s.period_start <= planDate && planDate <= s.period_end)
        .forEach(s => {
          const dayRow = s.daily_forecasts.find(d => d.forecast_date === planDate);
          if (dayRow) {
            fInputs.push({
              customer: s.customer,
              customer_code: s.customer_code,
              source: 'Customer Submitted',
              submission_ref: s.id,
              expected_orders: dayRow.expected_orders,
            });
          }
        });
    // 2) BQ baseline fallback for customers without submission
    const submittedSet = new Set(fInputs.map(x => x.customer_code));
    Object.keys(CUSTOMER_BASE).forEach(cc => {
      if (!submittedSet.has(cc)) {
        const bq = W.BQ_BASELINE_LOOKUP ? W.BQ_BASELINE_LOOKUP(cc, fc, planDate) : 0;
        if (bq > 0) {
          fInputs.push({
            customer: CUSTOMER_BASE[cc].name,
            customer_code: cc,
            source: 'BQ Baseline',
            submission_ref: null,
            expected_orders: bq,
          });
        }
      }
    });

    const availableMap = (W.AVAILABLE_HC && W.AVAILABLE_HC[fc]) || {};
    const result = P.computePlan({ fc, planDate, forecastInputs: fInputs, availableHCByDesig: availableMap });
    setPlan(result);
    setPlanState('Draft');
    if (addToast) addToast({ kind: 'SUCCESS', title: 'Plan generated', body: `${fInputs.length} forecast input — ${result.total_workload_pts.toFixed(0)} pts` });
  }

  function publish() {
    setPlanState('Published');
    if (addToast) addToast({ kind: 'SUCCESS', title: 'Plan published', body: 'Trưởng kho có thể đọc plan rồi.' });
  }

  function lock() {
    setPlanState('Locked');
    if (addToast) addToast({ kind: 'INFO', title: 'Plan locked', body: 'Chỉ HR Manager edit được.' });
  }

  function updateAction(idx, val) {
    setPlan(prev => {
      const dp = prev.designation_plan.slice();
      dp[idx] = Object.assign({}, dp[idx], { action: val });
      return Object.assign({}, prev, { designation_plan: dp });
    });
  }
  function updateNotes(idx, val) {
    setPlan(prev => {
      const dp = prev.designation_plan.slice();
      dp[idx] = Object.assign({}, dp[idx], { notes: val });
      return Object.assign({}, prev, { designation_plan: dp });
    });
  }

  function gapBadge(g) {
    if (g > 0) return <Badge kind="danger">+{g} thiếu</Badge>;
    if (g < 0) return <Badge kind="info">{g} dư</Badge>;
    return <Badge kind="success">✓ đủ</Badge>;
  }
  function stateBadge(s) {
    const map = { 'Draft': 'neutral', 'Published': 'success', 'Locked': 'info' };
    return <Badge kind={map[s] || 'neutral'}>{s}</Badge>;
  }

  const editable = planState === 'Draft';

  return (
    <div style={{ padding: 20, overflowY: 'auto' }}>
      <PageHeader
        title={`Workforce Plan ${plan ? `· WFP-${fc}-${planDate}` : ''}`}
        subtitle={`Point-based plan generator — Boxme ${P.getBranch(fc) ? P.getBranch(fc).label : fc}`}
      />

      <Card title="Generator" padding={16} style={{ marginBottom: 12 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr auto', gap: 12, alignItems: 'flex-end' }}>
          <Field label="Fulfillment Center">
            <Select value={fc} onChange={setFc} options={fcOpts}/>
          </Field>
          <Field label="Plan date">
            <Input type="date" value={planDate} onChange={setPlanDate}/>
          </Field>
          <Field label="Settings snapshot">
            <div style={{ fontSize: 12, color: 'var(--bx-text-muted)' }}>
              shift = {P.SETTINGS.shift_hours}h · attendance = {(P.SETTINGS.attendance_rate * 100).toFixed(0)}%
            </div>
          </Field>
          <Button variant="primary" icon="zap" onClick={generate}>Generate Draft</Button>
        </div>
      </Card>

      {!plan && (
        <Empty icon="info" title="Chưa generate plan" subtitle="Chọn FC + plan_date rồi bấm Generate Draft."/>
      )}

      {plan && (
        <React.Fragment>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12, marginBottom: 12 }}>
            <Metric icon="layers" label="Total workload" value={plan.total_workload_pts.toLocaleString('vi-VN')} sublabel="points"/>
            <Metric icon="check-circle" label="Customer submitted" value={plan.accepted_submissions_count}/>
            <Metric icon="database" label="BQ fallback" value={plan.fallback_customers_count}/>
            <Metric icon="users" label="Total required HC" value={plan.designation_plan.reduce((s, r) => s + r.required_hc, 0)}/>
            <Metric icon="alert-circle" label="Total gap"
                    value={plan.designation_plan.reduce((s, r) => s + Math.max(0, r.gap), 0)}
                    deltaTone="danger"/>
          </div>

          <Card title="Workflow state" padding={12} style={{ marginBottom: 12 }}>
            <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
              {stateBadge(planState)}
              <span style={{ fontSize: 12, color: 'var(--bx-text-muted)' }}>
                Generated at {new Date(plan.last_generated_at).toLocaleString('vi-VN')}
              </span>
              <div style={{ flex: 1 }}/>
              {planState === 'Draft' && <Button variant="primary" icon="upload" onClick={publish}>Publish</Button>}
              {planState === 'Published' && <Button variant="secondary" icon="lock" onClick={lock}>Lock</Button>}
            </div>
          </Card>

          <Card title="Forecast Input (per customer)" padding={0} style={{ marginBottom: 12 }}>
            <table style={{ width: '100%', fontSize: 13 }}>
              <thead>
                <tr style={{ background: 'var(--bx-page-bg)', color: 'var(--bx-text-muted)' }}>
                  <th style={{ padding: 8, textAlign: 'left' }}>Customer</th>
                  <th style={{ padding: 8 }}>Source</th>
                  <th style={{ padding: 8, textAlign: 'right' }}>Orders</th>
                  <th style={{ padding: 8, textAlign: 'right' }}>Packing pts</th>
                  <th style={{ padding: 8, textAlign: 'right' }}>Picking pts</th>
                  <th style={{ padding: 8, textAlign: 'right' }}>Handover pts</th>
                  <th style={{ padding: 8, textAlign: 'right' }}>VAS pts</th>
                </tr>
              </thead>
              <tbody>
                {plan.forecast_input.map((f, i) => (
                  <tr key={f.customer_code || i}>
                    <td style={{ padding: 8, borderTop: '1px solid var(--bx-border-soft)' }}><strong>{f.customer}</strong></td>
                    <td style={{ padding: 8, borderTop: '1px solid var(--bx-border-soft)' }}>
                      <Badge kind={f.source === 'Customer Submitted' ? 'success' : 'warning'}>{f.source}</Badge>
                    </td>
                    <td style={{ padding: 8, textAlign: 'right', borderTop: '1px solid var(--bx-border-soft)' }}>{f.expected_orders.toLocaleString('vi-VN')}</td>
                    <td style={{ padding: 8, textAlign: 'right', borderTop: '1px solid var(--bx-border-soft)', fontFamily: 'monospace' }}>{f.workload_packing.toLocaleString('vi-VN')}</td>
                    <td style={{ padding: 8, textAlign: 'right', borderTop: '1px solid var(--bx-border-soft)', fontFamily: 'monospace' }}>{f.workload_picking.toLocaleString('vi-VN')}</td>
                    <td style={{ padding: 8, textAlign: 'right', borderTop: '1px solid var(--bx-border-soft)', fontFamily: 'monospace' }}>{f.workload_handover.toLocaleString('vi-VN')}</td>
                    <td style={{ padding: 8, textAlign: 'right', borderTop: '1px solid var(--bx-border-soft)', fontFamily: 'monospace' }}>{f.workload_vas.toLocaleString('vi-VN')}</td>
                  </tr>
                ))}
                <tr style={{ background: 'var(--bx-page-bg)', fontWeight: 700 }}>
                  <td style={{ padding: 8 }} colSpan={2}>Tổng</td>
                  <td style={{ padding: 8, textAlign: 'right' }}>{plan.forecast_input.reduce((s, f) => s + f.expected_orders, 0).toLocaleString('vi-VN')}</td>
                  <td style={{ padding: 8, textAlign: 'right', fontFamily: 'monospace' }}>{plan.total_pts_by_task.Packing.toLocaleString('vi-VN')}</td>
                  <td style={{ padding: 8, textAlign: 'right', fontFamily: 'monospace' }}>{plan.total_pts_by_task.Picking.toLocaleString('vi-VN')}</td>
                  <td style={{ padding: 8, textAlign: 'right', fontFamily: 'monospace' }}>{plan.total_pts_by_task.Handover.toLocaleString('vi-VN')}</td>
                  <td style={{ padding: 8, textAlign: 'right', fontFamily: 'monospace' }}>{plan.total_pts_by_task.VAS.toLocaleString('vi-VN')}</td>
                </tr>
              </tbody>
            </table>
          </Card>

          <Card title="Designation Plan (required vs available)" padding={0}>
            <table style={{ width: '100%', fontSize: 13 }}>
              <thead>
                <tr style={{ background: 'var(--bx-page-bg)', color: 'var(--bx-text-muted)' }}>
                  <th style={{ padding: 8, textAlign: 'left' }}>Designation · Task</th>
                  <th style={{ padding: 8, textAlign: 'right' }}>Workload (pts)</th>
                  <th style={{ padding: 8, textAlign: 'right' }}>PPH p25</th>
                  <th style={{ padding: 8, textAlign: 'right' }}>Hours</th>
                  <th style={{ padding: 8, textAlign: 'right' }}>Required HC</th>
                  <th style={{ padding: 8, textAlign: 'right' }}>Available</th>
                  <th style={{ padding: 8 }}>Gap</th>
                  <th style={{ padding: 8 }}>Action</th>
                  <th style={{ padding: 8 }}>Notes</th>
                </tr>
              </thead>
              <tbody>
                {plan.designation_plan.map((dp, i) => (
                  <tr key={dp.designation}>
                    <td style={{ padding: 8, borderTop: '1px solid var(--bx-border-soft)' }}>
                      <strong>{dp.designation}</strong><br/>
                      <span style={{ fontSize: 11, color: 'var(--bx-text-muted)' }}>{dp.task_type}</span>
                    </td>
                    <td style={{ padding: 8, textAlign: 'right', borderTop: '1px solid var(--bx-border-soft)', fontFamily: 'monospace' }}>{dp.required_points.toLocaleString('vi-VN')}</td>
                    <td style={{ padding: 8, textAlign: 'right', borderTop: '1px solid var(--bx-border-soft)' }}>{dp.pph_used_snapshot.toLocaleString('vi-VN')}</td>
                    <td style={{ padding: 8, textAlign: 'right', borderTop: '1px solid var(--bx-border-soft)' }}>{dp.required_hours.toFixed(1)}h</td>
                    <td style={{ padding: 8, textAlign: 'right', borderTop: '1px solid var(--bx-border-soft)', fontWeight: 700 }}>{dp.required_hc}</td>
                    <td style={{ padding: 8, textAlign: 'right', borderTop: '1px solid var(--bx-border-soft)' }}>{dp.available_hc}</td>
                    <td style={{ padding: 8, borderTop: '1px solid var(--bx-border-soft)' }}>{gapBadge(dp.gap)}</td>
                    <td style={{ padding: 8, borderTop: '1px solid var(--bx-border-soft)' }}>
                      <Select value={dp.action} onChange={v => updateAction(i, v)} disabled={!editable}
                        options={[
                          { value: 'OK', label: 'OK' },
                          { value: 'Need CTV', label: 'Need CTV' },
                          { value: 'Need OT', label: 'Need OT' },
                          { value: 'Reassign', label: 'Reassign' },
                          { value: 'Reduce', label: 'Reduce' },
                        ]}/>
                    </td>
                    <td style={{ padding: 8, borderTop: '1px solid var(--bx-border-soft)' }}>
                      <Input value={dp.notes} onChange={v => updateNotes(i, v)} disabled={!editable} placeholder="..."/>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Card>

          <Card padding={12} style={{ marginTop: 12, background: 'var(--bx-page-bg)' }}>
            <div style={{ fontSize: 11, color: 'var(--bx-text-muted)', fontFamily: 'monospace' }}>
              Công thức: workload_pts = Σ(orders × PPO) · required_hours = workload_pts / PPH_p25 ·
              required_hc = ⌈required_hours / (shift × attendance)⌉ = ⌈hours / {(P.SETTINGS.shift_hours * P.SETTINGS.attendance_rate).toFixed(2)}⌉
            </div>
          </Card>
        </React.Fragment>
      )}
    </div>
  );
}

window.WorkforcePlanScreen = WorkforcePlanScreen;
