"use client";

import { useState } from "react";
import { ChevronDown, ChevronUp, Home, Building2, Info, X, Sparkles } 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 tierStyles = {
  Silver: {
    card: "border-gray-200 bg-white border-l-4 border-l-gray-400",
    accent: "text-gray-600",
  },
  Gold: {
    card: "border-gray-200 bg-white border-l-4 border-l-amber-500",
    accent: "text-amber-600",
  },
  Platinum: {
    card: "border-gray-200 bg-white border-l-4 border-l-primary",
    accent: "text-primary",
  },
} as const;

/**
 * Info panel explaining apartment connection types
 */
function ConnectionTypeInfo({ onClose }: { onClose: () => void }) {
  return (
    <div className="bg-info-soft/50 border border-info/20 rounded-lg p-4 mb-4">
      <div className="flex items-start justify-between gap-3 mb-3">
        <div className="flex items-center gap-2">
          <Info className="h-5 w-5 text-info flex-shrink-0" />
          <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"
        >
          <X className="h-4 w-4" />
        </button>
      </div>
      <div className="space-y-3 text-xs 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-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 (¥4,800~). We&apos;ll check what&apos;s
          available at your address.
        </p>
      </div>
    </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,
  maxPrice,
  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-xl border bg-card shadow-[var(--cp-shadow-1)] overflow-hidden transition-all duration-300 hover:shadow-lg hover:-translate-y-0.5",
        isExpanded ? "shadow-[var(--cp-shadow-2)] ring-1 ring-primary/20" : "",
        isPremium ? "border-primary/30" : "border-border"
      )}
    >
      {/* Header - Always visible */}
      <button
        type="button"
        onClick={() => setIsExpanded(!isExpanded)}
        className="w-full p-4 flex items-start justify-between gap-3 text-left hover:bg-muted/20 transition-colors"
      >
        <div className="flex items-start gap-3">
          <div
            className={cn(
              "flex h-10 w-10 items-center justify-center rounded-lg border flex-shrink-0",
              iconType === "home"
                ? "bg-info-soft/50 text-info border-info/20"
                : "bg-success-soft/50 text-success border-success/20"
            )}
          >
            <Icon className="h-5 w-5" />
          </div>

          <div className="space-y-1">
            <div className="flex flex-wrap items-center gap-2">
              <h3 className="text-base 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 pt-0.5">
              <span className="text-xs text-muted-foreground">From</span>
              <span className="text-lg font-bold text-foreground">
                ¥{startingPrice.toLocaleString()}
                {maxPrice && maxPrice > startingPrice && `~${maxPrice.toLocaleString()}`}
              </span>
              <span className="text-sm text-muted-foreground">/mo</span>
            </div>
          </div>
        </div>

        <div className="flex items-center gap-1.5 flex-shrink-0 mt-1">
          <span className="text-xs 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>

      {/* Expanded content - Tier pricing shown inline */}
      {isExpanded && (
        <div className="border-t border-border px-4 py-4 bg-muted/10">
          {/* Connection type info button (for Apartment) */}
          {showConnectionInfo && !showInfo && (
            <button
              type="button"
              onClick={() => setShowInfo(true)}
              className="flex items-center gap-1.5 text-xs text-info hover:text-info/80 transition-colors mb-3"
            >
              <Info className="h-4 w-4" />
              <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-3 mb-4">
            {tiers.map(tier => (
              <div
                key={tier.tier}
                className={cn(
                  "rounded-lg border p-3 transition-all duration-200 flex flex-col relative",
                  tierStyles[tier.tier].card
                )}
              >
                {/* Popular Badge for Gold */}
                {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>
                )}

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

                {/* Price - Always visible */}
                <div className="mb-2">
                  <div className="flex items-baseline gap-0.5 flex-wrap">
                    <span className="text-xl font-bold text-foreground">
                      ¥{tier.monthlyPrice.toLocaleString()}
                      {tier.maxMonthlyPrice &&
                        tier.maxMonthlyPrice > tier.monthlyPrice &&
                        `~${tier.maxMonthlyPrice.toLocaleString()}`}
                    </span>
                    <span className="text-xs text-muted-foreground">/mo</span>
                    {tier.pricingNote && (
                      <span
                        className={`text-[10px] ml-1 ${tier.tier === "Platinum" ? "text-primary" : "text-amber-600"}`}
                      >
                        {tier.pricingNote}
                      </span>
                    )}
                  </div>
                </div>

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

                {/* Features */}
                <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-xs">
                      <svg
                        className="h-3 w-3 text-gray-500 flex-shrink-0 mt-0.5"
                        viewBox="0 0 20 20"
                        fill="currentColor"
                      >
                        <path
                          fillRule="evenodd"
                          d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
                          clipRule="evenodd"
                        />
                      </svg>
                      <span className="text-muted-foreground leading-relaxed">{feature}</span>
                    </li>
                  ))}
                </ul>
              </div>
            ))}
          </div>

          {/* Footer with setup fee and CTA */}
          <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3 pt-3 border-t border-border/50">
            <p className="text-xs 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>
      )}
    </div>
  );
}

export type { PublicOfferingCardProps, TierInfo };
