"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 { 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 Styling Configuration
// ============================================================================

type TierKey = "gold" | "platinum" | "silver" | "default";

const tierStyles: Record<TierKey, { card: string; border: string }> = {
  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",
  },
};

// ============================================================================
// Helper Functions
// ============================================================================

function getTierKey(tier: string | undefined): TierKey {
  if (tier === "Gold") return "gold";
  if (tier === "Platinum") return "platinum";
  if (tier === "Silver") return "silver";
  return "default";
}

function getMinInstallationPrice(installations: InternetInstallationCatalogItem[]): number {
  const prices = installations
    .map(({ monthlyPrice, oneTimePrice }) => {
      if (typeof monthlyPrice === "number" && monthlyPrice > 0) return monthlyPrice;
      if (typeof oneTimePrice === "number" && oneTimePrice > 0) return oneTimePrice;
      return 0;
    })
    .filter(price => price > 0);

  return prices.length > 0 ? Math.min(...prices) : 0;
}

function getConnectionSpeed(offeringType: string | undefined): string {
  if (offeringType?.includes("10G")) return "10Gbps";
  if (offeringType?.includes("100M")) return "100Mbps";
  return "1Gbps";
}

function getResidenceType(offeringType: string | undefined): string {
  return offeringType?.includes("Apartment") ? "Mansion" : "Home";
}

function getPlanSubtitle(
  showDetailAsTitle: boolean,
  hasDetail: boolean,
  baseName: string,
  detail: string | null
): string | null {
  if (showDetailAsTitle) return baseName;
  if (hasDetail) return detail;
  return null;
}

interface PlanDisplayInfo {
  title: string;
  subtitle: string | null;
  description: string | null;
}

function getPlanDisplayInfo(
  plan: InternetPlanCatalogItem,
  titlePriority: "detail" | "base"
): PlanDisplayInfo {
  const { baseName, detail } = parsePlanName(plan);
  const hasDetail = Boolean(detail);
  const showDetailAsTitle = titlePriority === "detail" && hasDetail;

  return {
    title: showDetailAsTitle && detail ? detail : baseName,
    subtitle: getPlanSubtitle(showDetailAsTitle, hasDetail, baseName, detail),
    description: plan.catalogMetadata?.tierDescription || plan.description || null,
  };
}

function getButtonLabel(
  isDisabled: boolean,
  disabledReason: string | undefined,
  actionLabel: string | undefined
): string {
  if (isDisabled) return disabledReason || "Not available";
  return actionLabel ?? "Configure Plan";
}

// ============================================================================
// Sub-Components
// ============================================================================

interface FeatureItemProps {
  feature: string;
}

function FeatureItem({ feature }: FeatureItemProps): React.JSX.Element {
  const colonIndex = feature.indexOf(":");
  const hasLabelAndDetail = colonIndex > 0;

  if (hasLabelAndDetail) {
    const label = feature.slice(0, colonIndex).trim();
    const detail = feature.slice(colonIndex + 1).trim();

    return (
      <li 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}:</span>{" "}
          <span className="text-muted-foreground">{detail}</span>
        </span>
      </li>
    );
  }

  return (
    <li 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>
  );
}

interface PlanFeaturesListProps {
  plan: InternetPlanCatalogItem;
  minInstallationPrice: number;
  hasInstallations: boolean;
}

function PlanFeaturesList({
  plan,
  minInstallationPrice,
  hasInstallations,
}: PlanFeaturesListProps): React.JSX.Element {
  const catalogFeatures = plan.catalogMetadata?.features;

  if (catalogFeatures && catalogFeatures.length > 0) {
    return (
      <>
        {catalogFeatures.map((feature, index) => (
          <FeatureItem key={index} feature={feature} />
        ))}
      </>
    );
  }

  const features = buildFallbackFeatures(plan, minInstallationPrice, hasInstallations);

  return (
    <>
      {features.map((feature, index) => (
        <FeatureItem key={index} feature={feature} />
      ))}
    </>
  );
}

function buildFallbackFeatures(
  plan: InternetPlanCatalogItem,
  minInstallationPrice: number,
  hasInstallations: boolean
): string[] {
  const priceParts: string[] = [];
  if (typeof plan.monthlyPrice === "number" && plan.monthlyPrice > 0) {
    priceParts.push(`Monthly: ¥${plan.monthlyPrice.toLocaleString()}`);
  }
  if (typeof plan.oneTimePrice === "number" && plan.oneTimePrice > 0) {
    priceParts.push(`One-time: ¥${plan.oneTimePrice.toLocaleString()}`);
  }

  const residenceType = getResidenceType(plan.internetOfferingType);
  const speed = getConnectionSpeed(plan.internetOfferingType);

  const features: string[] = [
    "NTT Optical Fiber (Flet's Hikari Next)",
    `${residenceType} ${speed} connection`,
    "ISP connection protocols: IPoE and PPPoE",
  ];

  if (priceParts.length > 0) {
    features.push(priceParts.join(" | "));
  }

  if (hasInstallations && minInstallationPrice > 0) {
    features.push(`Installation from ¥${minInstallationPrice.toLocaleString()}`);
  }

  return features;
}

// ============================================================================
// Main Component
// ============================================================================

export function InternetPlanCard({
  plan,
  installations,
  disabled,
  disabledReason,
  configureHref,
  action,
  pricingPrefix,
  showTierBadge = true,
  showPlanSubtitle = true,
  showFeatures = true,
  titlePriority = "detail",
}: InternetPlanCardProps): React.JSX.Element {
  const router = useRouter();
  const servicesBasePath = useServicesBasePath();

  const tier = plan.internetPlanTier;
  const isGold = tier === "Gold";
  const isDisabled = Boolean(disabled) && !IS_DEVELOPMENT;

  const {
    title: planTitle,
    subtitle: planSubtitle,
    description: planDescription,
  } = getPlanDisplayInfo(plan, titlePriority);

  const minInstallationPrice = getMinInstallationPrice(installations);
  const tierKey = getTierKey(tier);
  const tierStyle = tierStyles[tierKey];

  const handleConfigure = (): void => {
    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);
  };

  const buttonLabel = getButtonLabel(isDisabled, disabledReason, action?.label);

  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">
        <PlanCardHeader
          plan={plan}
          tier={tier}
          isGold={isGold}
          tierStyle={tierStyle}
          showTierBadge={showTierBadge}
          showPlanSubtitle={showPlanSubtitle}
          planTitle={planTitle}
          planSubtitle={planSubtitle}
          planDescription={planDescription}
          pricingPrefix={pricingPrefix}
        />

        {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">
              <PlanFeaturesList
                plan={plan}
                minInstallationPrice={minInstallationPrice}
                hasInstallations={installations.length > 0}
              />
            </ul>
          </div>
        )}

        <Button
          className="w-full mt-2 transition-all duration-300"
          disabled={isDisabled}
          rightIcon={isDisabled ? undefined : <ArrowRightIcon className="w-4 h-4" />}
          onClick={handleConfigure}
        >
          {buttonLabel}
        </Button>
      </div>
    </AnimatedCard>
  );
}

// ============================================================================
// Header Sub-Component
// ============================================================================

interface PlanCardHeaderProps {
  plan: InternetPlanCatalogItem;
  tier: string | undefined;
  isGold: boolean;
  tierStyle: { card: string; border: string };
  showTierBadge: boolean;
  showPlanSubtitle: boolean;
  planTitle: string | undefined;
  planSubtitle: string | null;
  planDescription: string | null;
  pricingPrefix: string | undefined;
}

function PlanCardHeader({
  plan,
  tier,
  isGold,
  tierStyle,
  showTierBadge,
  showPlanSubtitle,
  planTitle,
  planSubtitle,
  planDescription,
  pricingPrefix,
}: PlanCardHeaderProps): React.JSX.Element {
  return (
    <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={tier ?? "Plan"} variant={getTierKey(tier)} size="sm" />}
        {showTierBadge && isGold && (
          <CardBadge text="Recommended" variant="recommended" size="xs" />
        )}
      </div>

      <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>

      <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>
  );
}

export type { InternetPlanCardProps };
