"use client";

import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";

export type ReportLifecycleBadgeKind = "potential" | "expired" | "upcoming";

type ReportLifecycleBadgeProps = {
  kind: ReportLifecycleBadgeKind;
  /** Optional tooltip / title (e.g. potentialReason). */
  title?: string | null;
  /** When set, shows e.g. "7 Potential" on accordion / section headers. */
  count?: number | null;
  className?: string;
};

const KIND_LABEL: Record<ReportLifecycleBadgeKind, string> = {
  potential: "Potential",
  expired: "Expired",
  upcoming: "Upcoming",
};

const KIND_CLASS: Record<ReportLifecycleBadgeKind, string> = {
  potential:
    "border-amber-500/30 bg-amber-500/10 text-amber-800 dark:text-amber-200",
  expired:
    "border-slate-400/40 bg-slate-500/10 text-slate-700 dark:border-slate-500/40 dark:text-slate-300",
  upcoming:
    "border-sky-500/30 bg-sky-500/10 text-sky-800 dark:text-sky-200",
};

/**
 * Compact lifecycle chip for Structured Products / Accumulator report rows.
 * Driven by sticky flags (move_potential / move_live) or current tab lifecycle.
 */
export function ReportLifecycleBadge({
  kind,
  title,
  count,
  className,
}: ReportLifecycleBadgeProps) {
  const countLabel =
    typeof count === "number" && Number.isFinite(count) && count > 0
      ? `${Math.trunc(count)} `
      : "";

  return (
    <Badge
      variant="outline"
      title={title?.trim() || undefined}
      className={cn("h-5 rounded-md px-1.5 text-[10px] font-semibold uppercase tracking-wide", KIND_CLASS[kind], className)}
    >
      {countLabel}
      {KIND_LABEL[kind]}
    </Badge>
  );
}

/** Prefer sticky Potential flag; fall back to tab lifecycle. */
export function resolvePotentialBadge(options: {
  lifecycle?: string | null;
  movePotential?: boolean | null;
  moveLive?: boolean | null;
}): Extract<ReportLifecycleBadgeKind, "potential"> | null {
  if (options.moveLive) {
    return null;
  }
  if (options.movePotential || options.lifecycle === "potential") {
    return "potential";
  }
  return null;
}

/**
 * Post-dated holding (t_date after today): kept out of every total until it starts, but still listed.
 * Driven by the backend `upcoming` flag.
 */
export function resolveUpcomingBadge(options: {
  upcoming?: boolean | null;
}): Extract<ReportLifecycleBadgeKind, "upcoming"> | null {
  return options.upcoming ? "upcoming" : null;
}

function localTodayKey(): string {
  const now = new Date();
  const y = now.getFullYear();
  const m = String(now.getMonth() + 1).padStart(2, "0");
  const d = String(now.getDate()).padStart(2, "0");
  return `${y}-${m}-${d}`;
}

/** Expired tab / past-dated cashflow events (Potential takes precedence when both apply). */
export function resolveExpiredBadge(options: {
  lifecycle?: string | null;
  /** yyyy-MM-dd — when before today, treat as expired on cashflow surfaces. */
  eventDate?: string | null;
  movePotential?: boolean | null;
  moveLive?: boolean | null;
  /** Override "today" for tests (yyyy-MM-dd). */
  today?: string | null;
}): Extract<ReportLifecycleBadgeKind, "expired"> | null {
  if (resolvePotentialBadge(options) === "potential") {
    return null;
  }
  if (options.lifecycle === "expired") {
    return "expired";
  }
  const date = options.eventDate?.trim() ?? "";
  if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
    return null;
  }
  const todayKey = options.today?.trim() || localTodayKey();
  return date < todayKey ? "expired" : null;
}

/** Soft de-emphasis so Potential / Expired cards read as non-live vs active chips. */
export function reportLifecycleSurfaceClass(
  kind: ReportLifecycleBadgeKind | null | undefined,
): string {
  if (kind === "potential" || kind === "expired") {
    return "opacity-[0.58] saturate-[0.45] hover:opacity-100 hover:saturate-100";
  }
  return "";
}
