"use client";

import { useEffect, useState } from "react";
import { getItems, createItem, updateItem, type ItemRecord } from "@/lib/api";
import { useAuth } from "@/lib/auth";

export default function ItemsPage() {
  const { user } = useAuth();
  const [items, setItems] = useState<ItemRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [successMsg, setSuccessMsg] = useState<string | null>(null);

  // ── Create form state ──────────────────────────────────────────────────────
  const [showForm, setShowForm] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [form, setForm] = useState({
    itemCode: "", itemName: "", brand: "", barcode: "", countryOfOrigin: "",
    blend: "", grainType: "", varietyType: "", processType: "", unit: "",
  });
  const [formErrors, setFormErrors] = useState<Record<string, string>>({});

  // ── Edit (bag weight) modal state ──────────────────────────────────────────
  const [editItem, setEditItem] = useState<ItemRecord | null>(null);
  const [editBagWeight, setEditBagWeight] = useState("");
  const [editSaving, setEditSaving] = useState(false);
  const [editError, setEditError] = useState<string | null>(null);

  const isManager = user?.role === "store_manager" || user?.role === "super_admin";

  useEffect(() => { load(); }, []);

  async function load() {
    setLoading(true);
    try { setItems(await getItems()); }
    catch { setError("Failed to load items."); }
    finally { setLoading(false); }
  }

  // ── Create ─────────────────────────────────────────────────────────────────
  function validate() {
    const e: Record<string, string> = {};
    if (!form.itemCode.trim()) e.itemCode = "Item code is required";
    if (!form.itemName.trim()) e.itemName = "Item name is required";
    if (!form.brand.trim()) e.brand = "Brand is required";
    return e;
  }

  async function handleCreate(e: React.FormEvent) {
    e.preventDefault();
    const errs = validate();
    if (Object.keys(errs).length) { setFormErrors(errs); return; }
    setFormErrors({});
    setSubmitting(true);
    try {
      await createItem({
        itemCode: form.itemCode.trim(),
        itemName: form.itemName.trim(),
        brand: form.brand.trim(),
        barcode: form.barcode || undefined,
        countryOfOrigin: form.countryOfOrigin || undefined,
        blend: form.blend || undefined,
        grainType: form.grainType || undefined,
        varietyType: form.varietyType || undefined,
        processType: form.processType || undefined,
        unit: form.unit || undefined,
      });
      setSuccessMsg("Item created successfully.");
      setShowForm(false);
      setForm({ itemCode: "", itemName: "", brand: "", barcode: "", countryOfOrigin: "", blend: "", grainType: "", varietyType: "", processType: "", unit: "" });
      await load();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to create item.");
    } finally {
      setSubmitting(false);
    }
  }

  // ── Edit bag weight ────────────────────────────────────────────────────────
  function openEdit(item: ItemRecord) {
    setEditItem(item);
    setEditBagWeight(item.bagWeightKg != null ? String(item.bagWeightKg) : "");
    setEditError(null);
  }

  async function handleSaveBagWeight(e: React.FormEvent) {
    e.preventDefault();
    if (!editItem) return;

    const parsed = editBagWeight.trim() === "" ? null : Number(editBagWeight);
    if (editBagWeight.trim() !== "" && (isNaN(parsed as number) || (parsed as number) <= 0)) {
      setEditError("Enter a valid positive number (e.g. 50).");
      return;
    }

    setEditSaving(true);
    setEditError(null);
    try {
      // When bagWeightKg is set, also update unit string so it auto-calculates MT
      const unitStr = parsed != null ? `BAG/1x${parsed}kg` : null;
      await updateItem(editItem._id, { bagWeightKg: parsed ?? undefined, unit: unitStr ?? undefined });
      setSuccessMsg(`Bag weight updated for ${editItem.itemName ?? editItem.itemCode}.`);
      setEditItem(null);
      await load();
    } catch (err) {
      setEditError(err instanceof Error ? err.message : "Failed to update.");
    } finally {
      setEditSaving(false);
    }
  }

  return (
    <>
      <section className="hero">
        <div className="hero-grid">
          <div>
            <h2>Items Master</h2>
            <p>Manage the item catalogue. Items are used across stock transactions and strategic sheets.</p>
          </div>
          {isManager && (
            <div style={{ alignSelf: "center" }}>
              <button className="button" onClick={() => setShowForm(true)}>+ New Item</button>
            </div>
          )}
        </div>
      </section>

      <section className="section">
        {successMsg && (
          <div className="snackbar" style={{ background: "var(--brand-soft)", color: "var(--brand)", border: "1px solid rgba(59,91,219,0.2)", marginBottom: 18 }}>
            ✓ {successMsg}
            <button className="snackbar-close" onClick={() => setSuccessMsg(null)}>✕</button>
          </div>
        )}
        {error && (
          <div className="snackbar snackbar-error" style={{ marginBottom: 18 }}>
            {error}
            <button className="snackbar-close" onClick={() => setError(null)}>✕</button>
          </div>
        )}

        {loading && <p style={{ color: "var(--muted)" }}>Loading…</p>}

        {!loading && (
          <div className="card">
            <div className="stock-table-scroll">
              <table className="table stock-table">
                <thead>
                  <tr>
                    <th>Item Code</th>
                    <th>Item Name</th>
                    <th>Brand</th>
                    <th>Barcode</th>
                    <th>COO</th>
                    <th>Unit</th>
                    <th style={{ textAlign: "right" }}>Bag Weight (KG)</th>
                    <th>Blend</th>
                    <th>Grain Type</th>
                    <th>Var/Type</th>
                    <th>Process</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  {items.length === 0 && (
                    <tr><td colSpan={12} style={{ textAlign: "center", color: "var(--muted)", padding: 24 }}>No items yet.</td></tr>
                  )}
                  {items.map((item) => {
                    const missingWeight = item.bagWeightKg == null;
                    return (
                      <tr key={item._id}>
                        <td><strong>{item.itemCode}</strong></td>
                        <td>{item.itemName ?? item.description ?? "—"}</td>
                        <td>{item.brand ?? "—"}</td>
                        <td style={{ color: "var(--muted)" }}>{item.barcode ?? "—"}</td>
                        <td style={{ color: "var(--muted)" }}>{item.countryOfOrigin ?? "—"}</td>
                        <td style={{ color: "var(--muted)" }}>{item.unit ?? "—"}</td>
                        {/* Bag Weight — highlighted in amber when missing */}
                        <td style={{ textAlign: "right" }}>
                          {missingWeight ? (
                            <span style={{
                              display: "inline-flex", alignItems: "center", gap: 5,
                              padding: "3px 10px", borderRadius: 999,
                              background: "var(--warn-soft)", color: "var(--warn)",
                              fontSize: "0.78rem", fontWeight: 600,
                            }}>
                              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                                <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>
                                <line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/>
                              </svg>
                              Not set
                            </span>
                          ) : (
                            <span style={{ fontWeight: 700, color: "var(--ink)" }}>
                              {item.bagWeightKg} kg
                            </span>
                          )}
                        </td>
                        <td style={{ color: "var(--muted)" }}>{item.blend ?? "—"}</td>
                        <td style={{ color: "var(--muted)" }}>{item.grainType ?? "—"}</td>
                        <td style={{ color: "var(--muted)" }}>{item.varietyType ?? "—"}</td>
                        <td style={{ color: "var(--muted)" }}>{item.processType ?? "—"}</td>
                        {/* Edit button — always visible so anyone can set bag weight */}
                        <td>
                          <button
                            onClick={() => openEdit(item)}
                            style={{
                              display: "inline-flex", alignItems: "center", gap: 5,
                              padding: "5px 12px", borderRadius: 999,
                              border: missingWeight ? "1.5px solid var(--warn)" : "1.5px solid var(--line)",
                              background: missingWeight ? "var(--warn-soft)" : "#fff",
                              color: missingWeight ? "var(--warn)" : "var(--brand)",
                              fontSize: "0.78rem", fontWeight: 600, cursor: "pointer",
                              whiteSpace: "nowrap",
                            }}
                          >
                            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                              <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
                              <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
                            </svg>
                            {missingWeight ? "Set Weight" : "Edit Weight"}
                          </button>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        )}
      </section>

      {/* ── Edit Bag Weight Modal ─────────────────────────────────────────── */}
      {editItem && (
        <div className="doc-modal-backdrop" onClick={() => setEditItem(null)}>
          <div
            className="doc-modal"
            style={{ maxWidth: 440 }}
            onClick={(e) => e.stopPropagation()}
          >
            <div className="doc-modal-header">
              <div>
                <strong className="doc-modal-title">Set Bag Weight</strong>
                <span className="doc-modal-meta">
                  {editItem.itemName ?? editItem.itemCode} · {editItem.itemCode}
                </span>
              </div>
              <button className="doc-modal-close" onClick={() => setEditItem(null)}>✕</button>
            </div>

            <div className="doc-modal-body" style={{ padding: "22px 24px" }}>
              {/* Info box */}
              <div style={{
                padding: "12px 14px", borderRadius: 10, marginBottom: 20,
                background: "var(--brand-soft)", border: "1px solid rgba(59,91,219,0.18)",
                fontSize: "0.84rem", color: "var(--brand)", lineHeight: 1.5,
              }}>
                <strong>Why this matters:</strong> The bag weight is used to auto-calculate
                Total MT from bag counts. Once set, you won't need to enter MT manually.
                <br />
                <span style={{ opacity: 0.8 }}>
                  Example: 50 kg/bag → 1,000 bags = 50 MT
                </span>
              </div>

              <form onSubmit={handleSaveBagWeight}>
                <div className="form-field" style={{ marginBottom: 18 }}>
                  <label className="form-label">
                    Bag Weight (KG)
                    <span className="form-required">*</span>
                  </label>
                  <div style={{ position: "relative" }}>
                    <input
                      className="form-input"
                      type="number"
                      min="0.1"
                      step="0.1"
                      value={editBagWeight}
                      onChange={(e) => setEditBagWeight(e.target.value)}
                      placeholder="e.g. 50"
                      autoFocus
                      style={{ paddingRight: 48 }}
                    />
                    <span style={{
                      position: "absolute", right: 14, top: "50%",
                      transform: "translateY(-50%)",
                      color: "var(--muted)", fontSize: "0.84rem", fontWeight: 600,
                      pointerEvents: "none",
                    }}>
                      kg
                    </span>
                  </div>
                  {/* Live preview */}
                  {editBagWeight && Number(editBagWeight) > 0 && (
                    <p style={{ margin: "6px 0 0", fontSize: "0.8rem", color: "var(--brand)" }}>
                      Unit will be set to: <strong>BAG/1x{editBagWeight}kg</strong>
                      &nbsp;·&nbsp; 1,000 bags = <strong>{(Number(editBagWeight) * 1000 / 1000).toFixed(2)} MT</strong>
                    </p>
                  )}
                  {editError && (
                    <p style={{ color: "var(--danger)", fontSize: "0.78rem", margin: "6px 0 0" }}>
                      {editError}
                    </p>
                  )}
                </div>

                <div style={{ display: "flex", gap: 10 }}>
                  <button className="button" type="submit" disabled={editSaving}>
                    {editSaving ? "Saving…" : "Save Bag Weight"}
                  </button>
                  <button
                    className="button secondary"
                    type="button"
                    onClick={() => setEditItem(null)}
                  >
                    Cancel
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}

      {/* ── New Item Modal ────────────────────────────────────────────────── */}
      {showForm && (
        <div className="doc-modal-backdrop" onClick={() => setShowForm(false)}>
          <div className="doc-modal" style={{ maxWidth: 640 }} onClick={(e) => e.stopPropagation()}>
            <div className="doc-modal-header">
              <div>
                <strong className="doc-modal-title">New Item</strong>
                <span className="doc-modal-meta">Add a new item to the master catalogue</span>
              </div>
              <button className="doc-modal-close" onClick={() => setShowForm(false)}>✕</button>
            </div>
            <div className="doc-modal-body" style={{ padding: 22, overflowY: "auto" }}>
              <form onSubmit={handleCreate}>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
                  {([
                    ["itemCode", "Item Code", true],
                    ["itemName", "Item Name", true],
                    ["brand", "Brand", true],
                    ["barcode", "Barcode"],
                    ["countryOfOrigin", "Country of Origin"],
                    ["unit", "Unit (e.g. BAG/1x40kg)"],
                    ["blend", "Blend"],
                    ["grainType", "Grain Type"],
                    ["varietyType", "Variety/Type"],
                    ["processType", "Process Type"],
                  ] as [keyof typeof form, string, boolean?][]).map(([key, label, req]) => (
                    <div className="form-field" key={key}>
                      <label className="form-label">
                        {label}
                        {req ? <span className="form-required">*</span> : <span className="form-optional">optional</span>}
                      </label>
                      <input
                        className="form-input"
                        type="text"
                        value={form[key]}
                        onChange={(e) => setForm((f) => ({ ...f, [key]: e.target.value }))}
                        placeholder={label}
                      />
                      {formErrors[key] && <p style={{ color: "var(--danger)", fontSize: "0.78rem", margin: 0 }}>{formErrors[key]}</p>}
                    </div>
                  ))}
                </div>
                <div style={{ display: "flex", gap: 10, marginTop: 18 }}>
                  <button className="button" type="submit" disabled={submitting}>
                    {submitting ? "Creating…" : "Create Item"}
                  </button>
                  <button className="button secondary" type="button" onClick={() => setShowForm(false)}>Cancel</button>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
