import React from 'react';

import { Spinner } from '../ui/Spinner';
import { LAUNCH_DISCOUNT_PERCENT } from '../launch-discount/plans';
import { PlanType } from '../../utils/plan';

/** Credits-tier presentation copy for a single plan. */
export interface ICreditTier {
  eyebrow: string;
  pricePrefix?: string;
  priceLabel: string;
  credits: string;
  description: string;
  audience: string;
  adds?: string;
}

interface PlanCardProps {
  planKey: PlanType;
  planName: string;
  monthly: number;
  priceId: string;
  isPopular: boolean;
  isFreePlan: boolean;
  isHyperScaling: boolean;
  isEnterprise: boolean;
  currentByTrial: boolean;
  currentPaid: boolean;
  isCurrentFree: boolean;
  showCurrentTag: boolean;
  ctaLabel: string;
  ctaDisabled: boolean;
  isLoadingThisPlan: boolean;
  isFreeTrialActive: boolean;
  launchTrial?: boolean;
  billingLabel: string;
  stripeSubscriptionStatus: string;
  tier?: ICreditTier;
  contactUrl?: string;
  onInitializePayment: (priceId: string, planKey: PlanType) => void;
  primaryBtn: string;
  secondaryBtn: string;
}

const formatUSD = (amount: number) =>
  new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
    maximumFractionDigits: amount % 1 === 0 ? 0 : 2,
  }).format(amount);

export const PlanCard: React.FC<PlanCardProps> = ({
  planKey,
  planName,
  monthly,
  priceId,
  isPopular,
  isFreePlan,
  isHyperScaling,
  isEnterprise,
  currentByTrial,
  currentPaid,
  isCurrentFree,
  showCurrentTag,
  ctaLabel,
  ctaDisabled,
  isLoadingThisPlan,
  isFreeTrialActive,
  launchTrial = false,
  billingLabel,
  stripeSubscriptionStatus,
  tier,
  contactUrl = 'https://recomaze.ai/contact/',
  onInitializePayment,
  primaryBtn,
  secondaryBtn,
}) => {
  const cardTone = showCurrentTag
    ? 'ring-2 ring-emerald-500'
    : 'ring-1 ring-gray-200';

  const accentTone =
    isHyperScaling && !showCurrentTag
      ? 'bg-gradient-to-b from-indigo-50 to-white ring-indigo-200'
      : isPopular && !currentPaid && !isCurrentFree && !currentByTrial
        ? 'bg-white ring-gray-900/20'
        : 'bg-white ring-gray-200';

  const priceLabel =
    tier?.priceLabel ?? (isFreePlan ? 'Free' : formatUSD(monthly));

  return (
    <div className="p-0">
      <div
        className={[
          'relative h-full rounded-xl transition-shadow shadow-sm hover:shadow-md',
          'ring-1',
          accentTone,
          cardTone,
        ].join(' ')}
      >
        <div className="absolute -top-3 left-1/2 -translate-x-1/2 z-[1] flex gap-2">
          {currentByTrial && (
            <div className="inline-flex items-center rounded-full bg-emerald-600 text-white text-xs font-semibold px-3 py-1 whitespace-nowrap">
              FREE TRIAL • Hyper Scaling
            </div>
          )}
          {!currentByTrial && isPopular && !currentPaid && !isCurrentFree && (
            <div className="inline-flex items-center rounded-full bg-gray-900 text-white text-xs font-semibold px-3 py-1 whitespace-nowrap">
              MOST POPULAR
            </div>
          )}
          {!currentByTrial && (currentPaid || isCurrentFree) && (
            <div className="inline-flex items-center rounded-full bg-emerald-600 text-white text-xs font-semibold px-3 py-1 whitespace-nowrap">
              {`CURRENT • ${
                isCurrentFree ? 'Free' : billingLabel || 'Monthly'
              }`}
            </div>
          )}
        </div>

        <div className="p-6 lg:p-7 space-y-4">
          <div className="flex items-center justify-between gap-2">
            <p
              className={[
                'text-xs font-semibold uppercase tracking-wider',
                isPopular ? 'text-[#B7007C]' : 'text-gray-500',
              ].join(' ')}
            >
              {tier?.eyebrow ?? planName}
            </p>
            {isEnterprise && (
              <span className="rounded-full border border-gray-200 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-gray-500">
                Enterprise
              </span>
            )}
          </div>

          {launchTrial && showCurrentTag ? (
            <div>
              <div className="flex items-baseline gap-1.5">
                <span className="text-lg font-semibold text-gray-900">
                  {formatUSD(monthly * (1 - LAUNCH_DISCOUNT_PERCENT / 100))}
                </span>
                <span className="text-xs text-gray-500">first month</span>
              </div>
              <p className="mt-0.5 text-xs text-emerald-600">
                {LAUNCH_DISCOUNT_PERCENT}% off · then {formatUSD(monthly)}/mo
              </p>
            </div>
          ) : (
            <div className="flex items-baseline gap-1.5">
              {tier?.pricePrefix && (
                <span className="text-xs text-gray-500">
                  {tier.pricePrefix}
                </span>
              )}
              <span className="text-lg font-semibold text-gray-900">
                {priceLabel}
              </span>
              <span className="text-xs text-gray-500">/mo</span>
            </div>
          )}

          {tier && (
            <div className="space-y-3">
              <div>
                <p
                  className={[
                    'text-4xl font-bold tracking-tight',
                    isPopular ? 'text-[#B7007C]' : 'text-gray-900',
                  ].join(' ')}
                >
                  {tier.credits}
                </p>
                <p className="mt-1 text-[11px] font-semibold uppercase tracking-wider text-gray-500">
                  Credits / month
                </p>
              </div>
              <p className="text-sm leading-relaxed text-gray-600">
                {tier.description}
              </p>
              <p className="text-xs leading-relaxed text-gray-400">
                {tier.audience}
              </p>
              {tier.adds && (
                <div>
                  <p className="text-[10px] font-semibold uppercase tracking-wider text-gray-400">
                    Adds
                  </p>
                  <p className="mt-1 text-sm leading-relaxed text-gray-600">
                    {tier.adds}
                  </p>
                </div>
              )}
            </div>
          )}

          <div className="mt-3">
            {isEnterprise ? (
              <a
                href={contactUrl}
                target="_blank"
                rel="noopener noreferrer"
                className={secondaryBtn}
              >
                {ctaLabel || 'Contact Sales'}
              </a>
            ) : isFreePlan ? (
              <button className={secondaryBtn} disabled>
                {ctaLabel || 'Included'}
              </button>
            ) : ctaDisabled && stripeSubscriptionStatus !== 'canceled' ? (
              <button className={primaryBtn} disabled>
                {ctaLabel}
              </button>
            ) : (
              <button
                className={primaryBtn}
                onClick={() => {
                  onInitializePayment(priceId, planKey);
                }}
                disabled={isLoadingThisPlan}
              >
                {isLoadingThisPlan ? (
                  <>
                    <Spinner className="h-4 w-4" />
                    Processing…
                  </>
                ) : (
                  ctaLabel
                )}
              </button>
            )}

            {isFreeTrialActive && planKey === PlanType.HYPER_SCALING && (
              <p className="pt-2 text-xs text-gray-500">
                Hyper Scaling is enabled during your free trial. Choose any plan
                to continue after your trial ends.
              </p>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};
