/* global window, React */
// ============================================================
// Edit drawer — manually update one or many trips
// ============================================================

const { useState: useEditState } = React;

function Field({ label, sub, children }) {
  return (
    <div className="field">
      <label className="field__label">{label}</label>
      {children}
      {sub && <div className="field__sub">{sub}</div>}
    </div>
  );
}

function Seg({ value, options, onChange, multi }) {
  if (multi) {
    return (
      <div className="seg">
        {options.map(o => (
          <button
            key={o.v}
            className={`seg__btn ${value.includes(o.v) ? 'on' : ''}`}
            onClick={() => {
              const next = value.includes(o.v) ? value.filter(x => x !== o.v) : [...value, o.v];
              onChange(next);
            }}
          >{o.label}</button>
        ))}
      </div>
    );
  }
  return (
    <div className="seg">
      {options.map(o => (
        <button
          key={o.v}
          className={`seg__btn ${value === o.v ? 'on' : ''}`}
          onClick={() => onChange(o.v)}
        >{o.label}</button>
      ))}
    </div>
  );
}

function EditDrawer({ trip, trips, onClose, onSave }) {
  const isMulti = !trip && trips && trips.length > 0;
  const targetCount = isMulti ? trips.length : 1;

  // Tabs — Orders & drops only meaningful when ≥1 trip; works for single OR multi.
  const [tab, setTab] = useEditState('props');

  // Default field values
  const initialFleet  = trip ? trip.fleet : '';
  const initialMode   = trip ? trip.mode : '';
  const initialStatus = trip ? trip.status : '';
  const initialPriority = 'normal';

  const [fleet, setFleet]       = useEditState(initialFleet);
  const [mode, setMode]         = useEditState(initialMode);
  const [status, setStatus]     = useEditState(initialStatus);
  const [priority, setPriority] = useEditState(initialPriority);
  const [pickup, setPickup]     = useEditState(trip?.routing?.nodes?.[0]?.time || '');
  const [delivery, setDelivery] = useEditState(trip?.routing?.nodes?.[2]?.time || '');
  const [tolerance, setTolerance] = useEditState(0);
  const [note, setNote]         = useEditState('');

  // Orders & drops working state (single-trip primary; bulk uses first checked trip)
  const workingTrip = trip || (trips && trips[0]);
  const [moves, setMoves] = useEditState([]); // {orderId, fromTripId, toTripId}
  const [adds, setAdds]   = useEditState([]); // {poolOrderId, toTripId}

  // For bulk, only show fields where the user explicitly chooses to override
  const [bulkFields, setBulkFields] = useEditState({
    fleet: false, mode: false, status: false, priority: false, delivery: false,
  });
  const toggleBulkField = (k) => setBulkFields(f => ({ ...f, [k]: !f[k] }));

  return (
    <>
      <div className="drawer__overlay" onClick={onClose}></div>
      <div className="drawer drawer--wide">
        <div className="drawer__head">
          <div>
            <div style={{
              fontFamily: 'var(--font-mono)', fontSize: 10,
              textTransform: 'uppercase', letterSpacing: '0.06em',
              color: 'var(--ink-3)', marginBottom: 3,
            }}>
              {isMulti ? `Bulk edit · ${targetCount} trips` : `Edit · ${trip.id}`}
            </div>
            <div className="drawer__title">
              {isMulti
                ? `${targetCount} trips · ${new Set(trips.map(t => `${t.route.from}→${t.route.to}`)).size} lanes`
                : `${trip.route.from} → ${trip.route.to}`
              }
            </div>
            <div className="drawer__sub">
              {isMulti
                ? trips.map(t => t.id).join(' · ')
                : trip.customer
              }
            </div>
          </div>
          <button className="drawer__close" onClick={onClose}>✕</button>
        </div>

        {/* Tabs */}
        <div className="drawer__tabs">
          <button className={`drawer__tab ${tab === 'props' ? 'drawer__tab--active' : ''}`}
                  onClick={() => setTab('props')}>
            <span className="num">1</span> Properties
          </button>
          <button className={`drawer__tab ${tab === 'orders' ? 'drawer__tab--active' : ''}`}
                  onClick={() => setTab('orders')}>
            <span className="num">2</span> Orders &amp; drops
            {(moves.length + adds.length) > 0 && <span className="drawer__tab-badge">{moves.length + adds.length}</span>}
          </button>
        </div>

        <div className="drawer__body">
          {tab === 'props' && (
            <EditProperties
              isMulti={isMulti} targetCount={targetCount} trip={trip} trips={trips}
              fleet={fleet} setFleet={setFleet}
              mode={mode} setMode={setMode}
              status={status} setStatus={setStatus}
              priority={priority} setPriority={setPriority}
              pickup={pickup} setPickup={setPickup}
              delivery={delivery} setDelivery={setDelivery}
              tolerance={tolerance} setTolerance={setTolerance}
              note={note} setNote={setNote}
              bulkFields={bulkFields} toggleBulkField={toggleBulkField}
            />
          )}

          {tab === 'orders' && (
            <EditOrdersDrops
              isMulti={isMulti}
              primaryTrip={workingTrip}
              trips={trips}
              moves={moves} setMoves={setMoves}
              adds={adds} setAdds={setAdds}
            />
          )}
        </div>

        <div className="drawer__foot">
          <button className="btn" onClick={onClose}>Cancel</button>
          <button
            className="btn btn--primary"
            onClick={() => onSave({
              fleet, mode, status, priority, pickup, delivery, tolerance, note, moves, adds,
              bulkFields: isMulti ? bulkFields : null,
            })}
          >✓ Save {isMulti ? `${targetCount} trips` : 'changes'}{(moves.length + adds.length) > 0 ? ` · ${moves.length + adds.length} order op${(moves.length + adds.length) === 1 ? '' : 's'}` : ''}</button>
        </div>
      </div>
    </>
  );
}

function EditProperties({
  isMulti, targetCount, trip, trips,
  fleet, setFleet, mode, setMode, status, setStatus, priority, setPriority,
  pickup, setPickup, delivery, setDelivery, tolerance, setTolerance, note, setNote,
  bulkFields, toggleBulkField,
}) {
  return (
    <>
      {isMulti && (
        <div style={{
          padding: '10px 12px', background: 'var(--amber-bg)',
          borderLeft: '2px solid var(--amber)', borderRadius: 'var(--r-sm)',
          fontSize: 11.5, color: 'var(--amber-2)', marginBottom: 16, lineHeight: 1.45,
        }}>
          <strong>Bulk edit.</strong> Toggle a field to override it across all {targetCount} trips.
          Fields left untoggled keep each trip's current value.
        </div>
      )}

      <Field label={
        <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          Fleet type
          {isMulti && <Toggle on={bulkFields.fleet} onChange={() => toggleBulkField('fleet')} />}
        </span>
      }>
        <Seg
          value={fleet}
          onChange={setFleet}
          options={[
            { v: 'private',   label: 'Private' },
            { v: 'dedicated', label: 'Dedicated' },
            { v: 'market',    label: 'Market' },
            { v: 'spot',      label: 'Spot' },
          ]}
        />
        {isMulti && !bulkFields.fleet && <div className="field__sub">Will keep each trip's current fleet type.</div>}
        {!isMulti && trip && trip.fleet !== fleet && (
          <div className="note-warn">Changing fleet may require manager approval per policy "Fleet type change from private to spot — always TP decision".</div>
        )}
      </Field>

      <Field label={
        <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          Mode
          {isMulti && <Toggle on={bulkFields.mode} onChange={() => toggleBulkField('mode')} />}
        </span>
      }>
        <Seg
          value={mode}
          onChange={setMode}
          options={[
            { v: 'FTL', label: 'FTL' },
            { v: 'LTL', label: 'LTL' },
            { v: 'Intermodal', label: 'Intermodal' },
          ]}
        />
      </Field>

      <Field label={
        <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          Status
          {isMulti && <Toggle on={bulkFields.status} onChange={() => toggleBulkField('status')} />}
        </span>
      }>
        <Seg
          value={status}
          onChange={setStatus}
          options={[
            { v: 'PLANNED',   label: 'Planned' },
            { v: 'HELD',      label: 'Hold' },
            { v: 'CONFIRMED', label: 'Confirm' },
            { v: 'CANCEL',    label: 'Cancel' },
          ]}
        />
      </Field>

      <Field label={
        <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          Priority
          {isMulti && <Toggle on={bulkFields.priority} onChange={() => toggleBulkField('priority')} />}
        </span>
      }>
        <Seg
          value={priority}
          onChange={setPriority}
          options={[
            { v: 'normal',   label: 'Normal' },
            { v: 'priority', label: 'Priority' },
            { v: 'urgent',   label: 'Urgent' },
          ]}
        />
      </Field>

      {!isMulti && (
        <>
          <div className="field__row">
            <Field label="Pickup time (CDT)">
              <input className="input mono" value={pickup} onChange={e => setPickup(e.target.value)} />
            </Field>
            <Field label="Delivery deadline">
              <input className="input mono" value={delivery} onChange={e => setDelivery(e.target.value)} />
            </Field>
          </div>

          <Field label="Window tolerance" sub="Hours of flex applied to delivery deadline. Above 4h requires manager sign-off.">
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <input
                type="range" min="0" max="8" step="0.5"
                value={tolerance}
                onChange={e => setTolerance(parseFloat(e.target.value))}
                style={{ flex: 1 }}
              />
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, minWidth: 60, textAlign: 'right' }}>
                {tolerance === 0 ? 'none' : `+${tolerance}h`}
              </span>
            </div>
            {tolerance > 4 && <div className="note-warn">Tolerance {tolerance}h exceeds 4h — requires Carrier Manager sign-off.</div>}
          </Field>
        </>
      )}

      {isMulti && (
        <Field label={
          <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            Window tolerance
            {isMulti && <Toggle on={bulkFields.delivery} onChange={() => toggleBulkField('delivery')} />}
          </span>
        }>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <input
              type="range" min="0" max="8" step="0.5"
              value={tolerance}
              onChange={e => setTolerance(parseFloat(e.target.value))}
              style={{ flex: 1 }}
            />
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, minWidth: 60, textAlign: 'right' }}>
              {tolerance === 0 ? 'none' : `+${tolerance}h`}
            </span>
          </div>
        </Field>
      )}

      <Field label="Edit note · audit trail" sub="Required when overriding agent recommendation or changing fleet type.">
        <textarea
          className="textarea"
          rows="3"
          placeholder="Why are you making this change? (visible to Carrier Manager + audit log)"
          value={note}
          onChange={e => setNote(e.target.value)}
        ></textarea>
      </Field>

      <div style={{
        padding: '10px 12px',
        background: 'var(--purple-bg)',
        border: '1px solid var(--purple-bg-2)',
        borderRadius: 'var(--r-md)',
        fontSize: 11.5,
        color: 'var(--ink-2)',
        lineHeight: 1.5,
        display: 'flex', gap: 10,
      }}>
        <span style={{
          width: 22, height: 22, background: 'var(--purple)', color: 'white',
          borderRadius: 4, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'var(--font-serif)', fontWeight: 700, fontSize: 11, flexShrink: 0,
        }}>TP</span>
        <span>
          <span style={{ color: 'var(--purple-2)', fontWeight: 600, marginRight: 4 }}>Agent will:</span>
          re-run feasibility on {isMulti ? `${targetCount} trips` : 'this trip'} after save · update HOS gap · refresh fleet recommendations · log edit to audit trail.
        </span>
      </div>
    </>
  );
}

// ============================================================
// Orders & drops — add from pool, move drops between trips,
// visualise on the route map.
// ============================================================
function EditOrdersDrops({ isMulti, primaryTrip, trips, moves, setMoves, adds, setAdds }) {
  const allTrips = window.TRIPS || [];
  const [activeTripId, setActiveTripId] = React.useState(primaryTrip ? primaryTrip.id : '');
  const activeTrip = allTrips.find(t => t.id === activeTripId) || primaryTrip;

  // Other trips this user can move drops to: in multi-edit, the bulk-selected trips;
  // in single, all other planned trips on a similar lane.
  const moveTargets = isMulti && trips
    ? trips.filter(t => t.id !== activeTrip.id)
    : allTrips.filter(t => t.id !== activeTrip.id && t.status === 'PLANNED');

  // Pool orders available to add — use activeTrip.poolOrders + cross-lane pool.
  const pool = activeTrip.poolOrders || [];

  const addToTrip = (poolOrder) => {
    if (adds.some(a => a.poolOrderId === poolOrder.id)) return;
    setAdds([...adds, { poolOrderId: poolOrder.id, toTripId: activeTrip.id, meta: poolOrder }]);
  };
  const removeAdd = (id) => setAdds(adds.filter(a => a.poolOrderId !== id));

  const moveDrop = (orderId, toTripId) => {
    setMoves([...moves.filter(m => m.orderId !== orderId), { orderId, fromTripId: activeTrip.id, toTripId }]);
  };
  const undoMove = (orderId) => setMoves(moves.filter(m => m.orderId !== orderId));

  // Build the "after save" projection for the active trip
  const movedAway = new Set(moves.filter(m => m.fromTripId === activeTrip.id).map(m => m.orderId));
  const addedHere = adds.filter(a => a.toTripId === activeTrip.id);
  const projectedOrders = activeTrip.orders.filter(o => !movedAway.has(o.id));
  const projectedLbs = projectedOrders.reduce((a, o) => a + o.lbs, 0)
    + addedHere.reduce((a, x) => {
        // pool order meta has "X pal · Y lbs · ..."
        const m = (x.meta?.meta || '').match(/(\d[\d,]*)\s*lbs/);
        return a + (m ? parseInt(m[1].replace(/,/g, ''), 10) : 0);
      }, 0);
  const projectedUtil = Math.round((projectedLbs / 45000) * 100);
  const utilKind = projectedUtil > 100 ? 'red' : projectedUtil > 95 ? 'amber' : projectedUtil < 70 ? 'amber' : 'green';

  // Extra trips for map preview = the trips orders are being moved TO
  const moveTargetIds = Array.from(new Set(moves.map(m => m.toTripId)));
  const extraTripsForMap = moveTargetIds
    .map(id => allTrips.find(t => t.id === id))
    .filter(Boolean);

  return (
    <div className="orders-drops">
      {/* Trip switcher when bulk editing */}
      {isMulti && trips && (
        <div className="orders-drops__switcher">
          <span className="orders-drops__switcher-label">Editing</span>
          {trips.map(t => (
            <button
              key={t.id}
              className={`orders-drops__switcher-btn ${activeTripId === t.id ? 'on' : ''}`}
              onClick={() => setActiveTripId(t.id)}
            >{t.id}</button>
          ))}
        </div>
      )}

      {/* Live impact summary */}
      <div className="orders-drops__summary">
        <div className="orders-drops__summary-card">
          <div className="orders-drops__summary-label">Active trip</div>
          <div className="orders-drops__summary-val">{activeTrip.id}</div>
          <div className="orders-drops__summary-sub">{activeTrip.route.from} → {activeTrip.route.to}</div>
        </div>
        <div className="orders-drops__summary-card">
          <div className="orders-drops__summary-label">After save</div>
          <div className={`orders-drops__summary-val util-${utilKind}`}>{projectedUtil}%</div>
          <div className="orders-drops__summary-sub">{projectedOrders.length + addedHere.length} orders · {projectedLbs.toLocaleString()} lbs</div>
        </div>
        <div className="orders-drops__summary-card">
          <div className="orders-drops__summary-label">Changes staged</div>
          <div className="orders-drops__summary-val">{moves.length + adds.length}</div>
          <div className="orders-drops__summary-sub">{adds.length} add{adds.length === 1 ? '' : 's'} · {moves.length} move{moves.length === 1 ? '' : 's'}</div>
        </div>
      </div>

      {/* Two-column layout: current orders + pool */}
      <div className="orders-drops__cols">
        {/* Current orders / drops */}
        <div className="orders-drops__col">
          <div className="orders-drops__col-head">
            Drops on {activeTrip.id} · {activeTrip.orders.length}
            <span className="orders-drops__col-sub">Reorder, remove, or move to another trip</span>
          </div>
          <div className="orders-drops__list">
            {activeTrip.orders.map(o => {
              const moveTo = moves.find(m => m.orderId === o.id);
              return (
                <div key={o.id} className={`orders-drops__drop ${moveTo ? 'moving' : ''}`}>
                  <div className="orders-drops__drop-main">
                    <div className="orders-drops__drop-id">{o.id}</div>
                    <div className="orders-drops__drop-cust">{o.customer}</div>
                    <div className="orders-drops__drop-meta">{o.pallets} pal · {o.lbs.toLocaleString()} lbs · ship {o.ship}</div>
                  </div>
                  {moveTo ? (
                    <div className="orders-drops__drop-action">
                      <span className="orders-drops__moving">
                        → moving to <b>{moveTo.toTripId}</b>
                      </span>
                      <button className="orders-drops__undo" onClick={() => undoMove(o.id)}>Undo</button>
                    </div>
                  ) : (
                    <div className="orders-drops__drop-action">
                      <select
                        className="orders-drops__select"
                        value=""
                        onChange={(e) => e.target.value && moveDrop(o.id, e.target.value)}
                      >
                        <option value="">Move to…</option>
                        {moveTargets.map(t => (
                          <option key={t.id} value={t.id}>{t.id} ({t.route.to})</option>
                        ))}
                      </select>
                    </div>
                  )}
                </div>
              );
            })}
            {addedHere.length > 0 && (
              <div className="orders-drops__added-divider">+ added from pool</div>
            )}
            {addedHere.map(a => (
              <div key={a.poolOrderId} className="orders-drops__drop adding">
                <div className="orders-drops__drop-main">
                  <div className="orders-drops__drop-id">{a.poolOrderId} <span className="pill pill--green" style={{ fontSize: 9, padding: '1px 5px' }}>POOL</span></div>
                  <div className="orders-drops__drop-cust">{a.meta?.customer}</div>
                  <div className="orders-drops__drop-meta">{a.meta?.meta}</div>
                </div>
                <button className="orders-drops__undo" onClick={() => removeAdd(a.poolOrderId)}>Undo</button>
              </div>
            ))}
          </div>
        </div>

        {/* Pool orders */}
        <div className="orders-drops__col">
          <div className="orders-drops__col-head">
            Pool · same lane · {pool.length}
            <span className="orders-drops__col-sub">Tap + to add to this trip</span>
          </div>
          <div className="orders-drops__list">
            {pool.length === 0 && <div className="orders-drops__empty">No pool orders on this lane.</div>}
            {pool.map(p => {
              const already = adds.some(a => a.poolOrderId === p.id);
              return (
                <div key={p.id} className={`orders-drops__drop pool ${already ? 'is-added' : ''}`}>
                  <div className="orders-drops__drop-main">
                    <div className="orders-drops__drop-id">{p.id}</div>
                    <div className="orders-drops__drop-cust">{p.customer}</div>
                    <div className="orders-drops__drop-meta">{p.meta}</div>
                  </div>
                  <button
                    className={`orders-drops__add ${already ? 'added' : ''}`}
                    onClick={() => already ? removeAdd(p.id) : addToTrip(p)}
                  >{already ? '✓ Added' : '+ Add'}</button>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Map preview */}
      <div className="orders-drops__map">
        <div className="orders-drops__map-head">
          <div className="orders-drops__map-title">Map preview</div>
          <div className="orders-drops__map-sub">
            Solid line = {activeTrip.id} · dashed = trips receiving moved drops
            {moveTargetIds.length === 0 && adds.length === 0 ? ' · no changes staged yet' : ''}
          </div>
        </div>
        <div className="orders-drops__map-frame">
          <window.RouteMap
            trip={activeTrip}
            extraTrips={extraTripsForMap}
            height={260}
            showLegend
          />
        </div>
      </div>
    </div>
  );
}

function Toggle({ on, onChange }) {
  return (
    <button
      onClick={onChange}
      style={{
        width: 28, height: 16,
        background: on ? 'var(--ink)' : 'var(--line-strong)',
        borderRadius: 999,
        position: 'relative',
        transition: 'background 0.12s',
      }}
      title={on ? 'Override' : 'Keep current'}
    >
      <span style={{
        position: 'absolute',
        top: 2, left: on ? 14 : 2,
        width: 12, height: 12,
        background: 'white',
        borderRadius: '50%',
        transition: 'left 0.12s',
      }}></span>
    </button>
  );
}

Object.assign(window, { EditDrawer });
