// @design-system: domain/DealCTA

'use client';

import { useState, useCallback } from 'react';
import { cn } from '@/lib/cn';
import { useT } from '@/lib/i18n/react';
import { useCartDrawerStore } from '@/features/cart/cartDrawerStore';
import { ToastProvider, ToastViewport, Toast } from '@/components/ui/overlays/Toast';
import { BuyButton } from './BuyButton';
import { AddToCartButton } from './AddToCartButton';
import type { DealType } from '@/lib/deal-types';

/** Minimal deal shape needed by DealCTA */
export interface DealCTADeal {
  id: string;
  title: string;
  /** Optional — not all surfaces have vendorName readily available */
  vendorName?: string;
  discountedPrice: number;
  imageSrc?: string;
  hasAxes?: boolean;
  defaultSkuId?: string | null;
  heSlug?: string;
  dealType?: DealType;
}

/** CTA display mode */
export type DealCTAMode = 'buy' | 'add' | 'both';

/** Props for DealCTA */
export interface DealCTAProps {
  /** Deal data needed for cart + navigation. */
  deal: DealCTADeal;
  /**
   * Visual size.
   * sm = h-8, icon-only by default.
   * md = h-10, icon + short label.
   * lg = h-12, full-width, full label.
   * @default 'md'
   */
  size?: 'sm' | 'md' | 'lg';
  /**
   * Which action(s) to show.
   * buy = open checkout modal via BuyButton
   * add = add to cart
   * both = buy (primary) + add (secondary) inline
   * @default 'buy'
   */
  mode?: DealCTAMode;
  /**
   * When true, shows only the icon (no label).
   * Defaults to true when size='sm'.
   */
  iconOnly?: boolean;
  /** When true, shows "Sold out" state and disables buttons. @default false */
  soldOut?: boolean;
  /** Additional disabled state. @default false */
  disabled?: boolean;
  /** Additional class names on the wrapper element. */
  className?: string;
  /** Called after add-to-cart completes. */
  onAdded?: () => void;
}

interface ToastEntry {
  id: string;
  message: string;
}

/**
 * DealCTA — buy / add-to-cart CTA for deal surfaces.
 * Composed of BuyButton (ShoppingCart icon) and AddToCartButton (Plus icon).
 * Handles toast feedback for add-to-cart.
 *
 * @example
 * ```tsx
 * // In DealCard hover overlay
 * <DealCTA deal={deal} size="sm" mode="both" iconOnly />
 *
 * // In DealDetail hero
 * <DealCTA deal={deal} size="lg" mode="both" />
 * ```
 */
export function DealCTA({
  deal,
  size = 'md',
  mode = 'buy',
  iconOnly: iconOnlyProp,
  soldOut = false,
  disabled = false,
  className,
  onAdded,
}: DealCTAProps) {
  const t = useT('domain_deal_cta');
  const setCartOpen = useCartDrawerStore((s) => s.setOpen);
  const [toasts, setToasts] = useState<ToastEntry[]>([]);

  const isDisabled = soldOut || disabled;
  const iconOnly = iconOnlyProp ?? size === 'sm';

  const handleAdded = useCallback(() => {
    onAdded?.();
    const toastId = `cart-added-${Date.now()}`;
    setToasts((prev) => [...prev, { id: toastId, message: t('added_toast') }]);
    setTimeout(() => {
      setToasts((prev) => prev.filter((entry) => entry.id !== toastId));
    }, 5000);
  }, [onAdded, t]);

  const handleViewCart = useCallback(
    (e: React.MouseEvent) => {
      e.stopPropagation();
      setCartOpen(true);
    },
    [setCartOpen],
  );

  return (
    <ToastProvider>
      <div className={cn('inline-flex items-center gap-1.5', size === 'lg' && 'w-full', className)}>
        {(mode === 'buy' || mode === 'both') && (
          <BuyButton
            dealId={deal.id}
            size={size}
            soldOut={soldOut}
            disabled={disabled}
            iconOnly={iconOnly}
            hasAxes={deal.hasAxes}
            defaultSkuId={deal.defaultSkuId}
            heSlug={deal.heSlug}
            dealType={deal.dealType}
          />
        )}

        {(mode === 'add' || mode === 'both') && (
          <AddToCartButton
            dealSkuId={deal.id}
            size={size}
            disabled={isDisabled}
            iconOnly={iconOnly}
            onAdded={handleAdded}
            title={deal.title}
            imageUrl={deal.imageSrc}
          />
        )}
      </div>

      {toasts.map((entry, index) => (
        <Toast
          key={entry.id}
          tone="success"
          className="flex items-center justify-between gap-3"
          style={
            {
              '--toast-stack-offset': `${index * 6}px`,
            } as React.CSSProperties
          }
        >
          <span className="text-sm">{entry.message}</span>
          <button
            type="button"
            onClick={handleViewCart}
            className="text-success-700 shrink-0 rounded text-sm font-semibold underline-offset-2 hover:underline focus-visible:ring-2 focus-visible:ring-current focus-visible:outline-none"
          >
            {t('view_cart')}
          </button>
        </Toast>
      ))}
      <ToastViewport />
    </ToastProvider>
  );
}
