/* global React, Icon, Chip, Button, Avatar, Pagination, AddCustomerModal, api */

const LIMIT = 20;

/* ── Customer drawer ─────────────────────────────────── */
function CustomerDrawer({ customer, onClose, onNewEng }) {
  return (
    <>
      <div className="scrim" onClick={onClose} />
      <aside className="drawer">
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "16px 22px", borderBottom: "1px solid var(--border-subtle)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <Avatar name={customer.name} />
            <div>
              <div style={{ fontWeight: 600, fontSize: 15 }}>{customer.name}</div>
              <div style={{ fontSize: 12, color: "var(--fg-3)", fontFamily: "var(--font-mono)" }}>{customer.eid}</div>
            </div>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>

        <div style={{ padding: 22, overflow: "auto", flex: 1 }}>
          <div className="eyebrow" style={{ fontSize: 10, marginBottom: 10 }}>Contact</div>
          <div style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: "8px 16px", fontSize: 13, marginBottom: 22 }}>
            <span style={{ color: "var(--fg-3)" }}>Phone</span>
            <span style={{ fontFamily: "var(--font-mono)" }}>{customer.phone || "—"}</span>
            <span style={{ color: "var(--fg-3)" }}>Email</span>
            <span>{customer.email || "—"}</span>
            <span style={{ color: "var(--fg-3)" }}>Nationality</span>
            <span>{customer.nationality}</span>
            <span style={{ color: "var(--fg-3)" }}>Customer since</span>
            <span>{customer.joined}</span>
          </div>

          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
            <div className="eyebrow" style={{ fontSize: 10 }}>Engagements</div>
            <button className="btn btn-ghost btn-sm" style={{ fontSize: 12 }} onClick={() => onNewEng(customer)}>
              <Icon name="plus" size={13} /> New
            </button>
          </div>
          <div style={{ color: "var(--fg-3)", fontSize: 13, padding: "12px 0" }}>No engagements on record.</div>

          <div className="eyebrow" style={{ fontSize: 10, marginBottom: 8 }}>Quick actions</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            <Button variant="secondary" icon="message-circle" size="sm">WhatsApp</Button>
            <Button variant="secondary" icon="mail" size="sm">Email</Button>
            <Button variant="secondary" icon="phone" size="sm">Log call</Button>
          </div>
        </div>

        <div style={{ padding: 16, borderTop: "1px solid var(--border-subtle)", display: "flex", gap: 8, justifyContent: "flex-end", background: "var(--ink-50)" }}>
          <Button variant="secondary" onClick={onClose}>Close</Button>
          <Button icon="briefcase" onClick={() => onNewEng(customer)}>New engagement</Button>
        </div>
      </aside>
    </>
  );
}

/* ── Main page ───────────────────────────────────────── */
function CustomersPage({ onNewEng }) {
  const [customers,     setCustomers]     = React.useState([]);
  const [loading,       setLoading]       = React.useState(true);
  const [searchInput,   setSearchInput]   = React.useState("");
  const [search,        setSearch]        = React.useState("");
  const [statusFilter,  setStatusFilter]  = React.useState("all");
  const [typeFilter,    setTypeFilter]    = React.useState("all");
  const [page,          setPage]          = React.useState(1);
  const [pages,         setPages]         = React.useState(1);
  const [total,         setTotal]         = React.useState(0);
  const [counts,        setCounts]        = React.useState({ active: 0, inactive: 0, individual: 0, organisation: 0 });
  const [openCustomer,  setOpenCustomer]  = React.useState(null);
  const [showAdd,       setShowAdd]       = React.useState(false);
  const [refreshKey,    setRefreshKey]    = React.useState(0);

  /* Debounce search — 400 ms */
  React.useEffect(() => {
    const t = setTimeout(() => { setSearch(searchInput); setPage(1); }, 400);
    return () => clearTimeout(t);
  }, [searchInput]);

  /* Fetch whenever filters / page / refreshKey change */
  React.useEffect(() => {
    setLoading(true);
    const params = new URLSearchParams({ page, limit: LIMIT });
    if (statusFilter !== "all") params.set("status", statusFilter);
    if (typeFilter   !== "all") params.set("type",   typeFilter);
    if (search)                 params.set("q",      search);
    api.get("/customers?" + params.toString())
      .then(res => {
        setCustomers((res.data || []).map(api.map.customer));
        setTotal(res.total  || 0);
        setPages(res.pages  || 1);
        if (res.counts) setCounts(res.counts);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [statusFilter, typeFilter, search, page, refreshKey]);

  function handleStatusChange(val) { setStatusFilter(val); setPage(1); }
  function handleTypeChange(val)   { setTypeFilter(val);   setPage(1); }

  function handleAdd(newCustomer) {
    setShowAdd(false);
    setStatusFilter("all");
    setTypeFilter("all");
    setSearchInput("");
    setSearch("");
    setPage(1);
    setRefreshKey(k => k + 1);
  }

  return (
    <>
    <div className="page">
      <div className="page-head">
        <div>
          <div className="eyebrow">Directory</div>
          <h1 className="page-title">Customers</h1>
          <div className="page-sub">
            {total} customers &nbsp;·&nbsp; {counts.active} active &nbsp;·&nbsp;
            {counts.individual} individuals &nbsp;·&nbsp; {counts.organisation} organisations
          </div>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <Button variant="secondary" icon="download">Export</Button>
          <Button variant="secondary" icon="briefcase" onClick={() => onNewEng && onNewEng(null)}>New engagement</Button>
          <Button icon="user-plus" onClick={() => setShowAdd(true)}>Register customer</Button>
        </div>
      </div>

      {/* Search + filter bar */}
      <div style={{ display: "flex", gap: 10, marginBottom: 16, alignItems: "center", flexWrap: "wrap" }}>

        {/* Search */}
        <div style={{ display: "flex", alignItems: "center", gap: 8, background: "#fff", border: "1px solid var(--border-subtle)", borderRadius: 6, padding: "7px 12px", flex: 1, maxWidth: 360 }}>
          <Icon name="search" size={15} />
          <input
            placeholder="Search by name, phone, Emirates ID…"
            value={searchInput}
            onChange={e => setSearchInput(e.target.value)}
            style={{ border: 0, outline: "none", fontFamily: "inherit", fontSize: 13.5, flex: 1, background: "transparent", color: "var(--fg-1)" }}
          />
          {searchInput && (
            <button onClick={() => { setSearchInput(""); setSearch(""); setPage(1); }}
              style={{ border: 0, background: "transparent", cursor: "pointer", color: "var(--fg-3)", padding: 0, display: "flex" }}>
              <Icon name="x" size={14} />
            </button>
          )}
        </div>

        {/* Status filter */}
        <div style={{ display: "flex", gap: 4 }}>
          {[
            { val: "all",      label: "All",      count: total               },
            { val: "active",   label: "Active",   count: counts.active       },
            { val: "inactive", label: "Inactive", count: counts.inactive     },
          ].map(({ val, label, count }) => (
            <button key={val} onClick={() => handleStatusChange(val)}
              style={{ padding: "7px 14px", borderRadius: 6, border: "1px solid", cursor: "pointer", fontSize: 13, fontFamily: "inherit", fontWeight: 500,
                background: statusFilter === val ? "var(--brand-burgundy)" : "#fff",
                color:      statusFilter === val ? "#fff" : "var(--fg-2)",
                borderColor:statusFilter === val ? "var(--brand-burgundy)" : "var(--border-strong)" }}>
              {label}
              {val !== "all" && <span style={{ marginLeft: 5, opacity: 0.8, fontSize: 11.5 }}>{count}</span>}
            </button>
          ))}
        </div>

        <div style={{ width: 1, height: 28, background: "var(--border-subtle)", flexShrink: 0 }} />

        {/* Type filter */}
        <div style={{ display: "flex", gap: 4 }}>
          {[
            { val: "all",          label: "All types"    },
            { val: "individual",   label: "Individual"   },
            { val: "organisation", label: "Organisation" },
          ].map(({ val, label }) => (
            <button key={val} onClick={() => handleTypeChange(val)}
              style={{ padding: "7px 14px", borderRadius: 6, border: "1px solid", cursor: "pointer", fontSize: 13, fontFamily: "inherit", fontWeight: 500,
                background: typeFilter === val ? "var(--plum-900)" : "#fff",
                color:      typeFilter === val ? "#fff" : "var(--fg-2)",
                borderColor:typeFilter === val ? "var(--plum-900)" : "var(--border-strong)" }}>
              {label}
            </button>
          ))}
        </div>
      </div>

      <div className="card" style={{ padding: 0 }}>
        <table className="tbl">
          <thead>
            <tr>
              <th>Customer</th>
              <th>Type</th>
              <th>Emirates ID / Licence</th>
              <th>Nationality</th>
              <th>Last service</th>
              <th style={{ textAlign: "center" }}>Engagements</th>
              <th>Joined</th>
              <th>Status</th>
              <th style={{ textAlign: "right" }}>Actions</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr><td colSpan="9" style={{ textAlign: "center", padding: "56px 0", color: "var(--fg-3)" }}>Loading…</td></tr>
            ) : customers.length === 0 ? (
              <tr><td colSpan="9" style={{ textAlign: "center", padding: "56px 0", color: "var(--fg-3)" }}>
                {search ? "No customers match your search." : "No customers found."}
              </td></tr>
            ) : customers.map(c => (
              <tr key={c.id} onClick={() => setOpenCustomer(c)}>
                <td>
                  <div className="av-row">
                    <Avatar name={c.name} />
                    <div>
                      <div className="nm">{c.name}</div>
                      <div className="sub" style={{ fontFamily: "var(--font-mono)", fontSize: 11.5 }}>{c.phone}</div>
                    </div>
                  </div>
                </td>
                <td><Chip kind={c.type === "organisation" ? "brand" : "default"}>{c.type === "organisation" ? "Organisation" : "Individual"}</Chip></td>
                <td className="cell-mono cell-muted">{c.eid}</td>
                <td className="cell-muted">{c.nationality}</td>
                <td style={{ fontSize: 13, color: "var(--fg-2)", maxWidth: 180 }}>{c.lastService}</td>
                <td style={{ textAlign: "center" }}><span style={{ fontWeight: 600, fontSize: 13.5 }}>{c.engagements}</span></td>
                <td className="cell-muted">{c.joined}</td>
                <td><Chip kind={c.status === "active" ? "success" : "default"}>{c.status.charAt(0).toUpperCase() + c.status.slice(1)}</Chip></td>
                <td style={{ textAlign: "right" }}>
                  <button className="btn btn-ghost btn-sm" onClick={e => { e.stopPropagation(); setOpenCustomer(c); }}>Open</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>

        <Pagination page={page} pages={pages} total={total} limit={LIMIT} onPage={setPage} />
      </div>
    </div>

    {openCustomer && (
      <CustomerDrawer
        customer={openCustomer}
        onClose={() => setOpenCustomer(null)}
        onNewEng={(c) => { setOpenCustomer(null); onNewEng && onNewEng(c); }}
      />
    )}

    {showAdd && (
      <AddCustomerModal
        onClose={() => setShowAdd(false)}
        onAdd={handleAdd}
      />
    )}
    </>
  );
}

Object.assign(window, { CustomersPage });
