// analytics.jsx — Doctor & clinic analytics wired to /api/analytics.

const { useState: useASt, useMemo: useAMemo, useEffect: useAEf } = React;

const PALETTE = [
  "var(--primary)",
  "var(--accent-success)",
  "var(--accent-warn)",
  "oklch(0.65 0.10 290)",
  "var(--accent-danger)",
  "oklch(0.55 0.10 220)",
  "oklch(0.55 0.10 30)",
];

function DeltaBadge({ delta, invert }) {
  if (delta === null || delta === undefined || isNaN(delta)) return null;
  const positive = invert ? delta < 0 : delta > 0;
  const neutral = delta === 0;
  const arrow = delta > 0 ? "↑" : delta < 0 ? "↓" : "—";
  const color = neutral ? "var(--ink-4)" : positive ? "oklch(0.40 0.13 155)" : "oklch(0.45 0.18 25)";
  const bg = neutral ? "var(--bg-sunk)" : positive ? "color-mix(in oklch, var(--accent-success) 12%, white)" : "color-mix(in oklch, var(--accent-danger) 12%, white)";
  return (
    <span style={{display: "inline-flex", alignItems: "center", gap: 3, fontSize: 11.5, fontWeight: 600, color, background: bg, borderRadius: 6, padding: "2px 7px"}}>
      {arrow} {Math.abs(delta)}%
    </span>
  );
}

function BarChart({ data, color = "var(--primary)", height = 160 }) {
  const t = window.MSStore.useT();
  const [hovered, setHovered] = useASt(null);
  const max = Math.max(...data.map(d => d.count), 1);
  const w = 520;
  const padX = 4;
  const barW = data.length ? Math.max(8, Math.floor((w - padX * 2) / data.length) - 6) : 0;

  if (!data.length) {
    return <div style={{padding: 24, textAlign: "center", color: "var(--ink-4)", fontSize: 13}}>{t("an.noData")}</div>;
  }

  return (
    <div style={{position: "relative", userSelect: "none"}}>
      <svg viewBox={`0 0 ${w} ${height + 28}`} style={{width: "100%", overflow: "visible"}}>
        {[0.25, 0.5, 0.75, 1].map(pct => {
          const y = height - pct * height + 4;
          return (
            <g key={pct}>
              <line x1={0} y1={y} x2={w} y2={y} stroke="var(--line)" strokeWidth="1" strokeDasharray="4 3"/>
              <text x={0} y={y - 4} fontSize="9" fill="var(--ink-5)" fontFamily="var(--font-ui)">{Math.round(pct * max)}</text>
            </g>
          );
        })}
        {data.map((d, i) => {
          const x = padX + i * ((w - padX * 2) / data.length) + 3;
          const barH = d.count === 0 ? 0 : Math.max(4, (d.count / max) * (height - 8));
          const y = height - barH + 4;
          const isHov = hovered === i;
          return (
            <g key={i} onMouseEnter={() => setHovered(i)} onMouseLeave={() => setHovered(null)}>
              <rect x={x} y={y} width={barW} height={barH} rx="4"
                fill={isHov ? "var(--primary-ink)" : color}
                opacity={d.count === 0 ? 0.15 : 1}
                style={{transition: "fill .1s"}}
              />
              {isHov && d.count > 0 && (
                <g>
                  <rect x={x - 4} y={y - 28} width={barW + 8} height={22} rx="5" fill="var(--ink)" opacity="0.88"/>
                  <text x={x + barW / 2} y={y - 13} fontSize="10.5" fill="white" textAnchor="middle" fontFamily="var(--font-ui)" fontWeight="600">{t("an.visitsCount", { n: d.count, plural: d.count === 1 ? "" : "s" })}</text>
                </g>
              )}
              <text x={x + barW / 2} y={height + 20} fontSize="10" fill="var(--ink-4)" textAnchor="middle" fontFamily="var(--font-ui)">{d.day}</text>
            </g>
          );
        })}
      </svg>
    </div>
  );
}

function DonutChart({ items }) {
  const t = window.MSStore.useT();
  const total = items.reduce((s, i) => s + i.count, 0);
  const r = 52, cx = 70, cy = 70, stroke = 22;
  const circ = 2 * Math.PI * r;

  if (total === 0) {
    return <div style={{padding: 24, textAlign: "center", color: "var(--ink-4)", fontSize: 13}}>{t("an.noData")}</div>;
  }

  let offset = 0;
  return (
    <div className="row" style={{gap: 20, alignItems: "center"}}>
      <svg width="140" height="140" viewBox="0 0 140 140" style={{flexShrink: 0}}>
        <circle cx={cx} cy={cy} r={r} fill="none" stroke="var(--bg-sunk)" strokeWidth={stroke}/>
        {items.map((item, i) => {
          const pct = item.count / total;
          const dash = pct * circ;
          const gap = circ - dash;
          const el = (
            <circle key={i} cx={cx} cy={cy} r={r}
              fill="none" stroke={item.color} strokeWidth={stroke}
              strokeDasharray={`${dash} ${gap}`}
              strokeDashoffset={-offset * circ} strokeLinecap="butt"
              style={{transform: "rotate(-90deg)", transformOrigin: `${cx}px ${cy}px`, transition: "stroke-dasharray .4s"}}
            />
          );
          offset += pct;
          return el;
        })}
        <text x={cx} y={cy - 6} textAnchor="middle" fontSize="22" fontWeight="600" fill="var(--ink)" fontFamily="var(--font-display)">{total}</text>
        <text x={cx} y={cy + 12} textAnchor="middle" fontSize="10" fill="var(--ink-4)" fontFamily="var(--font-ui)">{t("an.total")}</text>
      </svg>
      <div className="col" style={{gap: 6, flex: 1}}>
        {items.map(item => (
          <div key={item.label} className="row" style={{gap: 8}}>
            <span style={{width: 8, height: 8, borderRadius: 2, background: item.color, flexShrink: 0, marginTop: 1}}/>
            <span style={{flex: 1, fontSize: 12.5, color: "var(--ink-2)"}}>{item.label}</span>
            <span style={{fontSize: 12.5, fontWeight: 600, color: "var(--ink)"}}>{item.count}</span>
            <span style={{fontSize: 11, color: "var(--ink-4)", minWidth: 32, textAlign: "right"}}>{Math.round(item.count / total * 100)}%</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// Build the bar chart data given a range and the analytics payload's
// `sessions_per_day` (each entry: {day: "YYYY-MM-DD", count}).
function buildBars(range, sessionsPerDay, locale, t) {
  const byDay = {};
  for (const r of (sessionsPerDay || [])) byDay[r.day] = r.count;
  const today = new Date(); today.setHours(0, 0, 0, 0);
  const out = [];
  if (range === "week") {
    for (let i = 6; i >= 0; i--) {
      const d = new Date(today.getTime() - i * 86400000);
      const key = d.toISOString().slice(0, 10);
      out.push({ day: d.toLocaleDateString(locale, { weekday: "short" }), count: byDay[key] || 0 });
    }
  } else if (range === "month") {
    for (let w = 4; w >= 1; w--) {
      const start = new Date(today.getTime() - (w * 7 - 1) * 86400000);
      const end = new Date(start.getTime() + 6 * 86400000);
      let count = 0;
      for (let i = 0; i < 7; i++) {
        const d = new Date(start.getTime() + i * 86400000);
        count += byDay[d.toISOString().slice(0, 10)] || 0;
      }
      out.push({ day: t("an.weekShort", { n: 5 - w }), count });
    }
  } else { // quarter
    for (let m = 2; m >= 0; m--) {
      const monthStart = new Date(today.getFullYear(), today.getMonth() - m, 1);
      const monthEnd = new Date(today.getFullYear(), today.getMonth() - m + 1, 1);
      let count = 0;
      for (const k in byDay) {
        const d = new Date(k);
        if (!isNaN(d) && d >= monthStart && d < monthEnd) count += byDay[k];
      }
      out.push({ day: monthStart.toLocaleDateString(locale, { month: "short" }), count });
    }
  }
  return out;
}

function Analytics({ isAdmin }) {
  const store = window.MSStore.useStore();
  const t = window.MSStore.useT();
  const [lang] = window.MSStore.useLang();
  const [range, setRange] = useASt("week");

  useAEf(() => {
    if (!store.analytics && !(store.loading && store.loading.analytics)) {
      store.loadAnalytics();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const a = store.analytics || null;
  const isLoading = store.loading && store.loading.analytics;
  const error = store.errors && store.errors.analytics;

  const locale = lang === "es" ? "es-ES" : "en-US";
  const bars = useAMemo(() => buildBars(range, (a && a.sessions_per_day) || [], locale, t), [range, a, locale, t]);
  const totalForRange = bars.reduce((s, b) => s + b.count, 0);

  const diagnoses = (a && a.top_diagnoses) || [];
  const donutItems = diagnoses.slice(0, 6).map((d, i) => ({ label: d.name, count: d.count, color: PALETTE[i % PALETTE.length] }));

  const profile = store.profile;
  const account = store.activeAccount;
  const subtitle = isAdmin
    ? (account && account.name) ? t("an.clinicOverview", { clinic: account.name }) : t("an.clinicOverviewBlank")
    : t("an.yourPractice", { name: (profile && profile.name) ? profile.name.replace(/^Dr\.?\s+/i, "") : "—" });

  return (
    <div className="ms-page fade-in">
      {/* Header */}
      <div className="ms-page-head">
        <div>
          <h1 className="h1">{t("an.title")}</h1>
          <div style={{color: "var(--ink-3)", marginTop: 4, fontSize: 14}}>{subtitle}</div>
        </div>
        <div className="row" style={{gap: 8}}>
          <div className="ms-segmented">
            {[["week", t("common.week")], ["month", t("common.month")], ["quarter", t("common.quarter")]].map(([v, l]) => (
              <button key={v} className={range === v ? "is-active" : ""} onClick={() => setRange(v)}>{l}</button>
            ))}
          </div>
          <button className="btn btn-icon btn-sm" title={t("common.refresh")} onClick={() => store.loadAnalytics()}><Icon.Refresh size={14}/></button>
        </div>
      </div>

      {error && (
        <div className="card" style={{padding: 16, color: "var(--accent-danger)", fontSize: 13, marginBottom: 16}}>{error}</div>
      )}

      {/* Stat tiles */}
      <div className="ms-analytics-stats">
        {[
          { label: t("an.totalVisits"), value: totalForRange, sub: t("an.totalVisitsSub", { n: bars.length }), icon: <Icon.Patients size={16}/> },
          { label: t("an.avgDuration"), value: a ? `${a.avg_duration_minutes || 0} min` : "—", sub: t("an.avgDurationSub"), icon: <Icon.Clock size={16}/> },
          { label: t("an.visitsThisMonth"), value: a ? a.sessions_this_month || 0 : "—", sub: t("an.visitsThisMonthSub"), icon: <Icon.Calendar size={16}/> },
          { label: t("an.uniquePatients"), value: a ? a.total_patients || 0 : "—", sub: t("an.uniquePatientsSub"), icon: <Icon.User size={16}/> },
        ].map(stat => (
          <div key={stat.label} className="ms-stat">
            <div className="row" style={{gap: 6}}>
              <span className="ms-stat-label">{stat.label}</span>
              <span className="spacer"/>
              <span style={{color: "var(--ink-4)"}}>{stat.icon}</span>
            </div>
            <div className="ms-stat-value">{stat.value}</div>
            <div className="row" style={{gap: 6, marginTop: 6}}>
              <span className="ms-stat-sub">{stat.sub}</span>
            </div>
          </div>
        ))}
      </div>

      {isAdmin && (
        <div className="ms-analytics-prov-strip">
          {(store.providers || []).map(p => (
            <div key={p.id} className="ms-analytics-prov-chip" style={{borderColor: p.color + "33"}}>
              <span style={{width: 8, height: 8, borderRadius: "50%", background: p.color, flexShrink: 0, display: "inline-block"}}/>
              {p.name}
            </div>
          ))}
        </div>
      )}

      {/* Main chart + breakdown */}
      <div className="ms-analytics-grid">
        <div className="card">
          <div className="card-header">
            <span className="card-title">{t("an.visitVolume")}</span>
            <span className="dim" style={{fontSize: 12}}>
              {range === "week" ? t("an.daily") : range === "month" ? t("an.weekly") : t("an.monthly")}
            </span>
          </div>
          <div className="card-body" style={{paddingTop: 4}}>
            {isLoading && !a ? (
              <div style={{padding: 32, textAlign: "center", color: "var(--ink-4)", fontSize: 13}}>{t("an.loading")}</div>
            ) : (
              <BarChart data={bars} color="var(--primary)"/>
            )}
          </div>
        </div>

        <div className="card">
          <div className="card-header">
            <span className="card-title">{t("an.topDiagnoses")}</span>
            {a && <span className="dim" style={{fontSize: 12}}>{t("an.fromNotes")}</span>}
          </div>
          <div className="card-body" style={{paddingTop: 8}}>
            {isLoading && !a ? (
              <div style={{padding: 32, textAlign: "center", color: "var(--ink-4)", fontSize: 13}}>{t("an.loading")}</div>
            ) : donutItems.length === 0 ? (
              <div style={{padding: 32, textAlign: "center", color: "var(--ink-4)", fontSize: 13}}>{t("an.noDiagnoses")}</div>
            ) : (
              <DonutChart items={donutItems}/>
            )}
          </div>
        </div>
      </div>

      {/* Bottom: top medications + transcription accuracy */}
      <div className="ms-analytics-bottom">
        <div className="card">
          <div className="card-header">
            <span className="card-title">{t("an.topMeds")}</span>
            {a && <span className="dim" style={{fontSize: 12}}>{t("an.mostPrescribed")}</span>}
          </div>
          <div className="card-body" style={{paddingTop: 8}}>
            {a && a.top_medications && a.top_medications.length > 0 ? (
              <div className="col" style={{gap: 10}}>
                {a.top_medications.slice(0, 8).map((m, i) => {
                  const pct = a.top_medications[0] ? Math.round(m.count / a.top_medications[0].count * 100) : 0;
                  return (
                    <div key={m.name}>
                      <div className="row" style={{marginBottom: 4}}>
                        <span style={{fontSize: 13, color: "var(--ink-2)", flex: 1}}>{m.name}</span>
                        <span style={{fontWeight: 600, fontSize: 13}}>{m.count}</span>
                      </div>
                      <div style={{height: 6, borderRadius: 999, background: "var(--bg-sunk)", overflow: "hidden"}}>
                        <div style={{height: "100%", width: pct + "%", borderRadius: 999, background: "var(--primary)"}}/>
                      </div>
                    </div>
                  );
                })}
              </div>
            ) : (
              <div style={{padding: 32, textAlign: "center", color: "var(--ink-4)", fontSize: 13}}>{t("an.noMeds")}</div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

window.Analytics = Analytics;
