"use client";

import { useState } from "react";
import { ArrowRight, BadgePercent, Gift, Images, LoaderCircle, X } from "lucide-react";

import type { CommercialAction } from "@/data/schemas/chat";

import styles from "./chat-area.module.css";

export interface CommercialActionCardProps {
  action: CommercialAction;
  onActivate?: (action: CommercialAction) => void | Promise<void>;
  onDismiss?: (action: CommercialAction) => void;
}

export function CommercialActionCard({
  action,
  onActivate,
  onDismiss,
}: CommercialActionCardProps) {
  const [dismissed, setDismissed] = useState(false);
  const [activating, setActivating] = useState(false);
  const [activationError, setActivationError] = useState<string | null>(null);
  if (dismissed) return null;

  const Icon =
    action.type === "giftOffer"
      ? Gift
      : action.type === "discountOffer"
        ? BadgePercent
        : Images;

  return (
    <aside
      className={styles.commercialAction}
      aria-label={action.ctaLabel}
      data-commercial-action={action.type}
    >
      <div className={styles.commercialActionHeader}>
        <Icon size={18} aria-hidden="true" />
        <button
          type="button"
          className={styles.commercialActionDismiss}
          title="Dismiss offer"
          aria-label="Dismiss offer"
          onClick={() => {
            setDismissed(true);
            onDismiss?.(action);
          }}
        >
          <X size={16} aria-hidden="true" />
        </button>
      </div>
      <p className={styles.commercialActionCopy}>{action.copy}</p>
      {activationError ? (
        <p className={styles.commercialActionError} role="alert">
          {activationError}
        </p>
      ) : null}
      <button
        type="button"
        className={styles.commercialActionButton}
        disabled={activating}
        onClick={() => {
          setActivating(true);
          setActivationError(null);
          void Promise.resolve(onActivate?.(action))
            .catch(() => setActivationError("This private offer is unavailable right now. Please try again."))
            .finally(() => setActivating(false));
        }}
      >
        <span>{action.ctaLabel}</span>
        {activating ? (
          <LoaderCircle className={styles.commercialActionSpinner} size={17} aria-hidden="true" />
        ) : (
          <ArrowRight size={17} aria-hidden="true" />
        )}
      </button>
    </aside>
  );
}
