"use client";

import { useState } from "react";
import { ChevronDown, ChevronUp, Home, Building2, Info, X, Sparkles, Check } from "lucide-react";
import { Button } from "@/components/atoms/button";
import { CardBadge } from "@/features/services/components/base/CardBadge";
import { cn } from "@/shared/utils";

interface TierInfo {
  tier: "Silver" | "Gold" | "Platinum";
  monthlyPrice: number;
  /** Max price for showing price range (when prices vary by offering type) */
  maxMonthlyPrice?: number;
  description: string;
  features: string[];
  pricingNote?: string;
}

interface PublicOfferingCardProps {
  offeringType: string;
  title: string;
  speedBadge: string;
  description: string;
  iconType: "home" | "apartment";
  startingPrice: number;
  /** Maximum price for showing price range */
  maxPrice?: number;
  setupFee: number;
  tiers: TierInfo[];
  isPremium?: boolean;
  ctaPath: string;
  defaultExpanded?: boolean;
  /** Show info tooltip explaining connection types (for Apartment) */
  showConnectionInfo?: boolean;
  customCtaLabel?: string;
  onCtaClick?: (e: React.MouseEvent) => void;
}

const TIER_CARD_BASE = "border-border/60 bg-card";

const tierStyles = {
  Silver: {
    card: TIER_CARD_BASE,
    accent: "text-muted-foreground",
    leftBorder: "border-l-slate-400",
  },
  Gold: {
    card: TIER_CARD_BASE,
    accent: "text-amber-600",
    leftBorder: "border-l-amber-500",
  },
  Platinum: {
    card: TIER_CARD_BASE,
    accent: "text-primary",
    leftBorder: "border-l-primary",
  },
} as const;

function ConnectionTypeInfo({ onClose }: { onClose: () => void }) {
  return (
    <div className="bg-info-soft/30 border border-info/15 rounded-lg p-3.5 mb-4">
      <div className="flex items-start justify-between gap-3 mb-2.5">
        <div className="flex items-center gap-2">
          <Info className="h-4 w-4 text-info flex-shrink-0" />
          <h4 className="font-semibold text-xs text-foreground">
            Why does speed vary by building?
          </h4>
        </div>
        <button
          type="button"
          onClick={onClose}
          className="text-muted-foreground hover:text-foreground transition-colors"
        >
          <X className="h-3.5 w-3.5" />
        </button>
      </div>
      <div className="space-y-2.5 text-[11px] text-muted-foreground">
        <p>
          Apartment buildings in Japan have different fiber infrastructure installed by NTT. Your
          available speed depends on what your building supports:
        </p>
        <div className="grid gap-1.5">
          <div className="flex gap-2">
            <span className="font-semibold text-foreground whitespace-nowrap">FTTH (1Gbps)</span>
            <span>
              — Fiber directly to your unit. Fastest option, available in newer buildings.
            </span>
          </div>
          <div className="flex gap-2">
            <span className="font-semibold text-foreground whitespace-nowrap">VDSL (100Mbps)</span>
            <span>
              — Fiber to building, then phone line to your unit. Most common in older buildings.
            </span>
          </div>
          <div className="flex gap-2">
            <span className="font-semibold text-foreground whitespace-nowrap">LAN (100Mbps)</span>
            <span>
              — Fiber to building, then ethernet to your unit. Common in some mansion types.
            </span>
          </div>
        </div>
        <p className="text-foreground font-medium pt-0.5">
          Good news: All types have the same monthly price (¥4,800~). We&apos;ll check what&apos;s
          available at your address.
        </p>
      </div>
    </div>
  );
}

function PublicTierCard({ tier }: { tier: TierInfo }) {
  const style = tierStyles[tier.tier];
  return (
    <div
      className={cn(
        "rounded-lg border border-l-4 p-3 transition-all duration-200 flex flex-col relative",
        style.card,
        style.leftBorder
      )}
    >
      {tier.tier === "Gold" && (
        <div className="absolute -top-2.5 left-1/2 -translate-x-1/2">
          <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-amber-500 text-white text-[10px] font-semibold shadow-sm">
            <Sparkles className="h-2.5 w-2.5" />
            Popular
          </span>
        </div>
      )}

      <div className={cn("flex items-center gap-2 mb-2", tier.tier === "Gold" ? "mt-1" : "")}>
        <span className={cn("font-semibold text-xs", style.accent)}>{tier.tier}</span>
      </div>

      <div className="mb-2">
        <span className="text-lg font-bold text-foreground">
          ¥{tier.monthlyPrice.toLocaleString()}
          {tier.maxMonthlyPrice &&
            tier.maxMonthlyPrice > tier.monthlyPrice &&
            `~${tier.maxMonthlyPrice.toLocaleString()}`}
        </span>
        <span className="text-[10px] text-muted-foreground">/mo</span>
        {tier.pricingNote && (
          <span
            className={cn(
              "text-[10px] ml-0.5",
              tier.tier === "Platinum" ? "text-primary" : "text-amber-600"
            )}
          >
            {tier.pricingNote}
          </span>
        )}
      </div>

      <p className="text-[11px] text-muted-foreground mb-2">{tier.description}</p>

      <ul className="space-y-1 flex-grow">
        {tier.features.slice(0, 3).map((feature, index) => (
          <li key={index} className="flex items-start gap-1.5 text-[11px]">
            <Check className="h-3 w-3 text-primary/60 flex-shrink-0 mt-0.5" />
            <span className="text-muted-foreground leading-relaxed">{feature}</span>
          </li>
        ))}
      </ul>
    </div>
  );
}

function PublicOfferingExpanded({
  tiers,
  setupFee,
  showConnectionInfo,
  ctaPath,
  customCtaLabel,
  onCtaClick,
}: {
  tiers: TierInfo[];
  setupFee: number;
  showConnectionInfo: boolean;
  ctaPath: string;
  customCtaLabel: string | undefined;
  onCtaClick: ((e: React.MouseEvent) => void) | undefined;
}) {
  const [showInfo, setShowInfo] = useState(false);

  return (
    <div className="border-t border-border/60 px-4 py-4 bg-muted/5">
      {showConnectionInfo && !showInfo && (
        <button
          type="button"
          onClick={() => setShowInfo(true)}
          className="flex items-center gap-1.5 text-[11px] text-info hover:text-info/80 transition-colors mb-3"
        >
          <Info className="h-3.5 w-3.5" />
          <span>Why does speed vary by building?</span>
        </button>
      )}

      {showConnectionInfo && showInfo && <ConnectionTypeInfo onClose={() => setShowInfo(false)} />}

      <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 mb-4">
        {tiers.map(tier => (
          <PublicTierCard key={tier.tier} tier={tier} />
        ))}
      </div>

      <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3 pt-2.5 border-t border-border/40">
        <p className="text-[11px] text-muted-foreground flex-1">
          <span className="font-semibold text-foreground">
            + ¥{setupFee.toLocaleString()} one-time setup
          </span>{" "}
          (or 12/24-month installment)
        </p>
        {onCtaClick ? (
          <Button as="button" onClick={onCtaClick} size="sm" className="whitespace-nowrap">
            {customCtaLabel ?? "Check availability"}
          </Button>
        ) : (
          <Button as="a" href={ctaPath} size="sm" className="whitespace-nowrap">
            {customCtaLabel ?? "Check availability"}
          </Button>
        )}
      </div>
    </div>
  );
}

function PublicOfferingHeader({
  title,
  speedBadge,
  description,
  iconType,
  startingPrice,
  maxPrice,
  isPremium,
  isExpanded,
  onToggle,
}: {
  title: string;
  speedBadge: string;
  description: string;
  iconType: "home" | "apartment";
  startingPrice: number;
  maxPrice: number | undefined;
  isPremium: boolean;
  isExpanded: boolean;
  onToggle: () => void;
}) {
  const Icon = iconType === "home" ? Home : Building2;

  return (
    <button
      type="button"
      onClick={onToggle}
      className="w-full p-4 flex items-start justify-between gap-3 text-left hover:bg-muted/10 transition-colors"
    >
      <div className="flex items-start gap-3">
        <div
          className={cn(
            "flex h-9 w-9 items-center justify-center rounded-lg flex-shrink-0",
            iconType === "home"
              ? "bg-sky-500/10 text-sky-600"
              : "bg-emerald-500/10 text-emerald-600"
          )}
        >
          <Icon className="h-4.5 w-4.5" />
        </div>

        <div className="space-y-0.5">
          <div className="flex flex-wrap items-center gap-1.5">
            <h3 className="text-sm font-bold text-foreground">{title}</h3>
            <CardBadge text={speedBadge} variant={isPremium ? "new" : "default"} size="sm" />
            {isPremium && <span className="text-[10px] text-muted-foreground">(select areas)</span>}
          </div>
          <p className="text-xs text-muted-foreground">{description}</p>
          <div className="flex items-baseline gap-0.5 pt-0.5">
            <span className="text-[10px] text-muted-foreground">From</span>
            <span className="text-base font-bold text-foreground">
              ¥{startingPrice.toLocaleString()}
              {maxPrice && maxPrice > startingPrice && `~${maxPrice.toLocaleString()}`}
            </span>
            <span className="text-xs text-muted-foreground">/mo</span>
          </div>
        </div>
      </div>

      <div className="flex items-center gap-1 flex-shrink-0 mt-1">
        <span className="text-[10px] text-muted-foreground hidden sm:inline">
          {isExpanded ? "Hide" : "View tiers"}
        </span>
        {isExpanded ? (
          <ChevronUp className="h-4 w-4 text-muted-foreground" />
        ) : (
          <ChevronDown className="h-4 w-4 text-muted-foreground" />
        )}
      </div>
    </button>
  );
}

export function PublicOfferingCard({
  title,
  speedBadge,
  description,
  iconType,
  startingPrice,
  maxPrice,
  setupFee,
  tiers,
  isPremium = false,
  ctaPath,
  defaultExpanded = false,
  showConnectionInfo = false,
  customCtaLabel,
  onCtaClick,
}: PublicOfferingCardProps) {
  const [isExpanded, setIsExpanded] = useState(defaultExpanded);

  return (
    <div
      className={cn(
        "rounded-xl border bg-card overflow-hidden transition-all duration-300",
        isExpanded ? "shadow-md ring-1 ring-primary/15" : "hover:shadow-sm",
        isPremium ? "border-primary/25" : "border-border/60"
      )}
    >
      <div
        className={cn(
          "h-0.5 w-full",
          isPremium
            ? "bg-gradient-to-r from-sky-500 to-blue-600"
            : "bg-gradient-to-r from-sky-400 to-blue-500"
        )}
      />

      <PublicOfferingHeader
        title={title}
        speedBadge={speedBadge}
        description={description}
        iconType={iconType}
        startingPrice={startingPrice}
        maxPrice={maxPrice}
        isPremium={isPremium}
        isExpanded={isExpanded}
        onToggle={() => setIsExpanded(!isExpanded)}
      />

      {isExpanded && (
        <PublicOfferingExpanded
          tiers={tiers}
          setupFee={setupFee}
          showConnectionInfo={showConnectionInfo}
          ctaPath={ctaPath}
          customCtaLabel={customCtaLabel}
          onCtaClick={onCtaClick}
        />
      )}
    </div>
  );
}

export type { PublicOfferingCardProps, TierInfo };
