import type { StatsViewModel, StatSourceBreakdown } from "../_lib/types";

interface Props {
  stats: StatsViewModel;
  statsStatus?: "complete" | "partial" | "updating";
  onRefreshStats?: () => void;
}

function SourceTooltip({ breakdown, showSignal }: { breakdown: StatSourceBreakdown; showSignal: boolean }) {
  const parts: string[] = [];
  if (breakdown.audit > 0) parts.push(`${breakdown.audit} audit`);
  if (breakdown.siteTag > 0) parts.push(`${breakdown.siteTag} site tag`);
  if (showSignal && breakdown.signal > 0) parts.push(`${breakdown.signal} behavioral`);
  if (parts.length < 2) return null;
  return (
    <div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-2.5 py-1.5 bg-slate-900 text-white text-[11px] rounded-lg whitespace-nowrap pointer-events-none opacity-0 group-hover:opacity-100 transition-opacity z-10 shadow-lg">
      {parts.join(" + ")}
      <div className="absolute top-full left-1/2 -translate-x-1/2 border-4 border-transparent border-t-slate-900" />
    </div>
  );
}

const CARDS = [
  {
    key: "errors" as const,
    label: "Errors",
    tag: "Critical",
    iconPath: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z",
    value: (s: StatsViewModel) => s.errors,
    value_cls: "text-red-600",
    tag_cls: "bg-red-100 text-red-700",
    icon_cls: "text-red-500",
    border_cls: "border-red-200",
    showSignal: true,
  },
  {
    key: "warnings" as const,
    label: "Warnings",
    tag: "High",
    iconPath: "M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z",
    value: (s: StatsViewModel) => s.warnings,
    value_cls: "text-amber-600",
    tag_cls: "bg-amber-100 text-amber-700",
    icon_cls: "text-amber-500",
    border_cls: "border-amber-200",
    showSignal: true,
  },
  {
    key: "notices" as const,
    label: "Notices",
    tag: "Low",
    iconPath: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z",
    value: (s: StatsViewModel) => s.notices,
    value_cls: "text-blue-600",
    tag_cls: "bg-blue-100 text-blue-700",
    icon_cls: "text-blue-500",
    border_cls: "border-blue-200",
    showSignal: true,
  },
  {
    key: "quickWins" as const,
    label: "Quick Wins",
    tag: "Ready",
    iconPath: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z",
    value: (s: StatsViewModel) => s.quickWins,
    value_cls: "text-emerald-600",
    tag_cls: "bg-emerald-100 text-emerald-700",
    icon_cls: "text-emerald-500",
    border_cls: "border-emerald-200",
    showSignal: false,
  },
] as const;

function UpdatingBadge() {
  return (
    <span className="inline-flex items-center gap-1 text-[11px] text-slate-400">
      <svg className="w-3 h-3 animate-spin" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
        <path d="M21 12a9 9 0 11-6.219-8.56" strokeLinecap="round" />
      </svg>
      Updating...
    </span>
  );
}

export function StatsRow({ stats, statsStatus, onRefreshStats }: Props) {
  const showRefresh = statsStatus != null && statsStatus !== "complete" && onRefreshStats != null;
  return (
    <div className="space-y-2">
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
        {CARDS.map((card) => {
          const breakdown = card.value(stats);
          const hasPatterns = breakdown.patternCount != null && breakdown.patternCount > 0;
          const isUpdating = breakdown.isUpdating === true;
          return (
            <div
              key={card.key}
              className={`relative group bg-white border ${card.border_cls} rounded-xl px-5 py-[18px] shadow-subtle`}
            >
              <SourceTooltip breakdown={breakdown} showSignal={card.showSignal} />
              <div className="flex items-center justify-between mb-2.5">
                <span className={`text-[10px] font-semibold uppercase tracking-widest ${card.value_cls}`}>
                  {card.label}
                </span>
                <svg className={`w-3.5 h-3.5 ${card.icon_cls}`} viewBox="0 0 24 24" fill="currentColor">
                  <path d={card.iconPath} />
                </svg>
              </div>
              {isUpdating ? (
                <div className="mt-1">
                  <UpdatingBadge />
                </div>
              ) : hasPatterns ? (
                <>
                  <div className={`text-[36px] font-bold leading-none tabular-nums tracking-tight ${card.value_cls}`}>
                    {breakdown.patternCount}
                  </div>
                  <div className="text-[11px] text-slate-500 mt-1 leading-tight">
                    pattern{breakdown.patternCount !== 1 ? "s" : ""}
                    {breakdown.affectedPageCount != null && breakdown.affectedPageCount > 0
                      ? ` / ${breakdown.affectedPageCount} page${breakdown.affectedPageCount !== 1 ? "s" : ""}`
                      : ""}
                  </div>
                </>
              ) : (
                <div className={`text-[36px] font-bold leading-none tabular-nums tracking-tight ${card.value_cls}`}>
                  {breakdown.total}
                </div>
              )}
              <span className={`inline-block mt-2.5 px-2 py-0.5 text-[10px] font-bold uppercase tracking-widest rounded ${card.tag_cls}`}>
                {card.tag}
              </span>
            </div>
          );
        })}
      </div>
      {showRefresh && (
        <div className="flex items-center gap-2 text-[12px] text-slate-400">
          <svg className="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5}>
            <path d="M12 7v5m0 3v.5" strokeLinecap="round" />
            <circle cx="12" cy="12" r="9" />
          </svg>
          <span>Live event counts are still loading.</span>
          <button
            onClick={onRefreshStats}
            className="inline-flex items-center gap-1 text-red-500 hover:text-red-600 font-medium transition-colors"
          >
            <svg className="w-3 h-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round">
              <path d="M1 4v6h6M23 20v-6h-6" />
              <path d="M20.49 9A9 9 0 005.64 5.64L1 10M23 14l-4.64 4.36A9 9 0 013.51 15" />
            </svg>
            Refresh
          </button>
        </div>
      )}
    </div>
  );
}
