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

function OverviewServiceRow({ s, onOpenService, showMember }) {
  return (
    <div className="req" onClick={() => onOpenService && onOpenService(s)}>
      <div className="ic"><Icon name={s.icon} size={22} /></div>
      <div className="body">
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10 }}>
          <div className="title">{s.title}</div>
          <span className={"chip chip-" + s.status}><span className="dot" />{s.statusText}</span>
        </div>
        {showMember && s.member && (
          <div style={{ display: "flex", alignItems: "center", gap: 5, marginTop: 2, marginBottom: 1 }}>
            <Icon name="user" size={11} />
            <span style={{ fontSize: 11.5, color: "var(--brand-burgundy)", fontWeight: 600 }}>{s.member}</span>
          </div>
        )}
        <div className="meta">{s.meta} · {s.since}</div>
        <div className="progress">
          <div className={"bar " + (s.status === "success" ? "bar-success" : s.status === "info" ? "bar-info" : "")}><span style={{ width: ((s.stage / s.total) * 100) + "%" }} /></div>
          <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, color: "var(--fg-3)", marginTop: 6 }}>
            <span>Stage {s.stage} of {s.total}</span>
            <span>{Math.round((s.stage / s.total) * 100)}%</span>
          </div>
        </div>
      </div>
      <div style={{ alignSelf: "center", color: "var(--fg-3)" }}><Icon name="chevron-right" size={18} /></div>
    </div>
  );
}

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

  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 filtered   = isOrg && memberFilter !== "all"
    ? engagements.filter(e => e.member === memberFilter)
    : engagements;

  const services       = filtered;
  const activeServices = filtered.filter(s => s.category === "active");

  const notifs = [];

  const renewals = engagements
    .filter(e => e.due && e.due !== "—" && e.category === "active")
    .map(e => {
      const daysLeft = Math.ceil((new Date(e.due) - Date.now()) / 86400000);
      return {
        t:      e.title,
        id:     e._id,
        exp:    e.due,
        days:   daysLeft > 0 ? daysLeft : 0,
        status: daysLeft < 21 ? "warning" : "info",
      };
    })
    .filter(r => r.days >= 0)
    .sort((a, b) => a.days - b.days);

  const today = new Date().toLocaleDateString("en-GB", { weekday: "long", day: "numeric", month: "long", year: "numeric" });
  const shortName = user.shortName || user.displayName || "there";

  return (
    <>
      {/* Hero */}
      <section className="hero">
        <div className="ring-bg"><RingArt size={520} opacity={0.14} /></div>
        <div className="ring-bg-2"><RingArt size={360} opacity={0.08} /></div>
        <div className="inner">
          <div className="eyebrow">{today}</div>
          <h1>Welcome back, {shortName}.</h1>
          {loading ? (
            <p>Loading your services…</p>
          ) : (
            <p>
              {activeServices.length > 0
                ? `You have ${activeServices.length} active service${activeServices.length !== 1 ? "s" : ""} with us. We're working on them — we'll update you as each stage progresses.`
                : "No active services at the moment. Request a new service anytime."}
            </p>
          )}
          <div style={{ display: "flex", gap: 10, marginTop: 22 }}>
            <button className="btn btn-light" onClick={onRequest}><Icon name="plus" size={14} stroke={2} />Request a new service</button>
            <button className="btn btn-light"><Icon name="upload" size={14} stroke={2} />Upload documents</button>
          </div>
        </div>
      </section>

      <div className="container">
        {/* Active services */}
        <section className="section">
          <div className="section-head">
            <div>
              <h2>Your active services</h2>
              <div style={{ color: "var(--fg-3)", fontSize: 13, marginTop: 2 }}>
                Every engagement we're working on for you, with live status.
              </div>
            </div>
            <a className="lnk">View history →</a>
          </div>

          {isOrg && <MemberFilter members={orgMembers} value={memberFilter} onChange={setMemberFilter} />}
          <div className="pcard" style={{ padding: 0 }}>
            {loading ? (
              <div style={{ textAlign: "center", padding: "40px 20px", color: "var(--fg-3)" }}>
                <Icon name="loader" size={24} />
                <div style={{ marginTop: 8, fontSize: 14 }}>Loading…</div>
              </div>
            ) : services.length === 0 ? (
              <div style={{ textAlign: "center", padding: "40px 20px", color: "var(--fg-3)" }}>
                <Icon name="inbox" size={28} />
                <div style={{ marginTop: 8, fontSize: 14 }}>No services yet. Request your first service above.</div>
              </div>
            ) : services.map(s => (
              <OverviewServiceRow key={s.id} s={s} onOpenService={onOpenService} showMember={isOrg} />
            ))}
          </div>
        </section>

        {/* Two-col: renewals + notifications */}
        <section className="section resp-two-col" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
          <div className="pcard pcard-pad">
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
              <Icon name="calendar-clock" size={18} />
              <h2 style={{ margin: 0, fontSize: 18 }}>Coming up</h2>
            </div>
            <div style={{ fontSize: 13, color: "var(--fg-3)", marginBottom: 14 }}>
              Due dates we're tracking on your behalf.
            </div>
            {renewals.length === 0 ? (
              <div style={{ padding: "16px 0", fontSize: 13, color: "var(--fg-3)" }}>No upcoming deadlines.</div>
            ) : renewals.map((r, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "10px 0", borderTop: i > 0 ? "1px solid var(--border-subtle)" : 0 }}>
                <div>
                  <div style={{ fontSize: 13.5, fontWeight: 500 }}>{r.t}</div>
                  <div style={{ fontSize: 11.5, color: "var(--fg-3)" }}>Due {r.exp}</div>
                </div>
                <span className={"chip chip-" + r.status}><span className="dot" />{r.days} days</span>
              </div>
            ))}
          </div>

          <div className="pcard">
            <div style={{ padding: "16px 20px 12px", borderBottom: "1px solid var(--border-subtle)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <Icon name="bell" size={18} />
                <h2 style={{ margin: 0, fontSize: 18 }}>Notifications</h2>
              </div>
            </div>
            <div style={{ padding: "24px 20px", fontSize: 13, color: "var(--fg-3)" }}>No new notifications.</div>
          </div>
        </section>
      </div>
    </>
  );
}

Object.assign(window, { OverviewPage });
