"use client";

import { AnimatedCard } from "@/components/molecules";
import { Button } from "@/components/atoms/button";
import { ArrowRightIcon, CheckIcon } from "@heroicons/react/24/outline";
import type {
  InternetPlanCatalogItem,
  InternetInstallationCatalogItem,
} from "@customer-portal/domain/services";
import { useRouter } from "next/navigation";
import { CardPricing } from "@/features/services/components/base/CardPricing";
import { CardBadge } from "@/features/services/components/base/CardBadge";
import type { BadgeVariant } from "@/features/services/components/base/CardBadge";
import { useCatalogStore } from "@/features/services/stores/services.store";
import { IS_DEVELOPMENT } from "@/config/environment";
import { parsePlanName } from "@/features/services/components/internet/utils/planName";
import { useServicesBasePath } from "@/features/services/hooks/useServicesBasePath";

interface InternetPlanCardProps {
  plan: InternetPlanCatalogItem;
  installations: InternetInstallationCatalogItem[];
  disabled?: boolean;
  disabledReason?: string;
  /** Override the default configure href (default: /services/internet/configure?planSku=...) */
  configureHref?: string;
  /** Override default "Configure Plan" action (used for public browse-only flows) */
  action?: { label: string; href: string };
  /** Optional small prefix above pricing (e.g. "Starting from") */
  pricingPrefix?: string;
  /** Show tier badge (default: true) */
  showTierBadge?: boolean;
  /** Show plan subtitle (default: true) */
  showPlanSubtitle?: boolean;
  /** Show features list (default: true) */
  showFeatures?: boolean;
  /** Prefer which label becomes the title when details exist */
  titlePriority?: "detail" | "base";
}

// Tier-based styling using design tokens
const tierStyles = {
  gold: {
    card: "border-2 border-warning/50 bg-gradient-to-br from-card to-warning-soft/30 shadow-xl hover:shadow-2xl ring-2 ring-warning/20",
    border: "border-warning/30",
  },
  platinum: {
    card: "border-2 border-primary/50 bg-gradient-to-br from-card to-info-soft/30 shadow-xl hover:shadow-2xl ring-2 ring-primary/20",
    border: "border-primary/30",
  },
  silver: {
    card: "border-2 border-muted-foreground/30 bg-gradient-to-br from-card to-muted/30 shadow-lg hover:shadow-xl ring-1 ring-border",
    border: "border-muted-foreground/20",
  },
  default: {
    card: "border border-border bg-card shadow-md hover:shadow-xl",
    border: "border-border",
  },
} as const;

export function InternetPlanCard({
  plan,
  installations,
  disabled,
  disabledReason,
  configureHref,
  action,
  pricingPrefix,
  showTierBadge = true,
  showPlanSubtitle = true,
  showFeatures = true,
  titlePriority = "detail",
}: InternetPlanCardProps) {
  const router = useRouter();
  const servicesBasePath = useServicesBasePath();
  const tier = plan.internetPlanTier;
  const isGold = tier === "Gold";
  const isPlatinum = tier === "Platinum";
  const isSilver = tier === "Silver";
  const isDisabled = disabled && !IS_DEVELOPMENT;
  const { baseName: planBaseName, detail: planDetail } = parsePlanName(plan);
  const hasDetail = Boolean(planDetail);
  const showDetailAsTitle = titlePriority === "detail" && hasDetail;
  const planTitle = showDetailAsTitle ? planDetail : planBaseName;
  const planSubtitle = showDetailAsTitle ? planBaseName : hasDetail ? planDetail : null;
  const planDescription = plan.catalogMetadata?.tierDescription || plan.description || null;

  const installationPrices = installations
    .map(installation => {
      const { monthlyPrice, oneTimePrice } = installation;
      if (typeof monthlyPrice === "number" && monthlyPrice > 0) {
        return monthlyPrice;
      }
      if (typeof oneTimePrice === "number" && oneTimePrice > 0) {
        return oneTimePrice;
      }
      return 0;
    })
    .filter(price => price > 0);

  const minInstallationPrice = installationPrices.length ? Math.min(...installationPrices) : 0;

  const getTierStyle = () => {
    if (isGold) return tierStyles.gold;
    if (isPlatinum) return tierStyles.platinum;
    if (isSilver) return tierStyles.silver;
    return tierStyles.default;
  };

  const getTierBadgeVariant = (): BadgeVariant => {
    if (isGold) return "gold";
    if (isPlatinum) return "platinum";
    if (isSilver) return "silver";
    return "default";
  };

  const tierStyle = getTierStyle();

  const renderFeature = (feature: string, index: number) => {
    const [label, detail] = feature.split(":");

    if (detail && label) {
      return (
        <li key={index} className="flex items-start gap-2">
          <CheckIcon className="h-4 w-4 text-success mt-0.5 flex-shrink-0" />
          <span>
            <span className="font-medium text-foreground">{label.trim()}:</span>{" "}
            <span className="text-muted-foreground">{detail.trim()}</span>
          </span>
        </li>
      );
    }

    return (
      <li key={index} className="flex items-start gap-2">
        <CheckIcon className="h-4 w-4 text-success mt-0.5 flex-shrink-0" />
        <span className="text-muted-foreground">{feature}</span>
      </li>
    );
  };

  const renderPlanFeatures = () => {
    if (plan.catalogMetadata?.features && plan.catalogMetadata.features.length > 0) {
      return plan.catalogMetadata.features.map(renderFeature);
    }

    const priceSummaryParts = [
      typeof plan.monthlyPrice === "number" && plan.monthlyPrice > 0
        ? `Monthly: ¥${plan.monthlyPrice.toLocaleString()}`
        : null,
      typeof plan.oneTimePrice === "number" && plan.oneTimePrice > 0
        ? `One-time: ¥${plan.oneTimePrice.toLocaleString()}`
        : null,
    ].filter(Boolean) as string[];

    const fallbackFeatures = [
      "NTT Optical Fiber (Flet's Hikari Next)",
      `${plan.internetOfferingType?.includes("Apartment") ? "Mansion" : "Home"} ${
        plan.internetOfferingType?.includes("10G")
          ? "10Gbps"
          : plan.internetOfferingType?.includes("100M")
            ? "100Mbps"
            : "1Gbps"
      } connection`,
      "ISP connection protocols: IPoE and PPPoE",
      ...(priceSummaryParts.length > 0 ? [priceSummaryParts.join(" | ")] : []),
      installations.length > 0 && minInstallationPrice > 0
        ? `Installation from ¥${minInstallationPrice.toLocaleString()}`
        : null,
    ].filter(Boolean) as string[];

    return fallbackFeatures.map(renderFeature);
  };

  return (
    <AnimatedCard
      variant="static"
      className={`overflow-hidden flex flex-col h-full transition-all duration-200 ease-out hover:-translate-y-1 rounded-xl ${tierStyle.card}`}
    >
      <div className="p-6 sm:p-7 flex flex-col flex-grow space-y-5">
        {/* Header with badges */}
        <div className={`flex flex-col gap-3 pb-4 border-b ${tierStyle.border}`}>
          <div className="inline-flex flex-wrap items-center gap-2 text-sm">
            {showTierBadge && (
              <CardBadge
                text={plan.internetPlanTier ?? "Plan"}
                variant={getTierBadgeVariant()}
                size="sm"
              />
            )}
            {showTierBadge && isGold && (
              <CardBadge text="Recommended" variant="recommended" size="xs" />
            )}
          </div>

          {/* Plan name and description - Full width */}
          <div className="w-full space-y-2">
            <h3 className="text-xl sm:text-2xl font-bold text-foreground leading-tight">
              {planTitle}
            </h3>
            {showPlanSubtitle && planSubtitle && (
              <p className="text-xs uppercase tracking-wide text-muted-foreground">
                {planSubtitle}
              </p>
            )}
            {planDescription ? (
              <p className="text-sm text-muted-foreground leading-relaxed">{planDescription}</p>
            ) : null}
          </div>

          {/* Pricing - Full width below */}
          <div className="w-full pt-2">
            {pricingPrefix ? (
              <div className="text-xs font-medium uppercase tracking-wide text-muted-foreground mb-1">
                {pricingPrefix}
              </div>
            ) : null}
            <CardPricing
              monthlyPrice={plan.monthlyPrice}
              oneTimePrice={plan.oneTimePrice}
              size="md"
              alignment="left"
            />
          </div>
        </div>

        {/* Features */}
        {showFeatures && (
          <div className="flex-grow pt-1">
            <h4 className="font-semibold text-foreground mb-4 text-sm uppercase tracking-wide">
              Your Plan Includes:
            </h4>
            <ul className="space-y-3 text-sm">{renderPlanFeatures()}</ul>
          </div>
        )}

        {/* Action Button */}
        <Button
          className="w-full mt-2 transition-all duration-300"
          disabled={isDisabled}
          rightIcon={isDisabled ? undefined : <ArrowRightIcon className="w-4 h-4" />}
          onClick={() => {
            if (isDisabled) return;
            if (action) {
              router.push(action.href);
              return;
            }
            const { resetInternetConfig, setInternetConfig } = useCatalogStore.getState();
            resetInternetConfig();
            setInternetConfig({ planSku: plan.sku, currentStep: 1 });
            const href =
              configureHref ??
              `${servicesBasePath}/internet/configure?planSku=${encodeURIComponent(plan.sku)}`;
            router.push(href);
          }}
        >
          {isDisabled ? disabledReason || "Not available" : (action?.label ?? "Configure Plan")}
        </Button>
      </div>
    </AnimatedCard>
  );
}

export type { InternetPlanCardProps };
