"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { TrendingUp, TrendingDown } from "lucide-react";
import { usePageHeader } from "@/presentation/hooks/use-page-header";
import { useT } from "@/shared/i18n/client";
import { ROUTES } from "@/shared/constants";
import StatsCard from "@/presentation/components/shared/stats-card";
import { Card, CardContent, CardHeader, CardTitle } from "@/presentation/components/ui/card";
import { Skeleton } from "@/presentation/components/ui/skeleton";
import { useHealthExecutive } from "./hooks/use-health-executive";
import { PeriodFilter, type PeriodState } from "./components/period-filter";
import { NeedsComputeBanner } from "./components/needs-compute-banner";
import { HealthGauge, DistributionDonut, TrendLine } from "./components/charts";
import { HBarList } from "./components/grids";
import { TierDot } from "./components/tier";
import type { HealthPeriod, HealthTier } from "@/domain/entities/health";

export default function HealthDashboardPage() {
  const t = useT();
  usePageHeader(t.pages.health.title, t.pages.health.subtitle);
  const router = useRouter();

  // No override → the request carries no period params and the backend applies
  // the admin-configured default reporting period; the select reflects it.
  const [override, setOverride] = useState<PeriodState | null>(null);
  const { data, loading } = useHealthExecutive(override ?? {});
  const displayPeriod: PeriodState =
    override ?? { period: (data?.period.key as HealthPeriod) ?? "month" };

  const clientStats = data
    ? [
        { label: t.health.exec.totalClients, value: data.clients.total },
        { label: t.health.exec.activeThisMonth, value: data.clients.active },
        { label: t.health.exec.inactive, value: data.clients.inactive },
        { label: t.health.exec.newClients, value: data.clients.new },
        { label: t.health.exec.churnRisk, value: data.clients.churn_risk, danger: data.clients.churn_risk > 0 },
      ]
    : [];

  const userStats = data
    ? [
        { label: t.health.exec.totalUsers, value: data.users.total },
        { label: t.health.exec.activeToday, value: data.users.active_today },
        { label: t.health.exec.activeWeek, value: data.users.active_week },
        { label: t.health.exec.activeMonth, value: data.users.active_month },
      ]
    : [];

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-end">
        <PeriodFilter value={displayPeriod} onChange={setOverride} />
      </div>

      {data?.needs_compute && <NeedsComputeBanner />}

      {loading && !data ? (
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-4">
          {Array.from({ length: 4 }).map((_, i) => (
            <Skeleton key={i} className="h-44 rounded-xl" />
          ))}
        </div>
      ) : data ? (
        <>
          {/* Score + distribution + client/user KPI groups */}
          <div className="grid grid-cols-1 lg:grid-cols-4 gap-4">
            <Card className="flex flex-col items-center justify-center py-4">
              <p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                {t.health.exec.portfolioScore}
              </p>
              <HealthGauge
                score={data.portfolio_score ?? 0}
                healthyCut={data.tiers.healthy}
                atRiskCut={data.tiers.at_risk}
              />
            </Card>

            <Card className="py-4">
              <CardContent className="flex flex-col items-center">
                <p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground mb-1 self-start">
                  {t.health.exec.distribution}
                </p>
                <DistributionDonut
                  total={data.distribution.total}
                  data={[
                    { tier: "healthy", label: t.health.exec.bandHealthy(data.tiers.healthy), count: data.distribution.healthy.count },
                    { tier: "attention", label: t.health.exec.bandAttention, count: data.distribution.attention.count },
                    { tier: "at_risk", label: t.health.exec.bandAtRisk(data.tiers.at_risk), count: data.distribution.at_risk.count },
                  ]}
                  size={150}
                />
                <div className="mt-2 w-full space-y-1">
                  {(
                    [
                      ["healthy", t.health.exec.bandHealthy(data.tiers.healthy)],
                      ["attention", t.health.exec.bandAttention],
                      ["at_risk", t.health.exec.bandAtRisk(data.tiers.at_risk)],
                    ] as Array<[HealthTier, string]>
                  ).map(([tier, label]) => (
                    <div key={tier} className="flex items-center gap-2 text-xs">
                      <TierDot tier={tier} />
                      <span className="flex-1">{label}</span>
                      <span className="font-mono font-medium">{data.distribution[tier].count}</span>
                      <span className="text-muted-foreground w-9 text-right">{data.distribution[tier].share}%</span>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>

            <GroupCard title={t.health.exec.clients} stats={clientStats} />
            <GroupCard title={t.health.exec.users} stats={userStats} />
          </div>

          {/* Adoption KPIs */}
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
            <StatsCard title={t.health.exec.avgLoginFrequency} value={`${data.adoption.avg_login_frequency}${t.health.exec.perMonth}`} accent="blue" mono />
            <StatsCard title={t.health.exec.avgModules} value={data.adoption.avg_modules} accent="green" mono />
            <StatsCard title={t.health.exec.avgSession} value={data.adoption.avg_session_minutes != null ? t.health.exec.minutes(data.adoption.avg_session_minutes) : "—"} accent="amber" mono />
            <StatsCard title={t.health.exec.avgFeatureAdoption} value={`${data.adoption.avg_feature_adoption}%`} accent="purple" mono />
          </div>

          {/* Engagement trend line */}
          <Card>
            <CardHeader>
              <CardTitle className="text-base flex items-center justify-between flex-wrap gap-2">
                <span>
                  {t.health.exec.engagement}
                  <span className="ml-2 text-xs font-normal text-muted-foreground">{t.health.exec.actionsPerWeek}</span>
                </span>
                <span className="flex items-baseline gap-2">
                  <span className="text-2xl font-bold font-mono">{data.engagement.current.toLocaleString()}</span>
                  <span
                    className={`inline-flex items-center gap-1 text-xs font-semibold ${
                      data.engagement.trend_pct >= 0 ? "text-emerald-600" : "text-red-500"
                    }`}
                  >
                    {data.engagement.trend_pct >= 0 ? <TrendingUp className="w-3.5 h-3.5" /> : <TrendingDown className="w-3.5 h-3.5" />}
                    {data.engagement.trend_pct >= 0 ? "+" : ""}
                    {data.engagement.trend_pct}% {t.health.exec.vsPrev}
                  </span>
                </span>
              </CardTitle>
            </CardHeader>
            <CardContent>
              <TrendLine data={data.engagement.series} height={180} />
            </CardContent>
          </Card>

          {/* Churn list + module utilization */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
            <Card>
              <CardHeader>
                <CardTitle className="text-base flex items-center justify-between">
                  {t.health.exec.churnListTitle}
                  <button
                    onClick={() => router.push(`${ROUTES.healthClients}?tier=at_risk`)}
                    className="text-xs font-medium text-primary hover:underline"
                  >
                    {t.health.exec.viewAll}
                  </button>
                </CardTitle>
              </CardHeader>
              <CardContent>
                {data.churn_risk.length === 0 ? (
                  <p className="py-6 text-center text-sm text-muted-foreground">{t.health.exec.noChurn}</p>
                ) : (
                  <div className="divide-y divide-border">
                    {data.churn_risk.map((c) => (
                      <button
                        key={c.company_user_id}
                        onClick={() => router.push(`${ROUTES.healthClients}/${c.company_user_id}`)}
                        className="w-full flex items-center gap-3 py-2.5 text-left hover:bg-muted/40 rounded-md px-2 -mx-2 transition-colors"
                      >
                        <span className="font-mono font-bold text-sm w-8 text-right" style={{ color: "var(--chart-5)" }}>
                          {c.health}
                        </span>
                        <div className="flex-1 min-w-0">
                          <p className="text-sm font-medium truncate">{c.company}</p>
                          <p className="text-xs text-muted-foreground truncate">
                            {c.last_login_days != null ? t.health.exec.noLoginDays(c.last_login_days) : c.reason ?? ""}
                          </p>
                        </div>
                        {c.last_login_days != null && (
                          <span className="text-xs text-muted-foreground whitespace-nowrap">
                            {t.health.exec.daysAgo(c.last_login_days)}
                          </span>
                        )}
                      </button>
                    ))}
                  </div>
                )}
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="text-base">{t.health.exec.moduleUtil}</CardTitle>
              </CardHeader>
              <CardContent>
                <HBarList
                  items={data.module_utilization.map((m, i) => ({
                    key: m.key,
                    label: m.label,
                    value: m.avg_pct,
                    rank: i + 1,
                    // Top few emphasized in full blue; the tail reads muted.
                    color: i < 3 ? "var(--chart-1)" : "color-mix(in oklch, var(--chart-1) 45%, transparent)",
                  }))}
                />
              </CardContent>
            </Card>
          </div>
        </>
      ) : null}
    </div>
  );
}

function GroupCard({
  title,
  stats,
}: {
  title: string;
  stats: Array<{ label: string; value: number; danger?: boolean }>;
}) {
  return (
    <Card className="py-4">
      <CardContent>
        <p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground mb-3">{title}</p>
        <div className="space-y-2">
          {stats.map((s) => (
            <div key={s.label} className="flex items-center justify-between gap-2">
              <span className="text-sm text-muted-foreground">{s.label}</span>
              <span
                className="text-base font-bold font-mono tabular-nums"
                style={s.danger ? { color: "var(--chart-5)" } : undefined}
              >
                {s.value.toLocaleString()}
              </span>
            </div>
          ))}
        </div>
      </CardContent>
    </Card>
  );
}
