import { motion } from "motion/react";
import { cn } from "@/lib/utils";
import { StockBadge } from "./StockBadge";
import type {
  BillingCycle,
  GameBillingConfig,
  GameLocationOption,
  GamePlan,
  GameSoftwareOption,
  ProductBadgeTone,
} from "@/lib/data/game-hosting";

interface ProductCardProps {
  plan: GamePlan;
  tierColor: string;
  stockStatus: { status: string; count: number | null };
  isLoadingStock: boolean;
  index: number;
  cycle: BillingCycle;
  selectedLocation: GameLocationOption;
  billingConfig: GameBillingConfig;
  selectedSoftware?: GameSoftwareOption;
}

function toneClass(tone: ProductBadgeTone = "zinc") {
  return {
    accent: {
      card: "border-accent/65 bg-accent/[0.045] shadow-[0_4px_0_rgba(147,51,234,0.5),0_22px_42px_rgba(147,51,234,0.14),inset_0_1px_0_rgba(255,255,255,0.18)]",
      badge: "bg-accent text-white border-accent-hover/70 shadow-[0_2px_0_rgba(61,18,118,0.45),0_10px_24px_rgba(147,51,234,0.18)]",
    },
    emerald: {
      card: "border-emerald-500/65 bg-emerald-500/[0.045] shadow-[0_4px_0_rgba(16,185,129,0.42),0_22px_42px_rgba(16,185,129,0.12),inset_0_1px_0_rgba(255,255,255,0.18)]",
      badge: "bg-emerald-500 text-white border-emerald-400/70 shadow-[0_2px_0_rgba(6,95,70,0.42),0_10px_24px_rgba(16,185,129,0.16)]",
    },
    amber: {
      card: "border-amber-500/70 bg-amber-500/[0.045] shadow-[0_4px_0_rgba(245,158,11,0.46),0_22px_42px_rgba(245,158,11,0.12),inset_0_1px_0_rgba(255,255,255,0.18)]",
      badge: "bg-amber-500 text-zinc-950 border-amber-300/70 shadow-[0_2px_0_rgba(146,64,14,0.38),0_10px_24px_rgba(245,158,11,0.16)]",
    },
    rose: {
      card: "border-rose-500/65 bg-rose-500/[0.045] shadow-[0_4px_0_rgba(244,63,94,0.42),0_22px_42px_rgba(244,63,94,0.12),inset_0_1px_0_rgba(255,255,255,0.18)]",
      badge: "bg-rose-500 text-white border-rose-400/70 shadow-[0_2px_0_rgba(136,19,55,0.42),0_10px_24px_rgba(244,63,94,0.16)]",
    },
    zinc: {
      card: "border-border/90 bg-surface shadow-[0_4px_0_rgba(0,0,0,0.28),0_22px_42px_rgba(0,0,0,0.16),inset_0_1px_0_var(--depth-highlight)]",
      badge: "bg-elevated text-content border-border-hover/70 shadow-[0_2px_0_rgba(0,0,0,0.28),0_10px_24px_rgba(0,0,0,0.12)]",
    },
  }[tone];
}

function appendParams(url: string, params: Record<string, string | undefined>) {
  const entries = Object.entries(params).filter((entry): entry is [string, string] => Boolean(entry[1]));

  try {
    const parsed = new URL(url);
    entries.forEach(([key, value]) => parsed.searchParams.set(key, value));
    return parsed.toString();
  } catch {
    if (!entries.length) return url;
    const query = entries.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join("&");
    return `${url}${url.includes("?") ? "&" : "?"}${query}`;
  }
}

function getBillingUrl(
  plan: GamePlan,
  cycle: BillingCycle,
  billingConfig: GameBillingConfig,
  selectedLocation: GameLocationOption,
  selectedSoftware?: GameSoftwareOption
) {
  const baseUrl = selectedSoftware ? plan.billing.software?.[selectedSoftware.id]?.[cycle] ?? plan.billing[cycle] : plan.billing[cycle];
  const params: Record<string, string | undefined> = {
    [billingConfig.cycleParam]: cycle,
    [billingConfig.locationParam]: selectedLocation.configValue,
  };

  if (billingConfig.softwareParam && selectedSoftware) {
    params[billingConfig.softwareParam] = selectedSoftware.configValue;
  }

  return appendParams(baseUrl, params);
}

export function ProductCard({
  plan,
  tierColor,
  stockStatus,
  isLoadingStock,
  index,
  cycle,
  selectedLocation,
  billingConfig,
  selectedSoftware,
}: ProductCardProps) {
  const isSoldOut = stockStatus.status === "out_of_stock" && !isLoadingStock;
  const isLowStock = stockStatus.count !== null && stockStatus.count > 0 && stockStatus.count <= 5;
  const mainBadge = plan.badges?.[0];
  const tone = toneClass(mainBadge?.tone);
  const billingUrl = getBillingUrl(plan, cycle, billingConfig, selectedLocation, selectedSoftware);

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, scale: 0.97 }}
      transition={{ duration: 0.4, delay: index * 0.05 }}
      className={cn(
        "game-plan-card group relative flex flex-col overflow-visible border transition-all duration-200 rounded-xl",
        mainBadge ? tone.card : toneClass("zinc").card,
        isSoldOut ? "opacity-60" : "hover:-translate-y-1"
      )}
    >
      {mainBadge && (
        <div className="absolute left-5 top-0 z-20 -translate-y-1/2">
          <span className={cn("px-2.5 py-1 text-[10px] font-black uppercase tracking-widest border rounded-md", tone.badge)}>
            {mainBadge.label}
          </span>
        </div>
      )}

      <StockBadge
        isLoading={isLoadingStock}
        isSoldOut={isSoldOut}
        isLowStock={isLowStock}
        count={stockStatus.count}
      />

      <div className="flex-1 flex flex-col p-5 pt-7">
        <div className="mb-4">
          <h3
            className={cn(
              "text-lg font-black uppercase tracking-tight mb-1 transition-colors",
              isSoldOut ? "text-content-subtle" : "text-content group-hover:text-accent-text"
            )}
          >
            {plan.name}
          </h3>
          <p className="text-xs text-content-muted font-sans leading-relaxed">{plan.tagline}</p>
        </div>

        <div className="mb-4 pb-4 border-b border-dashed border-border/80">
          <p className="text-[9px] text-content-subtle font-black uppercase tracking-widest mb-1.5 flex items-center gap-1">
            <span className="w-1.5 h-1.5 bg-content-subtle block" /> REC_USAGE
          </p>
          <p className="text-[11px] text-content-dim font-sans leading-relaxed border-l-2 border-border pl-2">{plan.recommended}</p>
        </div>

        <div className="grid grid-cols-2 gap-x-2 gap-y-3 mb-6">
          <Spec label="RAM_ALLOC" value={plan.specs.ram} />
          <Spec label="CPU_CORES" value={plan.specs.cpu} />
          <Spec label="NVME_SSD" value={plan.specs.storage} />
          <Spec label="NET_LIMIT" value={plan.specs.bandwidth} />
          <Spec label="LOC_NODE" value={selectedLocation.label} />
          <Spec label="BKP_SLOTS" value={plan.specs.backup} />
        </div>
        
        <div className="mt-auto pt-4 bg-elevated/60 -mx-5 px-5 -mb-5 pb-5 border-t border-border/80 rounded-bl-xl rounded-br-xl">
          <div className="flex items-end justify-between gap-4 mb-4">
            <div>
              <p className="text-[10px] font-black uppercase tracking-widest text-content-subtle mb-1">
                {cycle === "monthly" ? "1 MONTH" : "12 MONTHS"}
              </p>
              <p className="text-2xl font-black text-content tracking-tighter">
                {plan.price[cycle]}
                <span className="text-[10px] font-bold text-content-subtle ml-1">
                  {cycle === "monthly" ? "/mo" : "/yr"}
                </span>
              </p>
            </div>
          </div>

          <a
            href={isSoldOut ? "#" : billingUrl}
            target={isSoldOut ? "_self" : "_blank"}
            rel="noopener noreferrer"
            onClick={(e) => isSoldOut && e.preventDefault()}
            className={cn(
              "w-full block text-center py-3 text-xs font-black uppercase tracking-widest transition-all duration-150 border rounded-lg",
              isSoldOut
                ? "bg-elevated border-border text-content-subtle cursor-not-allowed"
                : "bg-accent border-accent/80 text-white hover:bg-accent-hover hover:border-accent-hover hover:-translate-y-0.5 active:translate-y-1 active:shadow-none"
            )}
          >
            {isSoldOut ? "SOLD OUT" : "ORDER"}
          </a>
        </div>
      </div>
    </motion.div>
  );
}

function Spec({ label, value }: { label: string; value: string }) {
  return (
    <div className="bg-elevated/70 border border-border/80 rounded-md p-1.5 flex flex-col justify-center shadow-[inset_0_1px_0_var(--depth-highlight)]">
      <p className="text-[8px] font-black uppercase tracking-widest text-content-subtle mb-0.5">{label}</p>
      <p className="text-[11px] font-bold text-content-dim truncate">{value}</p>
    </div>
  );
}
