"use client";

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

interface InternetPlanCardProps {
  plan: InternetPlanCatalogItem;
  installations: InternetInstallationCatalogItem[];
  disabled?: boolean;
  disabledReason?: string;
}

export function InternetPlanCard({
  plan,
  installations,
  disabled,
  disabledReason,
}: InternetPlanCardProps) {
  const router = useRouter();
  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 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 getBorderClass = () => {
    if (isGold)
      return "border-2 border-yellow-300 bg-gradient-to-br from-white to-yellow-50/30 shadow-xl hover:shadow-2xl ring-2 ring-yellow-200/50";
    if (isPlatinum)
      return "border-2 border-indigo-300 bg-gradient-to-br from-white to-indigo-50/30 shadow-xl hover:shadow-2xl ring-2 ring-indigo-200/50";
    if (isSilver)
      return "border-2 border-gray-300 bg-gradient-to-br from-white to-gray-50/30 shadow-lg hover:shadow-xl ring-1 ring-gray-200/50";
    return "border border-gray-200 bg-white shadow-md hover:shadow-xl";
  };

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

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

    if (detail) {
      return (
        <li key={index} className="flex items-start gap-2">
          <span className="text-green-600 mt-0.5 flex-shrink-0">✓</span>
          <span>
            <span className="font-medium text-gray-900">{label.trim()}:</span>{" "}
            <span className="text-gray-700">{detail.trim()}</span>
          </span>
        </li>
      );
    }

    return (
      <li key={index} className="flex items-start gap-2">
        <span className="text-green-600 mt-0.5 flex-shrink-0">✓</span>
        <span className="text-gray-700">{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 ${getBorderClass()}`}
    >
      <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 border-gray-100">
          <div className="inline-flex flex-wrap items-center gap-2 text-sm">
            <CardBadge
              text={plan.internetPlanTier ?? "Plan"}
              variant={getTierBadgeVariant()}
              size="sm"
            />
            {isGold && <CardBadge text="Recommended" variant="recommended" size="xs" />}
            {planDetail && <CardBadge text={planDetail} variant="family" 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-gray-900 leading-tight">
              {planBaseName}
            </h3>
            {plan.catalogMetadata?.tierDescription || plan.description ? (
              <p className="text-sm text-gray-600 leading-relaxed">
                {plan.catalogMetadata?.tierDescription || plan.description}
              </p>
            ) : null}
          </div>

          {/* Pricing - Full width below */}
          <div className="w-full pt-2">
            <CardPricing
              monthlyPrice={plan.monthlyPrice}
              oneTimePrice={plan.oneTimePrice}
              size="md"
              alignment="left"
            />
          </div>
        </div>

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

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

export type { InternetPlanCardProps };
