"use client";

import { Home, Building2, 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";
  planSku: string;
  monthlyPrice: number;
  description: string;
  features: string[];
  recommended?: boolean | undefined;
  pricingNote?: string | undefined;
}

interface InternetOfferingCardProps {
  offeringType: string;
  title: string;
  speedBadge: string;
  description: string;
  iconType: "home" | "apartment";
  startingPrice: number;
  setupFee: number;
  tiers: TierInfo[];
  isPremium?: boolean | undefined;
  ctaPath: string;
  // defaultExpanded is no longer used but kept for prop compatibility if needed upstream
  defaultExpanded?: boolean | undefined;
  disabled?: boolean | undefined;
  disabledReason?: string | undefined;
  previewMode?: boolean | undefined;
}

const tierStyles = {
  Silver: {
    card: "border-border/60 bg-card",
    accent: "text-muted-foreground",
    stripe: "bg-gradient-to-r from-slate-400 to-slate-500",
    badge: "bg-slate-100 text-slate-600",
  },
  Gold: {
    card: "border-warning/25 bg-warning-soft/10",
    accent: "text-warning",
    stripe: "bg-gradient-to-r from-amber-400 to-yellow-500",
    badge: "bg-amber-50 text-amber-700",
  },
  Platinum: {
    card: "border-primary/25 bg-info-soft/10",
    accent: "text-primary",
    stripe: "bg-gradient-to-r from-sky-500 to-blue-600",
    badge: "bg-sky-50 text-sky-700",
  },
} as const;

function TierCardAction({
  previewMode,
  disabled,
  disabledReason,
  ctaPath,
  planSku,
  recommended,
}: {
  previewMode: boolean;
  disabled: boolean;
  disabledReason: string | undefined;
  ctaPath: string;
  planSku: string;
  recommended: boolean | undefined;
}) {
  const resolveTierHref = (basePath: string, sku: string): string => {
    const joiner = basePath.includes("?") ? "&" : "?";
    return `${basePath}${joiner}planSku=${encodeURIComponent(sku)}`;
  };

  if (previewMode) {
    return (
      <div className="mt-auto pt-2 border-t border-border/40">
        <p className="text-[10px] text-muted-foreground text-center">
          See pricing after verification
        </p>
      </div>
    );
  }

  if (disabled) {
    return (
      <div className="mt-auto">
        <Button variant="outline" size="sm" className="w-full" disabled>
          Unavailable
        </Button>
        {disabledReason && (
          <p className="text-[10px] text-muted-foreground text-center mt-1">{disabledReason}</p>
        )}
      </div>
    );
  }

  return (
    <Button
      as="a"
      href={resolveTierHref(ctaPath, planSku)}
      variant={recommended ? "default" : "outline"}
      size="sm"
      className="w-full mt-auto"
    >
      Select
    </Button>
  );
}

function TierCard({
  tier,
  previewMode,
  disabled,
  disabledReason,
  ctaPath,
}: {
  tier: TierInfo;
  previewMode: boolean;
  disabled: boolean;
  disabledReason: string | undefined;
  ctaPath: string;
}) {
  const style = tierStyles[tier.tier];

  return (
    <div
      className={cn(
        "rounded-lg border p-3 transition-all flex flex-col relative overflow-hidden",
        style.card,
        tier.recommended && "ring-1 ring-warning/25"
      )}
    >
      <div className={cn("absolute top-0 left-0 right-0 h-px", style.stripe)} />

      <div className="flex items-center gap-1.5 mb-2">
        <span className={cn("font-semibold text-xs", style.accent)}>{tier.tier}</span>
        {tier.recommended && <CardBadge text="Recommended" variant="recommended" size="xs" />}
      </div>

      {!previewMode && (
        <div className="mb-2">
          <div className="flex items-baseline gap-0.5 flex-wrap">
            <span className="text-lg font-bold text-foreground">
              ¥{tier.monthlyPrice.toLocaleString()}
            </span>
            <span className="text-[10px] text-muted-foreground">/mo</span>
            {tier.pricingNote && (
              <span className="text-[10px] text-warning ml-1">{tier.pricingNote}</span>
            )}
          </div>
        </div>
      )}

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

      <ul className="space-y-1 flex-grow mb-3">
        {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>

      <TierCardAction
        previewMode={previewMode}
        disabled={disabled}
        disabledReason={disabledReason}
        ctaPath={ctaPath}
        planSku={tier.planSku}
        recommended={tier.recommended}
      />
    </div>
  );
}

export function InternetOfferingCard({
  title,
  speedBadge,
  description,
  iconType,
  startingPrice,
  setupFee,
  tiers,
  isPremium = false,
  ctaPath,
  disabled = false,
  disabledReason,
  previewMode = false,
}: InternetOfferingCardProps) {
  const Icon = iconType === "home" ? Home : Building2;

  return (
    <div
      className={cn(
        "rounded-xl border bg-card overflow-hidden",
        isPremium ? "border-primary/25 shadow-sm" : "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"
        )}
      />

      <div className="w-full p-4 flex items-start justify-between gap-3 text-left">
        <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()}
              </span>
              <span className="text-xs text-muted-foreground">/mo</span>
              <span className="text-[10px] text-muted-foreground ml-1">
                + ¥{setupFee.toLocaleString()} setup
              </span>
            </div>
          </div>
        </div>
      </div>

      <div className="border-t border-border/60 px-4 py-4 bg-muted/5">
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
          {tiers.map(tier => (
            <TierCard
              key={tier.tier}
              tier={tier}
              previewMode={previewMode}
              disabled={disabled}
              disabledReason={disabledReason}
              ctaPath={ctaPath}
            />
          ))}
        </div>

        <p className="text-[11px] text-muted-foreground text-center mt-3 pt-2.5 border-t border-border/40">
          + ¥{setupFee.toLocaleString()} one-time installation (or 12/24-month installment)
        </p>
      </div>
    </div>
  );
}

export type { InternetOfferingCardProps, TierInfo };
