"use client";

import { useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { cn } from "@/shared/lib/utils";
import { usePageHeader } from "@/presentation/hooks/use-page-header";
import { useT } from "@/shared/i18n/client";
import { ROUTES } from "@/shared/constants";
import ServerDataTable, { type Column } from "@/presentation/components/shared/server-data-table";
import { Badge } from "@/presentation/components/ui/badge";
import { useHealthClients } from "../hooks/use-health-clients";
import { NeedsComputeBanner } from "../components/needs-compute-banner";
import { Sparkline } from "../components/charts";
import { ScoreBar, TierDot, TIER_VAR } from "../components/tier";
import type { HealthClientListItem, HealthTier } from "@/domain/entities/health";

const TIER_TABS: Array<{ key: "all" | HealthTier; labelKey: "all" | HealthTier }> = [
  { key: "all", labelKey: "all" },
  { key: "healthy", labelKey: "healthy" },
  { key: "attention", labelKey: "attention" },
  { key: "at_risk", labelKey: "at_risk" },
];

export default function HealthClientsPage() {
  const t = useT();
  usePageHeader(t.pages.healthClients.title, t.pages.healthClients.subtitle);
  const router = useRouter();
  const searchParams = useSearchParams();
  const { pagination, data, loading } = useHealthClients();

  // Deep-link support (e.g. "View all →" from the churn widget): apply ?tier=
  // once, via guarded state-adjustment during render.
  const [tierApplied, setTierApplied] = useState(false);
  const urlTier = searchParams.get("tier");
  if (!tierApplied && urlTier && ["healthy", "attention", "at_risk"].includes(urlTier)) {
    setTierApplied(true);
    pagination.setFilter("tier", urlTier);
  }

  const activeTier = (pagination.filters.tier as string) ?? "all";
  const counts = data?.counts ?? { all: 0, healthy: 0, attention: 0, at_risk: 0 };

  const open = (row: HealthClientListItem) =>
    router.push(`${ROUTES.healthClients}/${row.company_user_id}`);

  const columns: Column<HealthClientListItem>[] = [
    {
      key: "company",
      label: t.health.list.columns.company,
      sortable: true,
      render: (row) => (
        <div className="flex items-center gap-2.5 min-w-0">
          <span className="flex-shrink-0 w-8 h-8 rounded-lg flex items-center justify-center text-xs font-bold text-white" style={{ backgroundColor: `color-mix(in oklch, ${tierVar(row.tier)} 85%, black 5%)` }}>
            {initials(row.company)}
          </span>
          <div className="min-w-0">
            <div className="flex items-center gap-1.5">
              <span className="text-sm font-medium truncate">{row.company}</span>
              {row.is_new && <Badge className="text-[9px] px-1 py-0 h-4 bg-blue-500 text-white border-0">{t.health.list.new}</Badge>}
            </div>
            {row.industry && <p className="text-xs text-muted-foreground truncate">{row.industry}</p>}
          </div>
        </div>
      ),
    },
    { key: "plan", label: t.health.list.columns.plan, sortable: true, render: (row) => <span className="text-sm">{row.plan ?? "—"}</span> },
    { key: "vehicles", label: t.health.list.columns.vehicles, sortable: true, render: (row) => <span className="font-mono text-sm tabular-nums">{row.vehicles}</span> },
    { key: "users", label: t.health.list.columns.users, sortable: true, render: (row) => <span className="font-mono text-sm tabular-nums">{row.users}</span> },
    { key: "active_users", label: t.health.list.columns.active, sortable: true, render: (row) => <span className="font-mono text-sm tabular-nums text-muted-foreground">{row.active_users} / {row.users}</span> },
    { key: "modules_adopted", label: t.health.list.columns.modules, sortable: true, render: (row) => <span className="font-mono text-sm tabular-nums">{row.modules_adopted}/{row.modules_applicable}</span> },
    { key: "trend", label: t.health.list.columns.trend, render: (row) => <Sparkline values={row.trend} color={tierVar(row.tier)} /> },
    { key: "health", label: t.health.list.columns.health, sortable: true, render: (row) => <ScoreBar score={row.health} tier={row.tier} /> },
  ];

  return (
    <div className="p-6 space-y-4">
      {data?.needs_compute && <NeedsComputeBanner />}

      {/* Tier filter chips */}
      <div className="flex items-center gap-2 flex-wrap">
        {TIER_TABS.map((tab) => {
          const active = activeTier === tab.key;
          return (
            <button
              key={tab.key}
              onClick={() => pagination.setFilter("tier", tab.key === "all" ? undefined : tab.key)}
              className={cn(
                "inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-sm font-medium transition-colors",
                active ? "bg-primary text-primary-foreground border-primary" : "bg-card hover:bg-muted/50 border-border"
              )}
            >
              {tab.key !== "all" && <TierDot tier={tab.key as HealthTier} />}
              {t.health.list.tabs[tab.labelKey]}
              <span className={cn("text-xs font-mono", active ? "text-primary-foreground/80" : "text-muted-foreground")}>
                {counts[tab.key]}
              </span>
            </button>
          );
        })}
        <span className="ml-auto text-xs text-muted-foreground">
          {t.health.list.accounts(data?.total ?? 0)}
        </span>
      </div>

      <ServerDataTable<HealthClientListItem>
        columns={columns}
        data={data?.items ?? []}
        total={data?.total ?? 0}
        page={pagination.page}
        totalPages={data?.last_page ?? 1}
        loading={loading}
        search={pagination.search}
        onSearchChange={pagination.setSearch}
        onPageChange={pagination.setPage}
        onSortChange={pagination.setSort}
        sortBy={pagination.orderBy}
        sortOrder={pagination.order}
        searchPlaceholder={t.health.list.searchPlaceholder}
        onRowClick={open}
        getRowId={(row) => row.company_user_id}
      />
    </div>
  );
}

function tierVar(tier: HealthTier): string {
  return TIER_VAR[tier];
}

function initials(name: string): string {
  return name.split(" ").map((w) => w[0]).join("").slice(0, 2).toUpperCase();
}
