import { useEffect, useState, type CSSProperties } from "react"
import type { SubscriptionCustomization } from "./customization-tab"

export type SubscriptionPreviewMode = "single" | "plans" | "buy-once"

interface SubscriptionPreviewProps {
  settings: {
    button_text: string
    buy_now_subscribe_label: string
    buy_now_one_time_label: string
    buy_now_toggle_style: string
    buy_now_normal_bg: string
    buy_now_normal_text: string
    buy_now_normal_border: string
    buy_now_hover_bg: string
    buy_now_hover_text: string
    buy_now_hover_border: string
    buy_now_active_bg: string
    buy_now_active_text: string
    buy_now_active_border: string
    buy_now_border_radius: number
  }
  customization: SubscriptionCustomization
  isPro: boolean
  mode: SubscriptionPreviewMode
}

type SubscriptionPreviewStyle = CSSProperties & Record<`--swift-commerce-subscription-${string}`, string>

function formatLabel(template: string, replacements: Record<string, string>) {
  return Object.entries(replacements).reduce(
    (label, [token, value]) => label.replace(token, value),
    template,
  )
}

export function SubscriptionPreview({
  settings,
  customization,
  isPro,
  mode,
}: SubscriptionPreviewProps) {
  const [selectedPlan, setSelectedPlan] = useState(0)
  const [purchaseMode, setPurchaseMode] = useState<"subscription" | "one-time">("subscription")
  const isOutline = customization.buttonStyle === "outline"
  const style: SubscriptionPreviewStyle = {
    "--swift-commerce-subscription-button-background": isOutline
      ? "transparent"
      : customization.buttonBgColor,
    "--swift-commerce-subscription-button-color": isOutline
      ? customization.buttonBgColor
      : customization.buttonTextColor,
    "--swift-commerce-subscription-button-border-color": customization.buttonBgColor,
    "--swift-commerce-subscription-button-border-width": isOutline ? "2px" : "1px",
    "--swift-commerce-subscription-button-radius": `${customization.buttonBorderRadius}px`,
    "--swift-commerce-subscription-button-font-size": `${customization.buttonFontSize}px`,
    "--swift-commerce-subscription-button-font-weight": customization.buttonFontWeight,
    "--swift-commerce-subscription-button-padding-block": `${customization.buttonPadding}px`,
    "--swift-commerce-subscription-button-padding-inline": `${customization.buttonPadding * 2}px`,
    "--swift-commerce-subscription-button-width":
      customization.buttonWidth === "full" ? "100%" : "max-content",
    "--swift-commerce-subscription-price-color": customization.priceColor,
    "--swift-commerce-subscription-price-size": `${customization.priceFontSize}px`,
    "--swift-commerce-subscription-period-color": customization.periodColor,
    "--swift-commerce-subscription-period-size": `${customization.periodFontSize}px`,
    "--swift-commerce-subscription-fee-color": customization.signUpFeeColor,
    "--swift-commerce-subscription-fee-size": `${customization.signUpFeeFontSize}px`,
    "--swift-commerce-subscription-trial-color": customization.trialColor,
    "--swift-commerce-subscription-trial-size": `${customization.trialFontSize}px`,
    "--swift-commerce-subscription-surface": customization.containerBgColor,
    "--swift-commerce-subscription-border": customization.containerBorderColor,
    "--swift-commerce-subscription-radius": `${customization.containerBorderRadius}px`,
    "--swift-commerce-subscription-padding": `${customization.containerPadding}px`,
    "--swift-commerce-subscription-fee-display": customization.showSignUpFee ? "block" : "none",
    "--swift-commerce-subscription-trial-display": customization.showTrialText ? "block" : "none",
    "--swift-commerce-subscription-font-family":
      customization.fontFamily || "var(--swift-commerce-font-family)",
    "--swift-commerce-subscription-buy-now-normal-background": settings.buy_now_normal_bg,
    "--swift-commerce-subscription-buy-now-normal-color": settings.buy_now_normal_text,
    "--swift-commerce-subscription-buy-now-normal-border": settings.buy_now_normal_border,
    "--swift-commerce-subscription-buy-now-hover-background": settings.buy_now_hover_bg,
    "--swift-commerce-subscription-buy-now-hover-color": settings.buy_now_hover_text,
    "--swift-commerce-subscription-buy-now-hover-border": settings.buy_now_hover_border,
    "--swift-commerce-subscription-buy-now-active-background": settings.buy_now_active_bg,
    "--swift-commerce-subscription-buy-now-active-color": settings.buy_now_active_text,
    "--swift-commerce-subscription-buy-now-active-border": settings.buy_now_active_border,
    "--swift-commerce-subscription-buy-now-radius": `${settings.buy_now_border_radius}px`,
  }

  const signUpFee = formatLabel(customization.signUpFeeLabel, { "%s": "$50.00" })
  const trial = formatLabel(customization.trialLabel, {
    "%1$d": "7",
    "%2$s": "days",
  })
  const plans = [
    { name: "Monthly", price: "$29.99", period: " / month" },
    { name: "Quarterly", price: "$79.00", period: " / 3 months" },
    { name: "Annual", price: "$299.00", period: " / year", fee: "+ $20.00 sign-up fee" },
  ]
  const selectedPlanDetails = plans[selectedPlan]
  const hasBuyOnce = isPro && (mode === "buy-once" || mode === "plans")

  useEffect(() => {
    setPurchaseMode("subscription")
  }, [mode])

  const purchaseButton = (
    <button
      type="button"
      className="swift-commerce-button single_add_to_cart_button button alt"
    >
      {purchaseMode === "one-time" ? "Buy Now" : settings.button_text || "Sign Up Now"}
    </button>
  )

  const buyOnceSelector = hasBuyOnce ? (
    <div
      className="swift-commerce-subscription-buy-now"
      data-style={settings.buy_now_toggle_style}
    >
      <div
        className="swift-commerce-subscription-buy-now__options"
        role="group"
        aria-label="Purchase option"
      >
        <button
          type="button"
          className={`swift-commerce-subscription-buy-now__option${
            purchaseMode === "subscription" ? " is-active" : ""
          }`}
          aria-pressed={purchaseMode === "subscription"}
          onClick={() => setPurchaseMode("subscription")}
        >
          {settings.buy_now_subscribe_label || "Subscribe & Save"}
          <span className="swift-commerce-subscription-buy-now__price">
            {mode === "plans"
              ? `${selectedPlanDetails.price}${selectedPlanDetails.period}`
              : "$29.99 / month"}
          </span>
        </button>
        <button
          type="button"
          className={`swift-commerce-subscription-buy-now__option${
            purchaseMode === "one-time" ? " is-active" : ""
          }`}
          aria-pressed={purchaseMode === "one-time"}
          onClick={() => setPurchaseMode("one-time")}
        >
          {settings.buy_now_one_time_label || "Buy Once"}
          <span className="swift-commerce-subscription-buy-now__price">$349.00</span>
        </button>
      </div>
    </div>
  ) : null

  return (
    <div className="swift-commerce-subscription-preview" style={style}>
      {mode !== "single" ? (
        <form
          className="swift-commerce-ui swift-commerce-subscription-scope swift-commerce-subscription-purchase swift-commerce-subscription-plans cart"
          data-layout={customization.layout}
          data-alignment={customization.priceAlignment}
          data-plan-count={mode === "plans" ? plans.length : 1}
          data-purchase-mode={purchaseMode}
          onSubmit={(event) => event.preventDefault()}
        >
          {buyOnceSelector}
          {mode === "plans" && (
            <div
              className="swift-commerce-subscription-plans__options"
              hidden={purchaseMode === "one-time"}
            >
              <h4 className="swift-commerce-heading swift-commerce-subscription-plans__heading">
                Choose your plan
              </h4>
              {plans.map((plan, index) => (
                <label
                  key={plan.name}
                  className={`swift-commerce-surface swift-commerce-subscription-plan${
                    selectedPlan === index ? " is-selected" : ""
                  }`}
                >
                  <input
                    type="radio"
                    className="swift-commerce-radio"
                    name="swift-commerce-subscription-preview-plan"
                    checked={selectedPlan === index}
                    onChange={() => setSelectedPlan(index)}
                  />
                  <span className="swift-commerce-subscription-plan__details">
                    <span className="swift-commerce-subscription-plan__name">{plan.name}</span>
                    <span className="swift-commerce-price swift-commerce-subscription-plan__price">
                      {plan.price}
                      <span className="swift-commerce-subscription-plan__period">{plan.period}</span>
                    </span>
                    {plan.fee && (
                      <span className="swift-commerce-subscription-plan__fee">{plan.fee}</span>
                    )}
                  </span>
                </label>
              ))}
            </div>
          )}
          {purchaseButton}
        </form>
      ) : (
        <div
          className="swift-commerce-ui swift-commerce-subscription-scope swift-commerce-subscription-purchase"
          data-layout={customization.layout}
          data-alignment={customization.priceAlignment}
        >
          <div className="swift-commerce-price price swift-commerce-subscription-purchase__price">
            <span className="woocommerce-Price-amount amount">
              <bdi>
                <span className="woocommerce-Price-currencySymbol">$</span>
                29.99
              </bdi>
            </span>
            <span className="swift-commerce-subscription-price__period">
              {" "}
              {customization.periodSeparator.trim()} month
            </span>
            <br />
            <small className="swift-commerce-subscription-price__signup-fee">{signUpFee}</small>
            <small className="swift-commerce-subscription-price__trial">{trial}</small>
          </div>

          <div className="cart swift-commerce-subscription-purchase__form">
            {purchaseButton}
          </div>
        </div>
      )}
    </div>
  )
}
