"use client";

import Link from "next/link";
import type { LucideIcon } from "lucide-react";
import {
  ArrowUpRight, ArrowDownRight, Minus, Info,
  Plug, Inbox, Clock, AlertCircle,
} from "lucide-react";

/**
 * Shared KPI card used across every Site Tag Analytics tab.
 * Guarantees equal padding, font sizes, and height so cards in
 * the same grid row stay aligned.
 */
export interface SummaryCardProps {
  label: string;
  value: string;
  subtitle?: string;
  icon?: LucideIcon;
  change?: { pct: number; direction: string } | null;
  iconColor?: string;
  /** Semantic tint applied to the value — "good", "warn", "bad", or default slate */
  tone?: "good" | "warn" | "bad" | "default";
  /** Optional hover tooltip — renders an Info icon next to the label */
  tooltip?: string;
}

const toneClasses: Record<NonNullable<SummaryCardProps["tone"]>, string> = {
  good: "text-emerald-600",
  warn: "text-amber-600",
  bad: "text-red-600",
  default: "text-slate-900",
};

export function SummaryCard({
  label, value, subtitle, icon: Icon, change, iconColor = "text-slate-300", tone = "default",
  tooltip,
}: SummaryCardProps) {
  return (
    <div className="bg-white rounded-xl border border-slate-200 px-5 py-4 flex flex-col justify-between min-h-[110px] hover:border-slate-300 hover:shadow-sm transition-all">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-1.5">
          <p className="text-xs font-semibold text-slate-500 uppercase tracking-wide">{label}</p>
          {tooltip && (
            <span className="relative group inline-flex items-center">
              <Info className="w-3.5 h-3.5 text-slate-400 hover:text-slate-600 cursor-help" />
              <span
                role="tooltip"
                className="pointer-events-none absolute left-1/2 -translate-x-1/2 top-full mt-2 z-20 w-64 rounded-lg bg-slate-900 text-white text-[11px] leading-snug px-3 py-2 shadow-lg opacity-0 group-hover:opacity-100 transition-opacity whitespace-pre-line normal-case tracking-normal font-normal"
              >
                {tooltip}
              </span>
            </span>
          )}
        </div>
        {Icon && <Icon className={`w-4 h-4 ${iconColor}`} />}
      </div>
      <div className="mt-2">
        <p className={`text-[28px] font-bold leading-none tabular-nums ${toneClasses[tone]}`}>{value}</p>
        {subtitle && <p className="text-[10px] text-slate-400 mt-1.5 truncate">{subtitle}</p>}
        {change && (
          <p className={`text-xs font-medium mt-2 flex items-center gap-0.5 ${
            change.direction === "up" ? "text-green-600" :
            change.direction === "down" ? "text-red-500" : "text-slate-400"
          }`}>
            {change.direction === "up" ? <ArrowUpRight className="w-3 h-3" /> :
             change.direction === "down" ? <ArrowDownRight className="w-3 h-3" /> :
             <Minus className="w-3 h-3" />}
            {Math.abs(change.pct)}% vs previous period
          </p>
        )}
      </div>
    </div>
  );
}

/** Standard table card container — border, rounded, colored icon header */
export function CardShell({ title, icon: Icon, right, children, className = "" }: {
  title: string;
  icon?: LucideIcon;
  right?: React.ReactNode;
  children: React.ReactNode;
  className?: string;
}) {
  return (
    <div className={`bg-white rounded-xl border border-slate-200 overflow-hidden ${className}`}>
      <div className="px-5 py-3.5 border-b border-slate-100 flex items-center gap-2">
        {Icon && <Icon className="w-4 h-4 text-brand-600" />}
        <h3 className="font-bold text-slate-800 text-sm">{title}</h3>
        {right && <div className="ml-auto">{right}</div>}
      </div>
      {children}
    </div>
  );
}

/** Pulsing skeleton block — used in loading states instead of a bare spinner.
 * Matches the dimensions of the content that will replace it so the layout
 * doesn't jump when data arrives. */
export function Skeleton({ className = "" }: { className?: string }) {
  return <div className={`animate-pulse bg-slate-200 rounded ${className}`} />;
}

/** Skeleton placeholder mimicking a row of KPI cards (4 equal columns). */
export function KpiRowSkeleton() {
  return (
    <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
      {[0, 1, 2, 3].map((i) => (
        <div key={i} className="bg-white rounded-xl border border-slate-200 px-5 py-4 min-h-[110px] flex flex-col justify-between">
          <div className="flex items-center justify-between">
            <Skeleton className="h-3 w-20" />
            <Skeleton className="h-3.5 w-3.5 rounded-full" />
          </div>
          <Skeleton className="h-7 w-24 mt-2" />
        </div>
      ))}
    </div>
  );
}

/**
 * Section placeholder shown when a Site Tag Analytics card has no data,
 * is still calibrating, or depends on an integration that isn't connected.
 * Renders with the same card chrome as a real card so layout never shifts.
 *
 * Variant defaults (icon + tone) keep the visual language consistent —
 * "not_connected" reads neutral (gray Plug), not alarming. Red is reserved
 * for the "error" variant only.
 */
export interface SectionStateProps {
  variant: "calibrating" | "no_data" | "not_connected" | "error";
  title: string;
  description?: string;
  cta?: { label: string; href: string };
  /** Override the default icon for the variant */
  icon?: LucideIcon;
  /** Pin a min-height (used inside chart containers so cards stay full size) */
  minHeight?: number;
  /** "card" wraps the content in the same shell as a SummaryCard / CardShell.
   *  "bare" renders only the centered content — use when nesting inside an
   *  existing CardShell so titles don't get duplicated. */
  chrome?: "card" | "bare";
  className?: string;
}

const SECTION_STATE_VARIANTS = {
  calibrating:   { icon: Clock,        iconBg: "bg-slate-100", iconColor: "text-slate-500" },
  no_data:       { icon: Inbox,        iconBg: "bg-slate-100", iconColor: "text-slate-500" },
  not_connected: { icon: Plug,         iconBg: "bg-slate-100", iconColor: "text-slate-500" },
  error:         { icon: AlertCircle,  iconBg: "bg-red-50",    iconColor: "text-red-500"   },
} as const;

export function SectionState({
  variant, title, description, cta, icon, minHeight, chrome = "card", className = "",
}: SectionStateProps) {
  const v = SECTION_STATE_VARIANTS[variant];
  const Icon = icon ?? v.icon;
  const inner = (
    <div
      className={`flex flex-col items-center justify-center text-center px-6 py-8 ${className}`}
      style={minHeight ? { minHeight } : undefined}
    >
      <div className={`w-10 h-10 rounded-xl ${v.iconBg} flex items-center justify-center mb-3`}>
        <Icon className={`w-4 h-4 ${v.iconColor}`} />
      </div>
      <p className="text-sm font-bold text-slate-700">{title}</p>
      {description && <p className="text-xs text-slate-500 mt-1.5 max-w-sm leading-relaxed">{description}</p>}
      {cta && (
        <Link
          href={cta.href}
          className="inline-flex items-center gap-1.5 mt-3 px-3 py-1.5 rounded-lg text-xs font-semibold text-white bg-brand-600 hover:bg-brand-700 transition-colors"
        >
          {cta.label} <ArrowUpRight className="w-3 h-3" />
        </Link>
      )}
    </div>
  );
  if (chrome === "bare") return inner;
  return (
    <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
      {inner}
    </div>
  );
}

/** Skeleton placeholder mimicking a data table — header row + N body rows. */
export function TableSkeleton({ rows = 6, cols = 5 }: { rows?: number; cols?: number }) {
  return (
    <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
      <div className="px-5 py-3.5 border-b border-slate-100">
        <Skeleton className="h-4 w-32" />
      </div>
      <div className="divide-y divide-slate-100">
        {Array.from({ length: rows }, (_, i) => (
          <div key={i} className="px-5 py-3 flex items-center gap-4">
            {Array.from({ length: cols }, (_, j) => (
              <Skeleton key={j} className={`h-3 ${j === 0 ? "flex-1" : "w-16"}`} />
            ))}
          </div>
        ))}
      </div>
    </div>
  );
}
