/* Prep Center — Étiquetage, bundling, contrôle qualité (Canada) */

const PREP_TASKS = [
  { id: "pc-001", lot: "FBA-2031-LOT01", product: "Diffuseur huiles essentielles 500ml", units: 240, station: "Étiquetage",   eta: "11 mai",   owner: "kevin",   status: "en cours",   priority: "haute" },
  { id: "pc-002", lot: "FBA-2032-LOT01", product: "Stylet capacitif iPad",              units: 600, station: "Bundling",     eta: "12 mai",   owner: "kevin",   status: "en cours",   priority: "moyenne" },
  { id: "pc-003", lot: "FBA-2032-LOT02", product: "Tapis souris XL gaming",              units: 600, station: "QC final",    eta: "12 mai",   owner: "carly",   status: "revue",       priority: "haute" },
  { id: "pc-004", lot: "FBA-2033-LOT01", product: "Support téléphone vélo",              units: 320, station: "Réception",   eta: "13 mai",   owner: "kevin",   status: "à faire",    priority: "moyenne" },
  { id: "pc-005", lot: "FBA-2034-LOT01", product: "Diffuseur huiles essentielles 500ml", units: 1200,station: "Douanes",     eta: "18 mai",   owner: "kevin",   status: "douanes",    priority: "moyenne" },
  { id: "pc-006", lot: "FBA-2034-LOT02", product: "Couvre-volant cuir 38cm",             units: 1200,station: "—",          eta: "18 mai",   owner: "kevin",   status: "douanes",    priority: "haute" },
  { id: "pc-007", lot: "FBA-2030-LOT01", product: "Brosse poils chien",                   units: 480, station: "—",          eta: "08 mai",   owner: "kevin",   status: "fait",        priority: "basse" },
];

const STATIONS = ["Réception", "Étiquetage", "Bundling", "QC final", "Douanes", "—"];
const STATUS_TONE = { "à faire": "muted", "en cours": "blue", "revue": "amber", "douanes": "amber", "fait": "green" };

const PrepCenter = () => {
  const [filter, setFilter] = useState("all");
  const [, force] = useState(0);
  const toast = (window.useToast || (() => () => {}))();
  const trashHook = (window.useKCCTrash || (() => ({ items: [], send: async () => {} })))();

  const [newOpen, setNewOpen] = useState(false);
  const [draft, setDraft] = useState({ lot: "", product: "", units: 0, station: "Réception", priority: "moyenne" });

  const create = async () => {
    if (!draft.product?.trim() && !draft.lot?.trim()) return;
    const id = "pc-" + Date.now().toString(36);
    const fresh = {
      id,
      title: draft.product.trim() || draft.lot.trim(),
      lot: draft.lot.trim() || id.toUpperCase(),
      product: draft.product.trim() || "—",
      units: Number(draft.units) || 0,
      station: draft.station || "Réception",
      eta: "—",
      owner: "kevin",
      status: "à faire",
      priority: draft.priority || "moyenne",
    };
    PREP_TASKS.push(fresh);
    setNewOpen(false);
    setDraft({ lot: "", product: "", units: 0, station: "Réception", priority: "moyenne" });
    force(x => x + 1);
    try {
      await fetch("/api/sync", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ col: "tasks", items: [fresh] }),
      });
    } catch (_) {}
    toast?.({ message: `Lot "${fresh.lot}" créé`, tone: "green" });
  };

  const deletePrep = async (target) => {
    if (!target) return;
    if (!window.confirm(`Mettre le lot "${target.lot}" à la corbeille ?`)) return;
    const idx = PREP_TASKS.findIndex(t => t.id === target.id);
    if (idx >= 0) PREP_TASKS.splice(idx, 1);
    await trashHook.send("tasks", { ...target, title: target.title || target.lot });
    force(x => x + 1);
    toast?.({ message: `Lot → corbeille`, tone: "muted" });
  };

  const persistPrep = async (id, patch) => {
    const t = PREP_TASKS.find(x => x.id === id);
    if (!t) return;
    Object.assign(t, patch);
    force(x => x + 1);
    try {
      await fetch("/api/sync", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ col: "prep_tasks", items: [{ ...t }] }),
      });
    } catch (_) {}
  };

  const active = PREP_TASKS.filter(t => t.status !== "fait");
  const totalUnits = active.reduce((a, b) => a + b.units, 0);
  const byStation = {};
  STATIONS.forEach(s => { byStation[s] = active.filter(t => t.station === s).reduce((a, b) => a + b.units, 0); });

  const visible = filter === "all" ? PREP_TASKS : PREP_TASKS.filter(t => t.status === filter);

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">Prep Center</div>
          <div className="page-sub">
            Étiquetage · bundling · QC · {active.length} lots actifs · {totalUnits.toLocaleString()} unités en cours
          </div>
        </div>
        <button className="btn" data-variant="primary" onClick={() => setNewOpen(true)}><Icon name="plus" size={12} /> Nouveau lot</button>
      </div>

      {/* Stations capacity */}
      <div className="grid" style={{ gridTemplateColumns: "repeat(6, 1fr)", gap: 10, marginBottom: 14 }}>
        {STATIONS.slice(0, 5).map(s => (
          <div key={s} className="card" style={{ padding: 12 }}>
            <div style={{ fontSize: 10, color: "var(--text-faint)", textTransform: "uppercase", letterSpacing: "0.06em" }}>{s}</div>
            <div className="mono" style={{ fontSize: 18, fontWeight: 600, marginTop: 4 }}>{(byStation[s] || 0).toLocaleString()}</div>
            <div className="mono" style={{ fontSize: 10.5, color: "var(--text-faint)" }}>unités</div>
          </div>
        ))}
        <div className="card" style={{ padding: 12, background: "var(--accent-soft)" }}>
          <div style={{ fontSize: 10, color: "var(--accent)", textTransform: "uppercase", letterSpacing: "0.06em" }}>Total actif</div>
          <div className="mono" style={{ fontSize: 18, fontWeight: 700, marginTop: 4, color: "var(--accent)" }}>{totalUnits.toLocaleString()}</div>
        </div>
      </div>

      <div className="row" style={{ gap: 6, marginBottom: 12, flexWrap: "wrap" }}>
        <button className="btn" data-variant={filter === "all" ? "primary" : "ghost"} onClick={() => setFilter("all")}>Tous · {PREP_TASKS.length}</button>
        {["à faire", "en cours", "revue", "douanes", "fait"].map(st => (
          <button key={st} className="btn" data-variant={filter === st ? "primary" : "ghost"} onClick={() => setFilter(st)}>
            <Badge tone={STATUS_TONE[st]} dot /> {st} · {PREP_TASKS.filter(t => t.status === st).length}
          </button>
        ))}
      </div>

      <div className="card" style={{ padding: 0, overflow: "auto" }}>
        <table className="table">
          <thead>
            <tr>
              <th>Lot</th>
              <th>Produit</th>
              <th style={{ textAlign: "right" }}>Unités</th>
              <th>Station</th>
              <th>ETA</th>
              <th>Statut</th>
              <th>Priorité</th>
              <th>Owner</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {visible.map(t => (
              <tr key={t.id}>
                <td className="mono" style={{ fontWeight: 600 }}>
                  <EditableField value={t.lot} onSave={(v) => persistPrep(t.id, { lot: v })} width={140}/>
                </td>
                <td style={{ maxWidth: 220 }}>
                  <EditableField value={t.product} onSave={(v) => persistPrep(t.id, { product: v })} width={200}/>
                </td>
                <td className="mono" style={{ textAlign: "right" }}>
                  <EditableField value={t.units} onSave={(v) => persistPrep(t.id, { units: Number(v) || 0 })} type="number" format={(v) => Number(v).toLocaleString()} width={70}/>
                </td>
                <td>
                  <EditableField value={t.station} onSave={(v) => persistPrep(t.id, { station: v })} options={STATIONS.map(s => ({ value: s, label: s }))} width={120}/>
                </td>
                <td className="mono">
                  <EditableField value={t.eta} onSave={(v) => persistPrep(t.id, { eta: v })} width={100}/>
                </td>
                <td>
                  <EditableField
                    value={t.status}
                    onSave={(v) => persistPrep(t.id, { status: v })}
                    options={[{value:"à faire",label:"à faire"},{value:"en cours",label:"en cours"},{value:"revue",label:"revue"},{value:"douanes",label:"douanes"},{value:"fait",label:"fait"}]}
                    format={(v) => <Badge tone={STATUS_TONE[v] || "muted"} dot>{v}</Badge>}
                    width={110}
                  />
                </td>
                <td>
                  <EditableField
                    value={t.priority}
                    onSave={(v) => persistPrep(t.id, { priority: v })}
                    options={[{value:"basse",label:"basse"},{value:"moyenne",label:"moyenne"},{value:"haute",label:"haute"}]}
                    format={(v) => <Badge tone={v === "haute" ? "red" : v === "moyenne" ? "amber" : "muted"}>{v}</Badge>}
                    width={100}
                  />
                </td>
                <td>
                  <EditableField
                    value={t.owner}
                    onSave={(v) => persistPrep(t.id, { owner: v })}
                    options={USERS.map(u => ({ value: u.id, label: u.name }))}
                    format={(v) => <span className="row" style={{ gap: 6 }}><Avatar user={v} size="sm" /><span style={{ textTransform: "capitalize", fontSize: 12 }}>{v}</span></span>}
                    width={100}
                  />
                </td>
                <td>
                  <button
                    className="btn" data-variant="ghost" data-size="sm"
                    title="Mettre à la corbeille"
                    onClick={() => deletePrep(t)}
                    style={{ color: "var(--red)" }}
                  >
                    <Icon name="x" size={11}/>
                  </button>
                </td>
              </tr>
            ))}
            {visible.length === 0 && (
              <tr><td colSpan={9} style={{ textAlign: "center", padding: 30, color: "var(--text-faint)" }}>
                Aucun lot — clique « + Nouveau lot » pour en créer un.
              </td></tr>
            )}
          </tbody>
        </table>
      </div>

      {newOpen && (
        <div onClick={() => setNewOpen(false)} style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.55)", zIndex: 9999, display: "grid", placeItems: "center" }}>
          <div className="card" onClick={(e) => e.stopPropagation()} style={{ width: 480, padding: 20 }}>
            <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 14 }}>Nouveau lot</div>
            <div className="stack" style={{ gap: 10 }}>
              <div>
                <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>Numéro de lot *</div>
                <div className="input" style={{ height: 32, padding: "0 10px" }}>
                  <input autoFocus value={draft.lot} onChange={(e) => setDraft(d => ({ ...d, lot: e.target.value }))} placeholder="ex: FBA-2035-LOT01" style={{ flex: 1, background: "transparent", border: "none", outline: "none", color: "var(--text)", fontSize: 12.5 }}/>
                </div>
              </div>
              <div>
                <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>Produit</div>
                <div className="input" style={{ height: 32, padding: "0 10px" }}>
                  <input value={draft.product} onChange={(e) => setDraft(d => ({ ...d, product: e.target.value }))} placeholder="Nom du produit" style={{ flex: 1, background: "transparent", border: "none", outline: "none", color: "var(--text)", fontSize: 12.5 }}/>
                </div>
              </div>
              <div>
                <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>Unités</div>
                <div className="input" style={{ height: 32, padding: "0 10px" }}>
                  <input type="number" value={draft.units} onChange={(e) => setDraft(d => ({ ...d, units: e.target.value }))} style={{ flex: 1, background: "transparent", border: "none", outline: "none", color: "var(--text)", fontSize: 12.5 }}/>
                </div>
              </div>
              <div>
                <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>Station</div>
                <select value={draft.station} onChange={(e) => setDraft(d => ({ ...d, station: e.target.value }))} className="input" style={{ height: 32, width: "100%" }}>
                  {STATIONS.map(s => <option key={s} value={s}>{s}</option>)}
                </select>
              </div>
              <div>
                <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>Priorité</div>
                <select value={draft.priority} onChange={(e) => setDraft(d => ({ ...d, priority: e.target.value }))} className="input" style={{ height: 32, width: "100%" }}>
                  <option value="basse">Basse</option>
                  <option value="moyenne">Moyenne</option>
                  <option value="haute">Haute</option>
                </select>
              </div>
            </div>
            <div className="row" style={{ marginTop: 16, justifyContent: "flex-end", gap: 8 }}>
              <button className="btn" onClick={() => setNewOpen(false)}>Annuler</button>
              <button className="btn" data-variant="primary" onClick={create} disabled={!draft.lot.trim() && !draft.product.trim()}>Créer</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

window.PrepCenter = PrepCenter;
