/* Reusable shopping-list panel
   Lives inside each area (Cocina, Bar, Ama de llaves, Yate) and inside Compras (aggregated)

   Props:
   - items: array of shopping items for this list
   - onUpdate(newItems): fired with the full new array
   - listLabel: display name ("Cocina", "Bar", ...)
   - listId: data id (used to add new items)
   - user, role
   - canEdit: can add/edit/delete items + status
   - canManageStatus: can only change status (used by Encargado de Compras when viewing other dept lists)
*/

const COMPRAS_STATUS_META_SL = {
  pendiente:     { label: "Compra pendiente", badge: "cdc-badge--pending" },
  entregado:     { label: "Comprado",         badge: "cdc-badge--done" },
  no_encontrado: { label: "No encontrado",    badge: "cdc-badge--overdue" },
};

const ShoppingListPanel = ({ items, onUpdate, listLabel, listId, user, role, canEdit = false, canManageStatus = false, hideSupplier = false }) => {
  const [editing, setEditing] = React.useState(null); // null | "new" | item.id
  const [filter, setFilter] = React.useState("todos");
  const [viewPhoto, setViewPhoto] = React.useState(null);

  const visible = items.filter(i => filter === "todos" ? true : i.status === filter);
  const counts = {
    pendiente:     items.filter(i => i.status === "pendiente").length,
    entregado:     items.filter(i => i.status === "entregado").length,
    no_encontrado: items.filter(i => i.status === "no_encontrado").length,
  };

  const upd = (newItem) => {
    const exists = items.some(i => i.id === newItem.id);
    onUpdate(exists ? items.map(i => i.id === newItem.id ? newItem : i) : [{ ...newItem, id: newItem.id || "c-" + Date.now() }, ...items]);
    setEditing(null);
  };

  const removeItem = (id) => {
    if (window.confirm("¿Eliminar este artículo?")) onUpdate(items.filter(i => i.id !== id));
  };

  const setStatus = (id, status) => {
    onUpdate(items.map(i => i.id === id ? { ...i, status } : i));
  };

  const editingItem = editing === "new"
    ? null
    : editing
      ? items.find(i => i.id === editing)
      : null;

  return (
    <>
      <div className="cdc-card__head" style={{ flexWrap: "wrap", gap: 10 }}>
        <div style={{ display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap" }}>
          <I.Cart size={18} style={{ color: "var(--cdc-ink-3)" }} />
          <div className="cdc-card__title">Lista de compras — {listLabel}</div>
          <div style={{ display: "inline-flex", gap: 4 }}>
            {[
              ["todos",         "Todos",            items.length],
              ["pendiente",     "Compra pendiente", counts.pendiente],
              ["entregado",     "Comprados",        counts.entregado],
              ["no_encontrado", "No encontrados",   counts.no_encontrado],
            ].map(([k, lbl, c]) => (
              <button key={k} className="cdc-chip" aria-pressed={filter === k} onClick={() => setFilter(k)}>
                {lbl} <span style={{ color: "var(--cdc-ink-4)", fontVariantNumeric: "tabular-nums" }}>{c}</span>
              </button>
            ))}
          </div>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <button className="cdc-pill" onClick={() => exportShoppingListPDF({
            listLabel,
            items,
            requestedBy: user.name,
          })}>
            <I.Send size={14} /> Exportar PDF
          </button>
          {canEdit && (
            <button className="cdc-btn cdc-btn--coral" onClick={() => setEditing("new")}>
              <I.Plus size={14} /> Agregar artículo
            </button>
          )}
        </div>
      </div>

      {visible.length === 0 ? (
        <div className="cdc-empty">
          <I.Cart size={42} />
          <div className="cdc-empty__title">{items.length === 0 ? "Aún no hay artículos" : "No hay artículos en este filtro"}</div>
          {canEdit && items.length === 0 && (
            <button className="cdc-btn cdc-btn--coral" onClick={() => setEditing("new")}>
              <I.Plus size={14} /> Agregar primer artículo
            </button>
          )}
        </div>
      ) : (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(330px, 1fr))", gap: 14, padding: 18 }}>
          {visible.map(it => (
            <ShoppingItemCard
              key={it.id}
              item={it}
              canEdit={canEdit}
              canManageStatus={canEdit || canManageStatus}
              hideSupplier={hideSupplier}
              onEdit={() => setEditing(it.id)}
              onRemove={() => removeItem(it.id)}
              onStatusChange={(s) => setStatus(it.id, s)}
              onViewPhoto={() => it.photo && setViewPhoto(it.photo)}
            />
          ))}
        </div>
      )}

      {editing && (
        <ShoppingItemDrawer
          item={editingItem}
          onClose={() => setEditing(null)}
          onSave={upsertCoctel => {
            const exists = items.some(x => x.id === upsertCoctel.id);
            onUpdate(exists ? items.map(x => x.id === upsertCoctel.id ? upsertCoctel : x) : [{ ...upsertCoctel, id: upsertCoctel.id || "c-" + Date.now() }, ...items]);
            setEditing(null);
          }}
          listLabel={listLabel}
          listId={listId}
          user={user}
          hideSupplier={hideSupplier}
        />
      )}

      {viewPhoto && (
        <div className="cdc-overlay" onClick={() => setViewPhoto(null)} style={{ alignItems: "center", justifyContent: "center" }}>
          <img src={viewPhoto} alt="" style={{ maxWidth: "85vw", maxHeight: "85vh", borderRadius: 12, boxShadow: "var(--cdc-shadow-lg)" }} />
        </div>
      )}
    </>
  );
};

const ShoppingItemCard = ({ item, canEdit, canManageStatus, hideSupplier, onEdit, onRemove, onStatusChange, onViewPhoto }) => {
  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: "72px 1fr",
      gap: 12,
      padding: 12,
      background: "white",
      border: "1px solid var(--cdc-border)",
      borderRadius: 12,
    }}>
      {/* Photo */}
      <button
        onClick={item.photo ? onViewPhoto : (canEdit ? onEdit : undefined)}
        style={{
          width: 72, height: 72, borderRadius: 10, overflow: "hidden",
          background: "var(--cdc-cream-100)", border: "1px solid var(--cdc-border-soft)",
          display: "flex", alignItems: "center", justifyContent: "center",
          cursor: item.photo || canEdit ? "pointer" : "default",
          padding: 0,
        }}
      >
        {item.photo ? (
          <img src={item.photo} alt={item.name} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
        ) : (
          <I.Camera size={22} stroke={1.4} style={{ color: "var(--cdc-ink-4)" }} />
        )}
      </button>

      <div style={{ minWidth: 0 }}>
        <div style={{ display: "flex", justifyContent: "space-between", gap: 6, alignItems: "flex-start" }}>
          <div style={{ minWidth: 0, flex: 1 }}>
            <div style={{ fontWeight: 600, fontSize: 14, color: "var(--cdc-ink)", lineHeight: 1.3 }}>
              {item.name}
            </div>
            <div style={{ fontSize: 12.5, color: "var(--cdc-ink-3)", marginTop: 2, fontVariantNumeric: "tabular-nums" }}>
              <strong style={{ color: "var(--cdc-ink-2)" }}>{item.qty}</strong> {item.unit}
              {item.priority && (
                <> · <Priority p={item.priority} /></>
              )}
            </div>
          </div>
          <span className={`cdc-badge ${COMPRAS_STATUS_META_SL[item.status].badge}`}>{COMPRAS_STATUS_META_SL[item.status].label}</span>
        </div>

        {item.note && (
          <div style={{ fontSize: 12.5, color: "var(--cdc-ink-2)", marginTop: 6, lineHeight: 1.4 }}>{item.note}</div>
        )}

        {item.supplier && !hideSupplier && (
          <div style={{ fontSize: 12, color: "var(--cdc-ink-3)", marginTop: 4, display: "inline-flex", alignItems: "center", gap: 4 }}>
            <I.MapPin2 size={12} /> {item.supplier}
          </div>
        )}

        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8, marginTop: 8 }}>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11, color: "var(--cdc-ink-3)" }}>
            <Avatar id={item.addedBy} size="sm" />
            <span>{fmtShortDate(item.addedOn)}</span>
          </div>
          <div style={{ display: "flex", gap: 4 }}>
            {canEdit && (
              <button className="cdc-iconbtn" onClick={onEdit} title="Editar"><I.Edit size={13} /></button>
            )}
            {canEdit && (
              <button className="cdc-iconbtn" onClick={onRemove} title="Eliminar"><I.Trash size={13} /></button>
            )}
          </div>
        </div>

        {canManageStatus && item.status === "pendiente" && (
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6, marginTop: 8, paddingTop: 8, borderTop: "1px dashed var(--cdc-border-soft)" }}>
            <button
              onClick={() => onStatusChange("entregado")}
              style={{
                padding: "9px 8px", borderRadius: 10, border: 0,
                background: "var(--cdc-done-bg)", color: "var(--cdc-done)",
                fontWeight: 700, fontSize: 12.5, display: "inline-flex",
                alignItems: "center", justifyContent: "center", gap: 6, cursor: "pointer",
              }}
            >
              <I.Check size={13} stroke={2.4} /> Comprado
            </button>
            <button
              onClick={() => onStatusChange("no_encontrado")}
              style={{
                padding: "9px 8px", borderRadius: 10, border: 0,
                background: "var(--cdc-overdue-bg)", color: "var(--cdc-overdue)",
                fontWeight: 700, fontSize: 12.5, display: "inline-flex",
                alignItems: "center", justifyContent: "center", gap: 6, cursor: "pointer",
              }}
            >
              <I.X size={13} stroke={2.4} /> No encontrado
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

const ShoppingItemDrawer = ({ item, onClose, onSave, listLabel, listId, user, hideSupplier }) => {
  const [f, setF] = React.useState(item || {
    name: "", qty: 1, unit: "pza", supplier: "", priority: "media", note: "", photo: null,
    status: "pendiente", addedBy: user.id, addedOn: TODAY_ISO,
  });
  const fileInput = React.useRef(null);
  const u = (k, v) => setF(x => ({ ...x, [k]: v }));

  const handleFile = (e) => {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = () => u("photo", reader.result);
    reader.readAsDataURL(file);
  };

  return (
    <div className="cdc-overlay" onClick={onClose}>
      <div className="cdc-drawer" onClick={(e) => e.stopPropagation()}>
        <div className="cdc-drawer__head">
          <div className="cdc-drawer__title">{item ? "Editar artículo" : "Agregar a lista"} — {listLabel}</div>
          <button className="cdc-iconbtn" onClick={onClose}><I.X size={18} /></button>
        </div>
        <div className="cdc-drawer__body">
          {/* Photo */}
          <div className="cdc-field">
            <label>Foto del artículo</label>
            <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
              <button
                type="button"
                onClick={() => fileInput.current?.click()}
                style={{
                  width: 96, height: 96, borderRadius: 12, overflow: "hidden",
                  background: "var(--cdc-cream-100)", border: "1px dashed var(--cdc-cream-300)",
                  display: "flex", alignItems: "center", justifyContent: "center", padding: 0,
                  cursor: "pointer",
                }}
              >
                {f.photo ? (
                  <img src={f.photo} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                ) : (
                  <I.Camera size={28} stroke={1.4} style={{ color: "var(--cdc-ink-3)" }} />
                )}
              </button>
              <div style={{ flex: 1 }}>
                <input ref={fileInput} type="file" accept="image/*" onChange={handleFile} style={{ display: "none" }} />
                <button type="button" className="cdc-btn" onClick={() => fileInput.current?.click()}>
                  <I.Image size={14} /> {f.photo ? "Reemplazar foto" : "Subir foto"}
                </button>
                {f.photo && (
                  <button type="button" className="cdc-iconbtn" onClick={() => u("photo", null)} style={{ marginLeft: 6 }} title="Quitar foto">
                    <I.Trash size={14} />
                  </button>
                )}
                <div className="cdc-helper" style={{ marginTop: 6 }}>JPG / PNG, máx ~3 MB. Útil cuando se trata de marcas o productos específicos.</div>
              </div>
            </div>
          </div>

          <div className="cdc-field">
            <label>Artículo</label>
            <input className="cdc-input" autoFocus value={f.name} onChange={(e) => u("name", e.target.value)} placeholder="Ej. Toallas de playa bordadas Casa de Casas" />
          </div>

          <div className="cdc-row-3">
            <div className="cdc-field">
              <label>Cantidad</label>
              <input className="cdc-input" type="number" min="0" step="0.1" value={f.qty} onChange={(e) => u("qty", parseFloat(e.target.value) || 0)} />
            </div>
            <div className="cdc-field">
              <label>Unidad</label>
              <select className="cdc-select" value={f.unit} onChange={(e) => u("unit", e.target.value)}>
                <option value="pza">pza</option>
                <option value="kg">kg</option>
                <option value="L">L</option>
                <option value="btl">btl</option>
                <option value="caja">caja</option>
                <option value="ramo">ramo</option>
                <option value="set">set</option>
                <option value="rollo">rollo</option>
              </select>
            </div>
            <div className="cdc-field">
              <label>Prioridad</label>
              <select className="cdc-select" value={f.priority} onChange={(e) => u("priority", e.target.value)}>
                <option value="alta">Alta</option>
                <option value="media">Media</option>
                <option value="baja">Baja</option>
              </select>
            </div>
          </div>

          <div className="cdc-field">
            <label>Detalle / descripción</label>
            <textarea
              className="cdc-textarea"
              value={f.note}
              onChange={(e) => u("note", e.target.value)}
              placeholder="Marca, presentación, talla, color, código de barras, instrucciones…"
            />
          </div>

          {!hideSupplier && (
            <div className="cdc-field">
              <label>Dónde comprar</label>
              <input
                className="cdc-input"
                value={f.supplier}
                onChange={(e) => u("supplier", e.target.value)}
                placeholder="Costco Vallarta · Mercado Bucerías · Amazon MX · La Europea…"
              />
            </div>
          )}
        </div>

        <div className="cdc-panel__actions" style={{ position: "static", borderTop: "1px solid var(--cdc-border-soft)" }}>
          {item && (
            <button className="cdc-btn" style={{ marginRight: "auto", color: "var(--cdc-overdue)" }} onClick={() => { if (window.confirm("¿Eliminar?")) { onClose(); /* parent will handle delete */ } }}>
              <I.Trash size={14} /> Eliminar
            </button>
          )}
          <button className="cdc-btn" onClick={onClose}>Cancelar</button>
          <button
            className="cdc-btn cdc-btn--primary"
            disabled={!f.name.trim()}
            onClick={() => onSave({ ...f, name: f.name.trim() })}
          >
            <I.Check size={14} /> {item ? "Guardar cambios" : "Agregar"}
          </button>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { ShoppingListPanel, ShoppingItemCard, ShoppingItemDrawer, COMPRAS_STATUS_META_SL });
