/* global React, Icon, MemberFilter, portalApi */

function ServiceRow({ svc, onOpen, showMember }) {
  return (
    <div className="req" onClick={() => onOpen(svc)}>
      <div className="ic"><Icon name={svc.icon} size={22} /></div>
      <div className="body">
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10 }}>
          <div className="title">{svc.title}</div>
          <span className={"chip chip-" + svc.status} style={{ flexShrink: 0 }}>
            <span className="dot" />{svc.statusText}
          </span>
        </div>
        {showMember && svc.member && (
          <div style={{ display: "flex", alignItems: "center", gap: 5, marginTop: 2 }}>
            <Icon name="user" size={11} />
            <span style={{ fontSize: 11.5, color: "var(--brand-burgundy)", fontWeight: 600 }}>{svc.member}</span>
          </div>
        )}
        <div className="meta">{svc.meta} · Started {svc.started}</div>
        {svc.category === "active" && (
          <div className="progress">
            <div className={"bar " + (svc.status === "success" ? "bar-success" : svc.status === "info" ? "bar-info" : "")}>
              <span style={{ width: ((svc.stage / svc.total) * 100) + "%" }} />
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, color: "var(--fg-3)", marginTop: 5 }}>
              <span>Stage {svc.stage} of {svc.total}</span>
              <span>Due {svc.due}</span>
            </div>
          </div>
        )}
        {svc.category === "completed" && (
          <div style={{ display: "flex", alignItems: "center", gap: 16, marginTop: 6, fontSize: 12, color: "var(--fg-3)" }}>
            <span style={{ display: "flex", alignItems: "center", gap: 5 }}><Icon name="calendar" size={12} />Completed {svc.due}</span>
            <span style={{ display: "flex", alignItems: "center", gap: 5 }}><Icon name="wallet" size={12} />Paid {svc.paid}</span>
            <span style={{ display: "flex", alignItems: "center", gap: 5 }}><Icon name="user" size={12} />{svc.agent}</span>
          </div>
        )}
      </div>
      <div style={{ alignSelf: "center", color: "var(--fg-3)" }}><Icon name="chevron-right" size={18} /></div>
    </div>
  );
}

function MyServicesPage({ onOpenService, onRequest, user = {} }) {
  const [tab, setTab]             = React.useState("all");
  const [engagements, setEngagements] = React.useState([]);
  const [loading, setLoading]     = React.useState(true);
  const [memberFilter, setMemberFilter] = React.useState("all");
  const isOrg = user.type === "organisation";

  React.useEffect(() => {
    portalApi.get("/engagements")
      .then(res => setEngagements((res.data || []).map(portalApi.map.engagement)))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const orgMembers    = isOrg ? [...new Set(engagements.map(e => e.member).filter(Boolean))] : [];
  const memberFiltered = isOrg && memberFilter !== "all"
    ? engagements.filter(e => e.member === memberFilter)
    : engagements;

  const active    = memberFiltered.filter(s => s.category === "active");
  const completed = memberFiltered.filter(s => s.category === "completed");
  const shown     = tab === "active" ? active : tab === "completed" ? completed : memberFiltered;

  const tabs = [
    { id: "all",       label: "All services",  count: engagements.length },
    { id: "active",    label: "Active",         count: active.length },
    { id: "completed", label: "Completed",      count: completed.length },
  ];

  return (
    <div className="container" style={{ paddingTop: 32, paddingBottom: 64 }}>
      {/* Page header */}
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", marginBottom: 24 }}>
        <div>
          <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.18em", fontWeight: 600, color: "var(--brand-burgundy)", marginBottom: 4 }}>
            {isOrg ? "Organisation account" : "Your account"}
          </div>
          <h1 style={{ fontFamily: "var(--font-display)", fontSize: 34, fontWeight: 600, letterSpacing: "-0.02em", margin: 0 }}>
            {isOrg ? "All services" : "My services"}
          </h1>
          <div style={{ fontSize: 14, color: "var(--fg-3)", marginTop: 4 }}>
            {active.length} active &nbsp;·&nbsp; {completed.length} completed
          </div>
        </div>
        <button className="btn btn-primary" onClick={onRequest}>
          <Icon name="plus" size={14} stroke={2} />Request a service
        </button>
      </div>

      {/* Summary strip */}
      <div className="resp-grid-3" style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14, marginBottom: 28 }}>
        {[
          { label: "Active services",    value: active.length,    icon: "loader",       color: "var(--info-700)" },
          { label: "Completed services", value: completed.length, icon: "check-circle", color: "var(--success-700)" },
          { label: "Total services",     value: engagements.length, icon: "wallet",     color: "var(--brand-burgundy)" },
        ].map((k, i) => (
          <div key={i} className="pcard pcard-pad" style={{ display: "flex", gap: 14, alignItems: "center" }}>
            <div style={{ width: 40, height: 40, borderRadius: 10, background: "var(--plum-50)", color: k.color, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
              <Icon name={k.icon} size={20} />
            </div>
            <div>
              <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: "-0.02em" }}>{k.value}</div>
              <div style={{ fontSize: 12, color: "var(--fg-3)" }}>{k.label}</div>
            </div>
          </div>
        ))}
      </div>

      {isOrg && <MemberFilter members={orgMembers} value={memberFilter} onChange={(m) => { setMemberFilter(m); setTab("all"); }} />}

      {/* Tabs */}
      <div style={{ display: "flex", gap: 4, borderBottom: "1px solid var(--border-subtle)", marginBottom: 16 }}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            background: "transparent", border: 0, padding: "10px 16px", cursor: "pointer",
            fontSize: 13.5, fontFamily: "inherit", fontWeight: tab === t.id ? 600 : 500,
            color: tab === t.id ? "var(--brand-burgundy)" : "var(--fg-2)",
            borderBottom: tab === t.id ? "2px solid var(--brand-burgundy)" : "2px solid transparent",
            marginBottom: -1,
          }}>
            {t.label}
            <span style={{ marginLeft: 6, fontSize: 12, color: "var(--fg-3)" }}>{t.count}</span>
          </button>
        ))}
      </div>

      {/* Active services */}
      {(tab === "all" || tab === "active") && active.length > 0 && (
        <div style={{ marginBottom: 28 }}>
          {tab === "all" && (
            <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.14em", fontWeight: 600, color: "var(--fg-3)", marginBottom: 10 }}>
              Active
            </div>
          )}
          <div className="pcard" style={{ padding: 0 }}>
            {active.map(s => <ServiceRow key={s.id} svc={s} onOpen={onOpenService} showMember={isOrg} />)}
          </div>
        </div>
      )}

      {/* Completed services */}
      {(tab === "all" || tab === "completed") && completed.length > 0 && (
        <div>
          {tab === "all" && (
            <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.14em", fontWeight: 600, color: "var(--fg-3)", marginBottom: 10 }}>
              Completed
            </div>
          )}
          <div className="pcard" style={{ padding: 0 }}>
            {completed.map(s => <ServiceRow key={s.id} svc={s} onOpen={onOpenService} showMember={isOrg} />)}
          </div>
        </div>
      )}

      {shown.length === 0 && (
        <div className="pcard pcard-pad" style={{ textAlign: "center", padding: "56px 20px", color: "var(--fg-3)" }}>
          <Icon name="inbox" size={32} />
          <div style={{ marginTop: 10, fontSize: 15, fontWeight: 500, color: "var(--fg-2)" }}>No services yet</div>
          <div style={{ fontSize: 13, marginTop: 4 }}>Request your first service and we'll handle the rest.</div>
          <button className="btn btn-primary" style={{ marginTop: 16 }} onClick={onRequest}>
            <Icon name="plus" size={14} />Request a service
          </button>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { MyServicesPage });
