"use client";

import { ReactNode } from "react";
import { CurrencyYenIcon, InformationCircleIcon } from "@heroicons/react/24/outline";
import { Formatting } from "@customer-portal/domain/toolkit";
import type { PricingTier } from "@customer-portal/domain/services";

const { formatCurrency } = Formatting;

export interface PricingDisplayProps {
  // Single price mode
  monthlyPrice?: number;
  oneTimePrice?: number;
  originalMonthlyPrice?: number; // For discounts
  originalOneTimePrice?: number;

  // Multi-tier mode
  tiers?: PricingTier[];

  // Currency and formatting
  currency?: "JPY" | "USD";
  showCurrencySymbol?: boolean;

  // Features
  features?: string[];

  // Styling
  variant?: "simple" | "detailed" | "comparison";
  size?: "sm" | "md" | "lg";
  alignment?: "left" | "center" | "right";

  // Additional info
  disclaimer?: string;
  infoText?: string;
  children?: ReactNode;
}

const ALIGNMENT_CLASSES = {
  left: "text-left",
  center: "text-center",
  right: "text-right",
};

const SIZE_CLASSES = {
  sm: { price: "text-lg", currency: "h-4 w-4", label: "text-xs" },
  md: { price: "text-2xl", currency: "h-5 w-5", label: "text-sm" },
  lg: { price: "text-3xl", currency: "h-6 w-6", label: "text-base" },
};

function CurrencyIcon({
  currency,
  showCurrencySymbol,
}: {
  currency: string;
  showCurrencySymbol: boolean;
}) {
  if (!showCurrencySymbol) return null;
  return currency === "JPY" ? <CurrencyYenIcon className="h-5 w-5" /> : <span>$</span>;
}

function PriceWithDiscount({
  price,
  originalPrice,
  sizeKey,
  colorClass,
  periodLabel,
  getCurrencyIcon,
}: {
  price: number;
  originalPrice: number | undefined;
  sizeKey: keyof typeof SIZE_CLASSES;
  colorClass: string;
  periodLabel: string;
  getCurrencyIcon: () => ReactNode;
}) {
  const sizes = SIZE_CLASSES[sizeKey];
  const hasDiscount = originalPrice && originalPrice > price;

  return (
    <div className="mb-4">
      <div className="flex items-baseline gap-1">
        {getCurrencyIcon()}
        <span className={`font-bold ${colorClass} ${sizes.price}`}>{formatCurrency(price)}</span>
        <span className={`text-muted-foreground ${sizes.label}`}>{periodLabel}</span>
      </div>
      {hasDiscount && (
        <div className="flex items-baseline gap-1 mt-1">
          <span className="text-muted-foreground/60 line-through text-sm">
            ¥{formatCurrency(originalPrice)}
          </span>
          <span className="text-green-600 text-sm font-medium">
            Save ¥{formatCurrency(originalPrice - price)}
            {periodLabel === "/month" ? "/month" : ""}
          </span>
        </div>
      )}
    </div>
  );
}

function TierCard({
  tier,
  size,
  getCurrencyIcon,
}: {
  tier: PricingTier;
  size: keyof typeof SIZE_CLASSES;
  getCurrencyIcon: () => ReactNode;
}) {
  const sizes = SIZE_CLASSES[size];
  return (
    <div
      className={`border rounded-lg p-6 ${
        tier.isRecommended
          ? "border-blue-500 ring-2 ring-blue-100 bg-blue-50"
          : "border-border bg-card"
      }`}
    >
      {tier.isRecommended && (
        <div className="text-center mb-4">
          <span className="bg-blue-500 text-white px-3 py-1 rounded-full text-sm font-medium">
            Recommended
          </span>
        </div>
      )}

      <div className="text-center mb-4">
        <h3 className="text-lg font-semibold text-foreground mb-2">{tier.name}</h3>
        <div className="flex items-baseline justify-center gap-1">
          {getCurrencyIcon()}
          <span className={`font-bold text-foreground ${sizes.price}`}>
            {formatCurrency(tier.price)}
          </span>
          <span className={`text-muted-foreground ${sizes.label}`}>
            /{tier.billingCycle.toLowerCase()}
          </span>
        </div>
        {tier.description && (
          <p className="text-muted-foreground text-sm mt-2">{tier.description}</p>
        )}
      </div>

      {tier.features && tier.features.length > 0 && (
        <ul className="space-y-2 text-sm text-foreground">
          {tier.features.map((feature, featureIndex) => (
            <li key={featureIndex} className="flex items-start">
              <span className="text-green-600 mr-2">✓</span>
              {feature}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

function FeaturesList({ features }: { features: string[] }) {
  if (features.length === 0) return null;
  return (
    <div className="mb-4">
      <h4 className="font-medium text-foreground mb-2">Included:</h4>
      <ul className="space-y-1 text-sm text-foreground">
        {features.map((feature, index) => (
          <li key={index} className="flex items-start">
            <span className="text-green-600 mr-2">✓</span>
            {feature}
          </li>
        ))}
      </ul>
    </div>
  );
}

function DetailedPricing({
  monthlyPrice,
  oneTimePrice,
  originalMonthlyPrice,
  originalOneTimePrice,
  features,
  size,
  getCurrencyIcon,
  children,
}: {
  monthlyPrice: number | undefined;
  oneTimePrice: number | undefined;
  originalMonthlyPrice: number | undefined;
  originalOneTimePrice: number | undefined;
  features: string[];
  size: keyof typeof SIZE_CLASSES;
  getCurrencyIcon: () => ReactNode;
  children: ReactNode | undefined;
}) {
  return (
    <div className="bg-card border border-border rounded-lg p-6">
      <h3 className="text-lg font-semibold text-foreground mb-4">Pricing</h3>
      {monthlyPrice && (
        <PriceWithDiscount
          price={monthlyPrice}
          originalPrice={originalMonthlyPrice}
          sizeKey={size}
          colorClass="text-foreground"
          periodLabel="/month"
          getCurrencyIcon={getCurrencyIcon}
        />
      )}
      {oneTimePrice && (
        <PriceWithDiscount
          price={oneTimePrice}
          originalPrice={originalOneTimePrice}
          sizeKey={size}
          colorClass="text-orange-600"
          periodLabel="one-time"
          getCurrencyIcon={getCurrencyIcon}
        />
      )}
      <FeaturesList features={features} />
      {children}
    </div>
  );
}

function SimplePricing({
  monthlyPrice,
  oneTimePrice,
  size,
  getCurrencyIcon,
  children,
}: {
  monthlyPrice: number | undefined;
  oneTimePrice: number | undefined;
  size: keyof typeof SIZE_CLASSES;
  getCurrencyIcon: () => ReactNode;
  children: ReactNode | undefined;
}) {
  const sizes = SIZE_CLASSES[size];
  return (
    <div>
      {monthlyPrice && (
        <div className="flex items-baseline gap-1 mb-2">
          {getCurrencyIcon()}
          <span className={`font-bold text-foreground ${sizes.price}`}>
            {formatCurrency(monthlyPrice)}
          </span>
          <span className={`text-muted-foreground ${sizes.label}`}>/month</span>
        </div>
      )}
      {oneTimePrice && (
        <div className="flex items-baseline gap-1">
          {getCurrencyIcon()}
          <span className={`font-bold text-orange-600 ${sizes.price}`}>
            {formatCurrency(oneTimePrice)}
          </span>
          <span className={`text-orange-500 ${sizes.label}`}>one-time</span>
        </div>
      )}
      {children}
    </div>
  );
}

export function PricingDisplay({
  monthlyPrice,
  oneTimePrice,
  originalMonthlyPrice,
  originalOneTimePrice,
  tiers,
  currency = "JPY",
  showCurrencySymbol = true,
  features = [],
  variant = "simple",
  size = "md",
  alignment = "left",
  disclaimer,
  infoText,
  children,
}: PricingDisplayProps) {
  const getCurrencyIcon = () => (
    <CurrencyIcon currency={currency} showCurrencySymbol={showCurrencySymbol} />
  );

  if (tiers && tiers.length > 0) {
    return (
      <div className={ALIGNMENT_CLASSES[alignment]}>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {tiers.map((tier, index) => (
            <TierCard key={index} tier={tier} size={size} getCurrencyIcon={getCurrencyIcon} />
          ))}
        </div>

        {disclaimer && (
          <div className="mt-6 p-4 bg-muted rounded-lg">
            <div className="flex items-start gap-2">
              <InformationCircleIcon className="h-5 w-5 text-muted-foreground flex-shrink-0 mt-0.5" />
              <p className="text-sm text-muted-foreground">{disclaimer}</p>
            </div>
          </div>
        )}
      </div>
    );
  }

  return (
    <div className={ALIGNMENT_CLASSES[alignment]}>
      {variant === "detailed" && (
        <DetailedPricing
          monthlyPrice={monthlyPrice}
          oneTimePrice={oneTimePrice}
          originalMonthlyPrice={originalMonthlyPrice}
          originalOneTimePrice={originalOneTimePrice}
          features={features}
          size={size}
          getCurrencyIcon={getCurrencyIcon}
        >
          {children}
        </DetailedPricing>
      )}

      {variant === "simple" && (
        <SimplePricing
          monthlyPrice={monthlyPrice}
          oneTimePrice={oneTimePrice}
          size={size}
          getCurrencyIcon={getCurrencyIcon}
        >
          {children}
        </SimplePricing>
      )}

      {infoText && (
        <div className="mt-4 p-3 bg-blue-50 rounded-lg">
          <div className="flex items-start gap-2">
            <InformationCircleIcon className="h-5 w-5 text-blue-500 flex-shrink-0 mt-0.5" />
            <p className="text-sm text-blue-700">{infoText}</p>
          </div>
        </div>
      )}

      {disclaimer && (
        <div className="mt-4 p-3 bg-muted rounded-lg">
          <p className="text-xs text-muted-foreground">{disclaimer}</p>
        </div>
      )}
    </div>
  );
}
