'use client';

import { useState } from 'react';
import { useTranslations } from 'next-intl';

import { formatPrice } from '@/lib/utils';
import type { ActivePromotion } from '@/types/api';
import { FlashSaleCountdown } from '@/components/home-blocks/FlashSaleCountdown';
import { OfferScopeBadge } from './OfferScopeBadge';

/** Feature 054 — US11 (C4). Card for a single active promotion on /offers. */
export function ActiveOfferCard({
  promo,
  locale,
  onExpire,
}: {
  promo: ActivePromotion;
  locale: string;
  onExpire?: (publicId: string) => void;
}) {
  const t = useTranslations('offers.card');
  const [expired, setExpired] = useState(false);

  const discountLabel =
    promo.discount.kind === 'percentage'
      ? `${promo.discount.value_minor / 100}%`
      : formatPrice(promo.discount.value_minor, locale, promo.discount.currency);

  return (
    <article
      data-testid="active-offer-card"
      data-expired={expired ? 'true' : 'false'}
      className="flex flex-col gap-3 rounded-2xl border border-neutral-200 bg-white p-5 shadow-sm"
    >
      <div className="flex items-start justify-between gap-2">
        <OfferScopeBadge scope={promo.scope} />
        <span className="rounded-full bg-primary-600 px-2.5 py-0.5 text-sm font-bold text-white">
          -{discountLabel}
        </span>
      </div>

      <h3 className="font-heading text-lg font-bold text-neutral-900">{promo.title}</h3>
      {promo.description ? <p className="text-sm text-neutral-600">{promo.description}</p> : null}

      <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-neutral-500">
        <span>
          {t('code_label')}:{' '}
          <span className="font-mono font-semibold text-neutral-800">{promo.code}</span>
        </span>
        {promo.min_order_minor > 0 && (
          <span>{t('min_order', { amount: formatPrice(promo.min_order_minor, locale, promo.currency) })}</span>
        )}
      </div>

      {promo.ends_at ? (
        <FlashSaleCountdown
          endsAt={promo.ends_at}
          size="sm"
          className="mt-1 text-neutral-700"
          onExpire={() => {
            setExpired(true);
            onExpire?.(promo.public_id);
          }}
        />
      ) : null}
    </article>
  );
}
