/**
 * Pro Upgrade Dialog Component
 *
 * Modal dialog that displays Pro features and upgrade CTA.
 * Used when free users click on Pro-only features.
 *
 * @package OpusPriceBuilder
 */

import { forwardRef } from "react";
import * as Dialog from "@radix-ui/react-dialog";
import { Cross2Icon, LockClosedIcon, CheckIcon, RocketIcon, StarIcon } from "@radix-ui/react-icons";
import { motion, AnimatePresence } from "motion/react";

import { getAllProFeatures, getUpgradeUrl, type ProFeature } from "@/utils/license";

interface ProUpgradeDialogProps {
  /** Whether the dialog is open */
  open: boolean;
  /** Called when dialog open state changes */
  onOpenChange: (open: boolean) => void;
  /** The specific feature that triggered the dialog (for highlighting) */
  triggeredBy?: ProFeature;
  /** Custom title (optional) */
  title?: string;
  /** Custom description (optional) */
  description?: string;
}

/**
 * Pro Upgrade Dialog
 *
 * Shows all Pro features with the triggered feature highlighted.
 * Includes upgrade button that links to Freemius checkout.
 */
export function ProUpgradeDialog({
  open,
  onOpenChange,
  triggeredBy,
  title = "Unlock Pro Features",
  description = "Upgrade to Price Builder Pro to access advanced features and take your price displays to the next level.",
}: ProUpgradeDialogProps) {
  const features = getAllProFeatures();
  const upgradeUrl = getUpgradeUrl();

  const handleUpgrade = () => {
    if (upgradeUrl) {
      window.open(upgradeUrl, "_blank");
    }
    onOpenChange(false);
  };

  return (
    <Dialog.Root open={open} onOpenChange={onOpenChange}>
      <Dialog.Portal>
        <Dialog.Overlay className="oppb-dialog-overlay" />
        <Dialog.Content className="oppb-dialog-content oppb-pro-dialog" aria-describedby="pro-dialog-description">
          <AnimatePresence>
            {open && (
              <motion.div
                initial={{ opacity: 0, scale: 0.95 }}
                animate={{ opacity: 1, scale: 1 }}
                exit={{ opacity: 0, scale: 0.95 }}
                transition={{ duration: 0.2 }}
              >
                {/* Header */}
                <div className="oppb-pro-dialog__header">
                  <div className="oppb-pro-dialog__icon">
                    <StarIcon className="w-8 h-8" />
                  </div>
                  <Dialog.Title className="oppb-pro-dialog__title">{title}</Dialog.Title>
                  <Dialog.Description className="oppb-pro-dialog__description" id="pro-dialog-description">
                    {description}
                  </Dialog.Description>
                </div>

                {/* Features List */}
                <div className="oppb-pro-dialog__features">
                  {features.map((feature) => (
                    <div
                      key={feature.id}
                      className={`oppb-pro-dialog__feature ${triggeredBy === feature.id ? "oppb-pro-dialog__feature--highlighted" : ""}`}
                    >
                      <div className="oppb-pro-dialog__feature-icon">
                        <CheckIcon className="w-4 h-4" />
                      </div>
                      <div className="oppb-pro-dialog__feature-content">
                        <h4 className="oppb-pro-dialog__feature-title">{feature.label}</h4>
                        <p className="oppb-pro-dialog__feature-description">{feature.description}</p>
                      </div>
                    </div>
                  ))}
                </div>

                {/* Footer */}
                <div className="oppb-pro-dialog__footer">
                  <button type="button" className="oppb-button-secondary" onClick={() => onOpenChange(false)}>
                    Maybe Later
                  </button>
                  <button type="button" className="oppb-button-pro" onClick={handleUpgrade}>
                    <RocketIcon className="w-4 h-4" />
                    Upgrade to Pro
                  </button>
                </div>

                {/* Close Button */}
                <Dialog.Close asChild>
                  <button className="oppb-dialog-close" aria-label="Close">
                    <Cross2Icon className="w-4 h-4" />
                  </button>
                </Dialog.Close>
              </motion.div>
            )}
          </AnimatePresence>
        </Dialog.Content>
      </Dialog.Portal>
    </Dialog.Root>
  );
}

/**
 * Pro Badge Component
 *
 * Small badge that indicates a feature is Pro-only.
 * Can be used inline with labels or buttons.
 */
interface ProBadgeProps {
  /** Size variant */
  size?: "sm" | "md";
  /** Additional class names */
  className?: string;
}

export function ProBadge({ size = "sm", className = "" }: ProBadgeProps) {
  return (
    <span className={`oppb-pro-badge oppb-pro-badge--${size} ${className}`}>
      <StarIcon className={size === "sm" ? "w-2.5 h-2.5" : "w-3 h-3"} />
      <span>PRO</span>
    </span>
  );
}

/**
 * Pro Feature Gate Component
 *
 * Wraps a feature and shows upgrade dialog if user is not Pro.
 * Renders children normally if user has Pro access.
 */
interface ProFeatureGateProps {
  /** The feature being gated */
  feature: ProFeature;
  /** Whether user has Pro access */
  isPro: boolean;
  /** Children to render (the actual feature) */
  children: React.ReactNode;
  /** Fallback to render when not Pro (optional - defaults to showing badge overlay) */
  fallback?: React.ReactNode;
  /** Dialog open state */
  dialogOpen: boolean;
  /** Called when dialog open state changes */
  onDialogOpenChange: (open: boolean) => void;
  /** Called when the gate is clicked (to open dialog) */
  onGateClick: () => void;
}

export function ProFeatureGate({ feature, isPro, children, fallback, dialogOpen, onDialogOpenChange, onGateClick }: ProFeatureGateProps) {
  if (isPro) {
    return <>{children}</>;
  }

  if (fallback) {
    return (
      <>
        {fallback}
        <ProUpgradeDialog open={dialogOpen} onOpenChange={onDialogOpenChange} triggeredBy={feature} />
      </>
    );
  }

  return (
    <>
      <div className="oppb-pro-gate" onClick={onGateClick}>
        <div className="oppb-pro-gate__content">{children}</div>
        <div className="oppb-pro-gate__overlay">
          <LockClosedIcon className="w-5 h-5" />
          <ProBadge size="md" />
        </div>
      </div>
      <ProUpgradeDialog open={dialogOpen} onOpenChange={onDialogOpenChange} triggeredBy={feature} />
    </>
  );
}

/**
 * Upgrade to Pro Button
 *
 * Button that opens the upgrade dialog.
 * Used in toolbar/footer for free users.
 */
interface UpgradeButtonProps {
  /** Size variant */
  size?: "sm" | "md";
  /** Additional class names */
  className?: string;
}

export function UpgradeButton({ size = "sm", className = "" }: UpgradeButtonProps) {
  const upgradeUrl = getUpgradeUrl();

  const handleClick = () => {
    if (upgradeUrl) {
      window.open(upgradeUrl, "_blank");
    }
  };

  return (
    <button type="button" className={`oppb-upgrade-button oppb-upgrade-button--${size} ${className}`} onClick={handleClick}>
      <RocketIcon className={size === "sm" ? "w-3.5 h-3.5" : "w-4 h-4"} />
      <span>Upgrade to Pro</span>
    </button>
  );
}

export default ProUpgradeDialog;
