const { useState, useEffect, useMemo, useRef } = React;

// ---- design tokens ----
const BG = "#EDEBE3";
const PAPER = "#FBFAF7";
const INK = "#22261F";
const MUTED = "#7A7B6E";
const BORDER = "#DAD5C6";
const STEEL = "#2C5F8A";
const RUST = "#C1541C";
const DISPLAY_FONT = "'Space Grotesk', sans-serif";
const MONO_FONT = "'IBM Plex Mono', monospace";

const currency = (n) =>
  new Intl.NumberFormat("vi-VN", { style: "currency", currency: "VND", maximumFractionDigits: 0 }).format(n || 0);

const fmtDate = (d) => {
  if (!d) return "—";
  const dt = new Date(d);
  if (isNaN(dt)) return d;
  return dt.toLocaleDateString("vi-VN");
};

const emptyForm = { id: null, ten: "", ma: "", hinhAnh: "", moTa: "", ngayMua: "", boPhan: "", nguoiQuanLy: "", giaTri: "" };

async function api(path, options = {}) {
  const res = await fetch(path, {
    credentials: "include",
    headers: { "Content-Type": "application/json" },
    ...options,
  });
  const data = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(data.error || "Có lỗi xảy ra.");
  return data;
}

// ---------- Login screen ----------
function LoginScreen({ onLogin, error }) {
  const btnRef = useRef(null);

  useEffect(() => {
    if (!window.google || !window.__GOOGLE_CLIENT_ID__) return;
    window.google.accounts.id.initialize({
      client_id: window.__GOOGLE_CLIENT_ID__,
      callback: (resp) => onLogin(resp.credential),
    });
    window.google.accounts.id.renderButton(btnRef.current, {
      theme: "outline",
      size: "large",
      shape: "pill",
      text: "signin_with",
      width: 260,
    });
  }, [onLogin]);

  return (
    <div style={{ minHeight: "100vh", background: BG, display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}>
      <div style={{ background: PAPER, borderRadius: 14, padding: 32, maxWidth: 380, width: "100%", textAlign: "center", boxShadow: "0 20px 50px rgba(0,0,0,0.12)" }}>
        <img src="/logo.png" alt="Indruino" style={{ height: 44, margin: "0 auto 20px", display: "block" }} />
        <h2 style={{ margin: "0 0 6px", fontFamily: DISPLAY_FONT, fontSize: 20, color: INK }}>Kho dụng cụ kỹ thuật</h2>
        <p style={{ margin: "0 0 24px", fontSize: 13.5, color: MUTED }}>Đăng nhập bằng tài khoản Google công ty để tiếp tục.</p>
        <div ref={btnRef} style={{ display: "flex", justifyContent: "center" }} />
        {error && <div style={{ marginTop: 16, fontSize: 13, color: RUST }}>{error}</div>}
      </div>
    </div>
  );
}

// ---------- Small building blocks ----------
function Field({ label, children, full }) {
  return (
    <div style={{ gridColumn: full ? "1 / -1" : "auto", display: "flex", flexDirection: "column", gap: 5 }}>
      <label style={{ fontSize: 12, color: MUTED, fontWeight: 600 }}>{label}</label>
      {children}
    </div>
  );
}

function Row({ label }) {
  return <div style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{label}</div>;
}

const inputBase = { border: `1px solid ${BORDER}`, background: PAPER, borderRadius: 8, padding: "9px 12px", fontSize: 13.5, color: INK, outline: "none", width: "100%" };
const btnPrimary = { display: "inline-flex", alignItems: "center", gap: 7, background: STEEL, color: "#fff", border: "none", borderRadius: 8, padding: "10px 16px", fontSize: 13.5, fontWeight: 600, cursor: "pointer" };
const btnGhost = { background: "transparent", border: `1px solid ${BORDER}`, color: INK, borderRadius: 8, padding: "9px 16px", fontSize: 13.5, fontWeight: 600, cursor: "pointer" };
const iconBtn = { border: "none", background: "transparent", color: MUTED, cursor: "pointer", padding: 5, borderRadius: 6, display: "flex", alignItems: "center" };
const card = { background: PAPER, border: `1px solid ${BORDER}`, borderRadius: 12, overflow: "hidden" };
const overlay = { position: "fixed", inset: 0, background: "rgba(20,22,17,0.45)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20, zIndex: 50 };
const modalBox = { background: PAPER, borderRadius: 14, padding: 24, width: "100%", maxWidth: 520, maxHeight: "88vh", overflowY: "auto", boxShadow: "0 20px 50px rgba(0,0,0,0.25)" };

function resizeImageFile(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (ev) => {
      const img = new Image();
      img.onload = () => {
        const maxDim = 900;
        let { width, height } = img;
        if (width > maxDim || height > maxDim) {
          const scale = maxDim / Math.max(width, height);
          width = Math.round(width * scale);
          height = Math.round(height * scale);
        }
        const canvas = document.createElement("canvas");
        canvas.width = width;
        canvas.height = height;
        canvas.getContext("2d").drawImage(img, 0, 0, width, height);
        resolve(canvas.toDataURL("image/jpeg", 0.82));
      };
      img.onerror = reject;
      img.src = ev.target.result;
    };
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}

// ---------- Main app ----------
function App() {
  const [user, setUser] = useState(undefined); // undefined = chưa biết, null = chưa đăng nhập
  const [loginError, setLoginError] = useState("");
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(true);
  const [query, setQuery] = useState("");
  const [deptFilter, setDeptFilter] = useState("Tất cả");
  const [modalOpen, setModalOpen] = useState(false);
  const [form, setForm] = useState(emptyForm);
  const [confirmDelete, setConfirmDelete] = useState(null);
  const [actionError, setActionError] = useState("");
  const [imgBroken, setImgBroken] = useState({});
  const [uploading, setUploading] = useState(false);

  useEffect(() => {
    api("/api/auth/me")
      .then((d) => setUser(d.user))
      .catch(() => setUser(null));
  }, []);

  useEffect(() => {
    if (!user) return;
    setLoading(true);
    api("/api/equipment")
      .then((d) => setItems(d.items))
      .catch((e) => setActionError(e.message))
      .finally(() => setLoading(false));
  }, [user]);

  const handleGoogleLogin = async (credential) => {
    setLoginError("");
    try {
      const d = await api("/api/auth/google", { method: "POST", body: JSON.stringify({ credential }) });
      setUser(d.user);
    } catch (e) {
      setLoginError(e.message);
    }
  };

  const handleLogout = async () => {
    await api("/api/auth/logout", { method: "POST" }).catch(() => {});
    setUser(null);
    setItems([]);
  };

  const departments = useMemo(() => {
    const set = new Set(items.map((i) => i.boPhan).filter(Boolean));
    return ["Tất cả", ...Array.from(set).sort()];
  }, [items]);

  const filtered = useMemo(() => {
    return items.filter((i) => {
      const matchesQuery = !query || [i.ten, i.ma, i.moTa, i.nguoiQuanLy, i.boPhan].join(" ").toLowerCase().includes(query.toLowerCase());
      const matchesDept = deptFilter === "Tất cả" || i.boPhan === deptFilter;
      return matchesQuery && matchesDept;
    });
  }, [items, query, deptFilter]);

  const totalValue = useMemo(() => items.reduce((s, i) => s + (Number(i.giaTri) || 0), 0), [items]);

  const exportExcel = () => {
    const rows = filtered.map((i) => ({
      "Mã dụng cụ": i.ma || "",
      "Tên thiết bị / dụng cụ": i.ten || "",
      "Mô tả": i.moTa || "",
      "Ngày mua": i.ngayMua ? fmtDate(i.ngayMua) : "",
      "Bộ phận giữ": i.boPhan || "",
      "Người đang quản lý": i.nguoiQuanLy || "",
      "Giá trị (VNĐ)": Number(i.giaTri) || 0,
    }));
    const worksheet = XLSX.utils.json_to_sheet(rows);
    worksheet["!cols"] = [{ wch: 14 }, { wch: 28 }, { wch: 36 }, { wch: 13 }, { wch: 20 }, { wch: 20 }, { wch: 16 }];
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, "Dụng cụ");
    const today = new Date().toISOString().slice(0, 10);
    XLSX.writeFile(workbook, `kho-dung-cu-${today}.xlsx`);
  };

  const openAdd = () => { setForm(emptyForm); setModalOpen(true); };
  const openEdit = (item) => { setForm({ ...item, giaTri: item.giaTri ? String(item.giaTri) : "" }); setModalOpen(true); };
  const closeModal = () => { setModalOpen(false); setForm(emptyForm); };

  const handleImageUpload = async (e) => {
    const file = e.target.files && e.target.files[0];
    e.target.value = "";
    if (!file) return;
    if (!file.type.startsWith("image/")) { setActionError("Vui lòng chọn một tệp hình ảnh."); return; }
    setUploading(true);
    try {
      const dataUrl = await resizeImageFile(file);
      setForm((f) => ({ ...f, hinhAnh: dataUrl }));
    } catch (e) {
      setActionError("Không đọc được ảnh này.");
    } finally {
      setUploading(false);
    }
  };

  const submitForm = async (e) => {
    e.preventDefault();
    if (!form.ten.trim()) return;
    setActionError("");
    const payload = { ...form, giaTri: Number(form.giaTri) || 0 };
    try {
      if (form.id) {
        const d = await api(`/api/equipment/${form.id}`, { method: "PUT", body: JSON.stringify(payload) });
        setItems((prev) => prev.map((i) => (i.id === form.id ? d.item : i)));
      } else {
        const d = await api("/api/equipment", { method: "POST", body: JSON.stringify(payload) });
        setItems((prev) => [d.item, ...prev]);
      }
      closeModal();
    } catch (e) {
      setActionError(e.message);
    }
  };

  const doDelete = async (id) => {
    try {
      await api(`/api/equipment/${id}`, { method: "DELETE" });
      setItems((prev) => prev.filter((i) => i.id !== id));
    } catch (e) {
      setActionError(e.message);
    } finally {
      setConfirmDelete(null);
    }
  };

  if (user === undefined) {
    return <div style={{ minHeight: "100vh", background: BG, display: "flex", alignItems: "center", justifyContent: "center", color: MUTED }}>Đang tải…</div>;
  }
  if (user === null) {
    return <LoginScreen onLogin={handleGoogleLogin} error={loginError} />;
  }

  const initials = (user.name || "")
    .split(" ").filter(Boolean).slice(-2).map((w) => w[0]).join("").toUpperCase();

  return (
    <div style={{ minHeight: "100vh", background: BG, color: INK }}>
      <header style={{ borderBottom: `1px solid ${BORDER}`, background: PAPER }}>
        <div style={{ maxWidth: 1180, margin: "0 auto", padding: "28px 24px 22px" }}>
          <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", flexWrap: "wrap", gap: 16 }}>
            <div>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}>
                <img src="/logo.png" alt="Indruino" style={{ height: 36 }} />
                <h1 style={{ fontFamily: DISPLAY_FONT, fontSize: 26, fontWeight: 700, margin: 0, letterSpacing: "-0.01em" }}>Kho dụng cụ kỹ thuật</h1>
              </div>
              <p style={{ margin: 0, color: MUTED, fontSize: 14 }}>{items.length} dụng cụ · tổng giá trị {currency(totalValue)}</p>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                {user.picture ? (
                  <img src={user.picture} alt="" style={{ width: 30, height: 30, borderRadius: "50%" }} />
                ) : (
                  <div style={{ width: 30, height: 30, borderRadius: "50%", background: STEEL, color: "#fff", fontSize: 12, fontWeight: 700, display: "flex", alignItems: "center", justifyContent: "center" }}>{initials || "?"}</div>
                )}
                <div style={{ lineHeight: 1.25 }}>
                  <div style={{ fontSize: 13, fontWeight: 600 }}>{user.name}</div>
                  <div style={{ fontSize: 11.5, color: MUTED }}>{user.email}</div>
                </div>
              </div>
              <button onClick={handleLogout} style={btnGhost}>Đăng xuất</button>
              <button onClick={exportExcel} style={btnGhost} disabled={filtered.length === 0}>Xuất Excel</button>
              <button onClick={openAdd} style={btnPrimary}>+ Thêm dụng cụ</button>
            </div>
          </div>
        </div>
      </header>

      <div style={{ maxWidth: 1180, margin: "0 auto", padding: "20px 24px 0" }}>
        <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
          <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Tìm theo tên, mã, người quản lý..." style={{ ...inputBase, flex: "1 1 260px" }} />
          <select value={deptFilter} onChange={(e) => setDeptFilter(e.target.value)} style={{ ...inputBase, minWidth: 190, width: "auto" }}>
            {departments.map((d) => <option key={d} value={d}>{d}</option>)}
          </select>
        </div>
      </div>

      {actionError && (
        <div style={{ maxWidth: 1180, margin: "12px auto 0", padding: "0 24px" }}>
          <div style={{ background: "#FCE9E4", border: `1px solid ${RUST}`, color: RUST, borderRadius: 8, padding: "10px 14px", fontSize: 13 }}>{actionError}</div>
        </div>
      )}

      <main style={{ maxWidth: 1180, margin: "0 auto", padding: "20px 24px 60px" }}>
        {loading ? (
          <div style={{ color: MUTED, padding: "60px 0", textAlign: "center" }}>Đang tải dữ liệu…</div>
        ) : filtered.length === 0 ? (
          <div style={{ textAlign: "center", padding: "70px 20px", color: MUTED, border: `1px dashed ${BORDER}`, borderRadius: 12, background: PAPER }}>
            {items.length === 0 ? "Chưa có dụng cụ nào. Thêm dụng cụ đầu tiên vào kho." : "Không tìm thấy kết quả phù hợp."}
          </div>
        ) : (
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(270px, 1fr))", gap: 16 }}>
            {filtered.map((item) => (
              <div key={item.id} style={card}>
                <div style={{ height: 150, background: "#EEEBE1", position: "relative", overflow: "hidden" }}>
                  {item.hinhAnh && !imgBroken[item.id] ? (
                    <img src={item.hinhAnh} alt={item.ten} onError={() => setImgBroken((s) => ({ ...s, [item.id]: true }))} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                  ) : (
                    <div style={{ width: "100%", height: "100%", display: "flex", alignItems: "center", justifyContent: "center", color: "#B7B0A0", fontSize: 12 }}>Không có hình</div>
                  )}
                  {item.ma && <span style={{ position: "absolute", top: 10, left: 10, background: "rgba(31,36,33,0.82)", color: "#fff", fontSize: 11, padding: "3px 8px", borderRadius: 6, fontFamily: MONO_FONT }}>{item.ma}</span>}
                </div>
                <div style={{ padding: "14px 16px 16px" }}>
                  <div style={{ display: "flex", justifyContent: "space-between", gap: 8, alignItems: "flex-start" }}>
                    <h3 style={{ margin: 0, fontFamily: DISPLAY_FONT, fontSize: 16, lineHeight: 1.3 }}>{item.ten}</h3>
                    <div style={{ display: "flex", gap: 4, flexShrink: 0 }}>
                      <button onClick={() => openEdit(item)} style={iconBtn} title="Sửa">✎</button>
                      <button onClick={() => setConfirmDelete(item.id)} style={iconBtn} title="Xóa">🗑</button>
                    </div>
                  </div>
                  {item.moTa && <p style={{ margin: "6px 0 10px", fontSize: 13, color: MUTED, lineHeight: 1.45, display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden" }}>{item.moTa}</p>}
                  <div style={{ display: "flex", flexDirection: "column", gap: 6, fontSize: 12.5 }}>
                    <Row label={item.boPhan || "Chưa gán bộ phận"} />
                    <Row label={item.nguoiQuanLy || "Chưa gán người quản lý"} />
                    <Row label={`Mua ngày ${fmtDate(item.ngayMua)}`} />
                  </div>
                  <div style={{ marginTop: 12, paddingTop: 10, borderTop: `1px solid ${BORDER}`, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 6 }}>
                    <span style={{ fontFamily: MONO_FONT, fontWeight: 600, fontSize: 13.5, color: RUST }}>{currency(item.giaTri)}</span>
                    {item.capNhatBoi && <span style={{ fontSize: 10.5, color: MUTED }}>Cập nhật bởi {item.capNhatBoi}</span>}
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </main>

      {modalOpen && (
        <div style={overlay} onClick={closeModal}>
          <div style={modalBox} onClick={(e) => e.stopPropagation()}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 18 }}>
              <h2 style={{ margin: 0, fontFamily: DISPLAY_FONT, fontSize: 19 }}>{form.id ? "Sửa dụng cụ" : "Thêm dụng cụ"}</h2>
              <button onClick={closeModal} style={iconBtn}>✕</button>
            </div>
            <form onSubmit={submitForm}>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                <Field label="Tên thiết bị / dụng cụ *" full>
                  <input required style={inputBase} value={form.ten} onChange={(e) => setForm({ ...form, ten: e.target.value })} placeholder="VD: Máy khoan cầm tay Bosch" />
                </Field>
                <Field label="Mã dụng cụ">
                  <input style={inputBase} value={form.ma} onChange={(e) => setForm({ ...form, ma: e.target.value })} placeholder="TB-0001" />
                </Field>
                <Field label="Giá trị (VNĐ)">
                  <input
                    type="text"
                    inputMode="numeric"
                    style={inputBase}
                    value={form.giaTri ? Number(form.giaTri).toLocaleString("vi-VN") : ""}
                    onChange={(e) => setForm({ ...form, giaTri: e.target.value.replace(/\D/g, "") })}
                    placeholder="0"
                  />
                </Field>
                <Field label="Hình ảnh" full>
                  <div style={{ display: "flex", gap: 12, alignItems: "flex-start", flexWrap: "wrap" }}>
                    <div style={{ width: 84, height: 84, borderRadius: 8, border: `1px solid ${BORDER}`, background: "#EEEBE1", flexShrink: 0, overflow: "hidden", display: "flex", alignItems: "center", justifyContent: "center" }}>
                      {form.hinhAnh ? <img src={form.hinhAnh} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} /> : <span style={{ fontSize: 11, color: "#B7B0A0" }}>Không ảnh</span>}
                    </div>
                    <div style={{ flex: "1 1 220px", display: "flex", flexDirection: "column", gap: 8 }}>
                      <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                        <label style={{ ...btnGhost, display: "inline-flex", alignItems: "center", gap: 6, cursor: uploading ? "wait" : "pointer" }}>
                          {uploading ? "Đang xử lý…" : "Thêm ảnh từ thư viện"}
                          <input type="file" accept="image/*" onChange={handleImageUpload} style={{ display: "none" }} disabled={uploading} />
                        </label>
                        {form.hinhAnh && <button type="button" onClick={() => setForm({ ...form, hinhAnh: "" })} style={{ ...btnGhost, color: RUST }}>Xóa ảnh</button>}
                      </div>
                      <input style={inputBase} value={form.hinhAnh} onChange={(e) => setForm({ ...form, hinhAnh: e.target.value })} placeholder="hoặc dán link ảnh https://..." />
                    </div>
                  </div>
                </Field>
                <Field label="Mô tả" full>
                  <textarea rows={2} style={{ ...inputBase, resize: "vertical" }} value={form.moTa} onChange={(e) => setForm({ ...form, moTa: e.target.value })} placeholder="Công dụng, thông số, ghi chú..." />
                </Field>
                <Field label="Ngày mua">
                  <input type="date" style={inputBase} value={form.ngayMua} onChange={(e) => setForm({ ...form, ngayMua: e.target.value })} />
                </Field>
                <Field label="Bộ phận giữ">
                  <input style={inputBase} value={form.boPhan} onChange={(e) => setForm({ ...form, boPhan: e.target.value })} placeholder="VD: Bộ phận Cơ điện" />
                </Field>
                <Field label="Người đang quản lý" full>
                  <input style={inputBase} value={form.nguoiQuanLy} onChange={(e) => setForm({ ...form, nguoiQuanLy: e.target.value })} placeholder="Họ và tên" />
                </Field>
              </div>
              <div style={{ display: "flex", justifyContent: "flex-end", gap: 10, marginTop: 20 }}>
                <button type="button" onClick={closeModal} style={btnGhost}>Hủy</button>
                <button type="submit" style={btnPrimary}>{form.id ? "Lưu thay đổi" : "Thêm vào kho"}</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {confirmDelete && (
        <div style={overlay} onClick={() => setConfirmDelete(null)}>
          <div style={{ ...modalBox, maxWidth: 360 }} onClick={(e) => e.stopPropagation()}>
            <h3 style={{ margin: "0 0 8px", fontFamily: DISPLAY_FONT, fontSize: 17 }}>Xóa dụng cụ này?</h3>
            <p style={{ margin: "0 0 20px", fontSize: 13.5, color: MUTED }}>Hành động này không thể hoàn tác.</p>
            <div style={{ display: "flex", justifyContent: "flex-end", gap: 10 }}>
              <button onClick={() => setConfirmDelete(null)} style={btnGhost}>Hủy</button>
              <button onClick={() => doDelete(confirmDelete)} style={{ ...btnPrimary, background: RUST }}>Xóa</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
