// @design-system: domain/VendorDealCard
/**
 * VendorDealCard — vendor-console deal card.
 *
 * Variants:
 *   active  — live deal with progress bar, tier badges, countdown
 *   pending — awaiting moderation OR needs fix-and-resubmit inline
 *   closed  — recently ended with outcome pill (won/partial/lost)
 *   history — older closed deal (compact, outcome pill)
 *
 * Tokens: `--color-mode-vendor-*`, `--color-brand-primary-*`,
 *          `--color-success-*`, `--color-danger-*`, `--color-warning-*`,
 *          `--color-surface-raised`, `--color-border`, `--color-text-*`
 */

'use client';

import { cn } from '@/lib/cn';
import { useT, useLocale } from '@/lib/i18n/react';
import { interpolate } from '@/lib/i18n/interpolate';
import { formatDateTime } from '@/lib/format';
import { formatShekelFloat } from '@/lib/money';
import { Icon } from '@/components/ui/icons/Icon';
import { Button } from '@/components/ui/primitives/Button';
import { Image } from '@/components/ui/primitives/Image';
import {
  Tooltip,
  TooltipTrigger,
  TooltipContent,
  TooltipProvider,
} from '@/components/ui/overlays/Tooltip';

export type VendorDealCardVariant = 'active' | 'pending' | 'closed' | 'history';
export type DealOutcome = 'won' | 'partial' | 'lost' | 'sold_out';

export interface TierBadge {
  /** Minimum participants for this tier. */
  participants: number;
  /** Price at this tier. */
  price: number;
  /** Whether this tier was reached. */
  reached?: boolean;
}

export interface VendorDealCardProps {
  /** Card variant. */
  variant: VendorDealCardVariant;
  /** Deal title. */
  title: string;
  /** Owner detail route for the deal title. */
  href?: string;
  /** SKU or deal reference. */
  meta?: string;
  /** Current participant count. */
  participants?: number;
  /** Target participant count. */
  targetParticipants?: number;
  /** Tier thresholds. */
  tiers?: TierBadge[];
  /** GROUP vs ITEM/COUPON — controls progress copy on active cards. */
  dealType?: string | null;
  /** Override the right-side progress detail line (e.g. dashboard stock label). */
  progressDetailText?: string;
  /** Pre-formatted window-end label (from formatDealWindowEnd). */
  timeRemaining?: string;
  /** Current price (₪). */
  price?: number;
  /** Deal outcome (closed/history variants). */
  outcome?: DealOutcome;
  /** Neutral state label for history variant (e.g. Expired / Paused). */
  dealStateLabel?: string;
  /** Tooltip for the neutral state pill. */
  dealStateLabelTooltip?: string;
  /** Rejection reason text (pending variant with issues). */
  rejectionReason?: string;
  /** Number of issues to fix (pending variant). */
  issueCount?: number;
  /** Called when user clicks Fix & Resubmit. */
  onFixResubmit?: () => void;
  /** Called when user clicks Delete. */
  onDelete?: () => void;
  /** Called when user clicks Duplicate (closed / history variants). */
  onDuplicate?: () => void;
  /** Duplicate action in flight. */
  duplicateLoading?: boolean;
  /** Deal date string (history variant). */
  dealDate?: string;
  /** Label prefix for dealDate (history variant, e.g. "Published:"). */
  dealDateLabel?: string;
  /** Optional deal hero image URL (active variant). Shown above header row when provided. */
  imageSrc?: string;
  /** Alt text for the hero image. Falls back to title when omitted. */
  imageAlt?: string;
  /** ISO date the deal was submitted for review (pending variant). */
  submittedAt?: string;
  /** Extra class names. */
  className?: string;
}

const outcomeClasses: Record<DealOutcome, string> = {
  won: 'bg-success-50 text-success-700 border-success-200',
  partial: 'bg-warning-50 text-warning-700 border-warning-200',
  lost: 'bg-danger-50 text-danger-700 border-danger-200',
  sold_out: 'bg-success-50 text-success-700 border-success-200',
};

const outcomeTooltipKeys: Record<
  DealOutcome,
  | 'outcome_won_tooltip'
  | 'outcome_partial_tooltip'
  | 'outcome_lost_tooltip'
  | 'outcome_sold_out_tooltip'
> = {
  won: 'outcome_won_tooltip',
  partial: 'outcome_partial_tooltip',
  lost: 'outcome_lost_tooltip',
  sold_out: 'outcome_sold_out_tooltip',
};

/**
 * VendorDealCard
 *
 * Tokens: `--color-brand-primary-600`, `--color-surface-raised`, `--color-border`
 */
export function VendorDealCard({
  variant,
  title,
  href,
  meta,
  participants = 0,
  targetParticipants = 0,
  dealType,
  progressDetailText,
  tiers = [],
  timeRemaining,
  price,
  outcome,
  dealStateLabel,
  dealStateLabelTooltip,
  rejectionReason,
  issueCount = 0,
  onFixResubmit,
  onDelete,
  onDuplicate,
  duplicateLoading = false,
  dealDate,
  dealDateLabel,
  submittedAt,
  imageSrc,
  imageAlt,
  className,
}: VendorDealCardProps) {
  const t = useT('vendor_deal_card');
  const displayTitle = (title ?? '').trim() || t('untitledDeal');
  const { locale } = useLocale();
  const isGroupDeal = dealType === 'GROUP';

  const fillPct =
    targetParticipants > 0 ? Math.min(100, (participants / targetParticipants) * 100) : 0;

  const barColor =
    fillPct >= 80
      ? 'bg-success-500'
      : fillPct >= 40
        ? 'bg-brand-primary-600'
        : 'bg-brand-primary-400';

  const progressDetail =
    progressDetailText ??
    (isGroupDeal || !dealType
      ? `${participants} ${t('participants_of')} ${targetParticipants}`
      : interpolate(t('progress_stock'), { sold: participants, total: targetParticipants }));

  return (
    <TooltipProvider>
      <article
        className={cn(
          'bg-surface-raised border-border rounded-xl border p-4',
          'flex flex-col gap-3',
          className,
        )}
      >
        {variant === 'active' && imageSrc ? (
          <div data-testid="top-deal-image" className="overflow-hidden rounded-lg">
            <Image
              src={imageSrc}
              alt={imageAlt || displayTitle}
              variant="card"
              width={400}
              height={200}
              loading="lazy"
              className="aspect-[2/1] w-full object-cover"
            />
          </div>
        ) : null}

        <div className="flex items-start justify-between gap-3">
          <div className="min-w-0">
            {href ? (
              <a className="text-text-primary block truncate font-semibold" href={href}>
                {displayTitle}
              </a>
            ) : (
              <p className="text-text-primary truncate font-semibold">{displayTitle}</p>
            )}
            {meta && <p className="text-text-muted mt-0.5 text-xs">{meta}</p>}
            {(variant === 'closed' || variant === 'history') && targetParticipants > 0 && (
              <p className="text-text-muted mt-0.5 text-xs">
                {interpolate(t('sold_meta'), { sold: participants, total: targetParticipants })}
              </p>
            )}
          </div>

          {variant === 'active' && (
            <span className="bg-success-50 text-success-700 border-success-200 inline-flex shrink-0 items-center gap-1 rounded-full border px-2 py-0.5 text-xs font-semibold">
              <span aria-hidden className="bg-success-500 inline-block h-1.5 w-1.5 rounded-full" />
              {t('status_active')}
            </span>
          )}
          {variant === 'pending' && issueCount === 0 && (
            <Tooltip>
              <TooltipTrigger asChild>
                <span className="bg-warning-50 text-warning-700 border-warning-200 pointer-events-auto inline-flex shrink-0 items-center gap-1 rounded-full border px-2 py-0.5 text-xs font-semibold">
                  {t('status_pending')}
                </span>
              </TooltipTrigger>
              <TooltipContent>{t('status_pending_tooltip')}</TooltipContent>
            </Tooltip>
          )}
          {variant === 'pending' && issueCount > 0 && (
            <span className="bg-danger-50 text-danger-700 border-danger-200 inline-flex shrink-0 items-center gap-1 rounded-full border px-2 py-0.5 text-xs font-semibold">
              <Icon name="AlertTriangle" size="xs" aria-hidden />
              {t('rejection_needs_fix')}
            </span>
          )}
          {variant === 'history' && dealStateLabel && !outcome && (
            <Tooltip>
              <TooltipTrigger asChild>
                <span className="bg-surface-inset text-text-secondary border-border pointer-events-auto inline-flex shrink-0 items-center gap-1 rounded-full border px-2 py-0.5 text-xs font-semibold">
                  {dealStateLabel}
                </span>
              </TooltipTrigger>
              {dealStateLabelTooltip ? (
                <TooltipContent>{dealStateLabelTooltip}</TooltipContent>
              ) : null}
            </Tooltip>
          )}
          {(variant === 'closed' || variant === 'history') && outcome && (
            <Tooltip>
              <TooltipTrigger asChild>
                <span
                  className={cn(
                    'pointer-events-auto inline-flex shrink-0 items-center gap-1 rounded-full border px-2 py-0.5 text-xs font-semibold',
                    outcomeClasses[outcome],
                  )}
                >
                  {outcome === 'won' && t('outcome_won')}
                  {outcome === 'partial' && t('outcome_partial')}
                  {outcome === 'lost' && t('outcome_lost')}
                  {outcome === 'sold_out' && t('outcome_sold_out')}
                </span>
              </TooltipTrigger>
              <TooltipContent>{t(outcomeTooltipKeys[outcome])}</TooltipContent>
            </Tooltip>
          )}
        </div>

        {variant === 'active' && targetParticipants > 0 && (
          <div>
            <div className="mb-1 flex items-center justify-between">
              <span className="text-text-muted text-xs">{t('progress_label')}</span>
              <span className="text-text-secondary text-xs font-[var(--font-en)] font-medium tabular-nums">
                {progressDetail}
                {price != null && ` · ${formatShekelFloat(price)}`}
              </span>
            </div>
            <div
              role="progressbar"
              aria-valuenow={participants}
              aria-valuemin={0}
              aria-valuemax={targetParticipants}
              aria-label={t('progress_label')}
              className="h-1.5 overflow-hidden rounded-full bg-neutral-100"
            >
              <div
                className={cn('h-full rounded-full transition-[width]', barColor)}
                style={{ width: `${fillPct}%` }}
              />
            </div>
          </div>
        )}

        {tiers.length > 0 && (
          <div className="flex flex-wrap gap-2">
            {tiers.map((tier) => (
              <span
                key={tier.participants}
                className={cn(
                  'rounded-full border px-2 py-0.5 text-xs font-[var(--font-en)] tabular-nums',
                  tier.reached
                    ? 'bg-brand-primary-50 text-brand-primary-700 border-brand-primary-200'
                    : 'bg-surface-inset text-text-secondary border-border',
                )}
              >
                {tier.participants} · {formatShekelFloat(tier.price)}
              </span>
            ))}
          </div>
        )}

        {variant === 'active' && timeRemaining && (
          <div className="text-text-muted flex items-center gap-2 text-xs">
            <Icon name="Clock" size="xs" aria-hidden />
            <span className="text-text-primary font-[var(--font-en)] font-semibold tabular-nums">
              {timeRemaining}
            </span>
          </div>
        )}

        {variant === 'pending' && submittedAt && (
          <div className="text-text-muted flex items-center gap-2 text-xs">
            <Icon name="Clock" size="xs" aria-hidden />
            <span>{t('submitted_at')}:</span>
            <time
              dateTime={submittedAt}
              className="text-text-secondary font-[var(--font-en)] tabular-nums"
            >
              {formatDateTime(submittedAt, locale)}
            </time>
          </div>
        )}

        {variant === 'pending' && rejectionReason && (
          <div className="bg-danger-50 border-danger-200 text-danger-700 rounded-lg border p-3 text-sm">
            <strong className="font-semibold">{t('required_label')} </strong>
            {rejectionReason}
          </div>
        )}

        {variant === 'history' && dealDate && (
          <p className="text-text-muted text-xs">
            {dealDateLabel ? <span>{dealDateLabel} </span> : null}
            <span className="font-[var(--font-en)] tabular-nums">{dealDate}</span>
          </p>
        )}

        {variant === 'pending' && issueCount > 0 && (
          <div className="flex justify-end gap-2">
            {onDelete && (
              <Button variant="ghost" size="sm" onClick={onDelete}>
                {t('delete_deal')}
              </Button>
            )}
            {onFixResubmit && (
              <Button variant="primary" size="sm" onClick={onFixResubmit}>
                {t('fix_resubmit')}
              </Button>
            )}
          </div>
        )}

        {(variant === 'closed' || variant === 'history') && onDuplicate && (
          <div className="flex justify-end">
            <Tooltip>
              <TooltipTrigger asChild>
                <span>
                  <Button
                    variant="ghost"
                    size="sm"
                    loading={duplicateLoading}
                    disabled={duplicateLoading}
                    onClick={onDuplicate}
                  >
                    {t('duplicate_action')}
                  </Button>
                </span>
              </TooltipTrigger>
              <TooltipContent>{t('duplicate_tooltip')}</TooltipContent>
            </Tooltip>
          </div>
        )}
      </article>
    </TooltipProvider>
  );
}
