'use client';

import { cn } from '@/lib/cn';
import { Icon } from '@/components/ui/icons/Icon';
import { Badge } from '@/components/ui/primitives/Badge';
import { LabelWithTooltip } from '@/components/ui/primitives/LabelWithTooltip';

export interface SharedStatCardProps {
  label: string;
  value: string | number;
  href?: string;
  tone?: 'default' | 'warning' | 'success';
  description?: string;
  tooltip?: string;
  linkHint?: string;
  urgentLabel?: string;
  linkAriaLabel?: string;
  className?: string;
}

const TONE_CLASSES: Record<NonNullable<SharedStatCardProps['tone']>, string> = {
  default: 'border-[var(--color-neutral-200)] bg-[var(--color-surface-base)]',
  warning: 'border-[var(--color-warning-border)] bg-[var(--color-warning-surface)]',
  success: 'border-[var(--color-success-border)] bg-[var(--color-success-surface)]',
};

export function SharedStatCard({
  label,
  value,
  href,
  tone = 'default',
  description,
  tooltip,
  linkHint,
  urgentLabel,
  linkAriaLabel,
  className,
}: SharedStatCardProps) {
  const inner = (
    <div
      className={cn(
        'rounded-lg border p-4',
        TONE_CLASSES[tone],
        href && 'transition-shadow hover:shadow-sm',
        className,
      )}
    >
      <div className="flex items-start justify-between gap-2">
        <div className="min-w-0 flex-1">
          {tooltip ? (
            <LabelWithTooltip label={label} tooltip={tooltip} />
          ) : (
            <p className="text-sm text-[var(--color-text-secondary)]">{label}</p>
          )}
        </div>
        {tone === 'warning' && urgentLabel ? (
          <Badge tone="warning" size="sm">
            {urgentLabel}
          </Badge>
        ) : null}
        {href ? (
          <Icon
            name="ChevronLeft"
            size="sm"
            className="shrink-0 text-[var(--color-text-tertiary)] rtl:scale-x-[-1]"
            aria-hidden
          />
        ) : null}
      </div>
      <p className="mt-1 text-2xl font-bold text-[var(--color-text-primary)]">{value}</p>
      {description ? (
        <p className="mt-1 text-xs text-[var(--color-text-secondary)]">{description}</p>
      ) : null}
      {linkHint ? (
        <p className="mt-2 text-xs text-[var(--color-text-secondary)]">{linkHint}</p>
      ) : null}
    </div>
  );

  if (!href) return inner;

  return (
    <a
      href={href}
      className="block transition-opacity hover:opacity-80 focus-visible:opacity-80"
      aria-label={linkAriaLabel ?? label}
    >
      {inner}
    </a>
  );
}
