"use client";

import { useState } from "react";
import { ChevronDown, Home, Building2, Info, X, Check, Star } 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;
  description: string;
  features: string[];
  pricingNote?: string | undefined;
}

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

const tierStyles = {
  Silver: {
    card: "border-border bg-card",
    accent: "text-muted-foreground",
    badge: "bg-muted text-muted-foreground",
    iconBg: "bg-muted",
  },
  Gold: {
    card: "border-warning/40 bg-gradient-to-br from-warning/5 to-card ring-1 ring-warning/20",
    accent: "text-warning",
    badge: "bg-warning/10 text-warning",
    iconBg: "bg-warning/10",
  },
  Platinum: {
    card: "border-primary/40 bg-gradient-to-br from-primary/5 to-card ring-1 ring-primary/20",
    accent: "text-primary",
    badge: "bg-primary/10 text-primary",
    iconBg: "bg-primary/10",
  },
} as const;

/**
 * Info panel explaining apartment connection types
 */
function ConnectionTypeInfo({ onClose }: { onClose: () => void }) {
  return (
    <div className="bg-info/5 border border-info/20 rounded-xl p-4 mb-4">
      <div className="flex items-start justify-between gap-3 mb-3">
        <div className="flex items-center gap-2">
          <div className="h-8 w-8 rounded-lg bg-info/10 flex items-center justify-center">
            <Info className="h-4 w-4 text-info" />
          </div>
          <h4 className="font-semibold text-sm text-foreground">
            Why does speed vary by building?
          </h4>
        </div>
        <button
          type="button"
          onClick={onClose}
          className="text-muted-foreground hover:text-foreground transition-colors p-1"
        >
          <X className="h-4 w-4" />
        </button>
      </div>
      <div className="space-y-3 text-xs text-muted-foreground pl-10">
        <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-2">
          <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-1">
          Good news: All types have the same monthly price. We&apos;ll check what&apos;s available
          at your address.
        </p>
      </div>
    </div>
  );
}

/**
 * Tier card component
 */
function TierCard({ tier }: { tier: TierInfo }) {
  const styles = tierStyles[tier.tier];
  const isGold = tier.tier === "Gold";

  return (
    <div
      className={cn(
        "rounded-xl border p-4 transition-all duration-200 flex flex-col relative",
        styles.card,
        "hover:-translate-y-0.5 hover:shadow-md"
      )}
    >
      {/* Recommended badge for Gold */}
      {isGold && (
        <div className="absolute -top-2.5 left-4">
          <span className="inline-flex items-center gap-1 text-[10px] font-bold bg-warning text-warning-foreground px-2 py-0.5 rounded-full shadow-sm">
            <Star className="h-3 w-3" fill="currentColor" />
            Popular
          </span>
        </div>
      )}

      {/* Header */}
      <div className="flex items-center justify-between mb-3">
        <span className={cn("font-bold text-sm", styles.accent)}>{tier.tier}</span>
      </div>

      {/* Price */}
      <div className="mb-3">
        <div className="flex items-baseline gap-0.5 flex-wrap">
          <span className="text-2xl font-bold text-foreground">
            ¥{tier.monthlyPrice.toLocaleString()}
          </span>
          <span className="text-sm text-muted-foreground">/mo</span>
        </div>
        {tier.pricingNote && (
          <span className="text-[10px] text-warning font-medium">{tier.pricingNote}</span>
        )}
      </div>

      {/* Description */}
      <p className="text-xs text-muted-foreground mb-3 leading-relaxed">{tier.description}</p>

      {/* Features */}
      <ul className="space-y-2 flex-grow">
        {tier.features.slice(0, 3).map((feature, index) => (
          <li key={index} className="flex items-start gap-2 text-xs">
            <Check className="h-3.5 w-3.5 text-success flex-shrink-0 mt-0.5" />
            <span className="text-muted-foreground leading-relaxed">{feature}</span>
          </li>
        ))}
      </ul>
    </div>
  );
}

/**
 * Public-facing offering card that shows pricing inline
 * No modals - all information is visible or expandable within the card
 */
export function PublicOfferingCard({
  title,
  speedBadge,
  description,
  iconType,
  startingPrice,
  setupFee,
  tiers,
  isPremium = false,
  ctaPath,
  defaultExpanded = false,
  showConnectionInfo = false,
  customCtaLabel,
  onCtaClick,
}: PublicOfferingCardProps) {
  const [isExpanded, setIsExpanded] = useState(defaultExpanded);
  const [showInfo, setShowInfo] = useState(false);

  const Icon = iconType === "home" ? Home : Building2;

  return (
    <div
      className={cn(
        "rounded-2xl border overflow-hidden",
        "transition-all duration-[var(--cp-duration-normal)]",
        "hover:shadow-lg",
        isExpanded ? "shadow-md ring-1 ring-primary/10" : "shadow-sm",
        isPremium
          ? "border-primary/30 bg-gradient-to-r from-primary/5 to-card"
          : "border-border bg-card"
      )}
    >
      {/* Header - Always visible */}
      <button
        type="button"
        onClick={() => setIsExpanded(!isExpanded)}
        className="w-full p-5 flex items-start justify-between gap-4 text-left hover:bg-muted/30 transition-colors"
      >
        <div className="flex items-start gap-4">
          <div
            className={cn(
              "flex h-12 w-12 items-center justify-center rounded-xl border flex-shrink-0",
              "transition-transform duration-[var(--cp-duration-normal)]",
              isExpanded && "scale-105",
              iconType === "home"
                ? "bg-blue-500/10 text-blue-500 border-blue-500/20"
                : "bg-green-500/10 text-green-500 border-green-500/20"
            )}
          >
            <Icon className="h-6 w-6" />
          </div>

          <div className="space-y-1.5">
            <div className="flex flex-wrap items-center gap-2">
              <h3 className="text-lg font-bold text-foreground">{title}</h3>
              <CardBadge text={speedBadge} variant={isPremium ? "new" : "default"} size="sm" />
              {isPremium && <span className="text-xs text-muted-foreground">(select areas)</span>}
            </div>
            <p className="text-sm text-muted-foreground">{description}</p>
            <div className="flex items-baseline gap-1.5 pt-1">
              <span className="text-xs text-muted-foreground">From</span>
              <span className="text-xl font-bold text-foreground">
                ¥{startingPrice.toLocaleString()}
              </span>
              <span className="text-sm text-muted-foreground">/mo</span>
            </div>
          </div>
        </div>

        <div className="flex items-center gap-2 flex-shrink-0 mt-1">
          <span className="text-xs text-muted-foreground hidden sm:inline">
            {isExpanded ? "Hide tiers" : "View tiers"}
          </span>
          <div
            className={cn(
              "h-8 w-8 rounded-lg flex items-center justify-center",
              "bg-muted/50 text-muted-foreground",
              "transition-all duration-[var(--cp-duration-normal)]",
              isExpanded && "bg-primary/10 text-primary rotate-180"
            )}
          >
            <ChevronDown className="h-4 w-4" />
          </div>
        </div>
      </button>

      {/* Expanded content - Tier pricing shown inline */}
      {isExpanded && (
        <div className="border-t border-border px-5 py-5 bg-muted/20">
          {/* Connection type info button (for Apartment) */}
          {showConnectionInfo && !showInfo && (
            <button
              type="button"
              onClick={() => setShowInfo(true)}
              className="flex items-center gap-2 text-xs text-info hover:text-info/80 transition-colors mb-4 group"
            >
              <div className="h-6 w-6 rounded-md bg-info/10 flex items-center justify-center group-hover:bg-info/20 transition-colors">
                <Info className="h-3.5 w-3.5" />
              </div>
              <span>Why does speed vary by building?</span>
            </button>
          )}

          {/* Connection type info panel */}
          {showConnectionInfo && showInfo && (
            <ConnectionTypeInfo onClose={() => setShowInfo(false)} />
          )}

          {/* Tier cards - 3 columns on desktop */}
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-5">
            {tiers.map(tier => (
              <TierCard key={tier.tier} tier={tier} />
            ))}
          </div>

          {/* Footer with setup fee and CTA */}
          <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-4 pt-4 border-t border-border/50">
            <p className="text-sm 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 onClick={onCtaClick} className="whitespace-nowrap">
                {customCtaLabel ?? "Check availability"}
              </Button>
            ) : (
              <Button as="a" href={ctaPath} className="whitespace-nowrap">
                {customCtaLabel ?? "Check availability"}
              </Button>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

export type { PublicOfferingCardProps, TierInfo };
