import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '../utils/cn';

const providerBadgeVariants = cva(
  'inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-xs font-medium',
  {
    variants: {
      provider: {
        gemini: 'bg-blue-500/15 text-blue-400 border border-blue-500/30',
        laozhang: 'bg-emerald-500/15 text-emerald-400 border border-emerald-500/30',
        default: 'bg-[var(--surface-200)] text-[var(--text-secondary)] border border-[var(--border)]',
      },
    },
    defaultVariants: {
      provider: 'default',
    },
  }
);

type ProviderVariant = 'gemini' | 'laozhang' | 'default';

export interface ProviderBadgeProps
  extends React.HTMLAttributes<HTMLSpanElement>,
    Omit<VariantProps<typeof providerBadgeVariants>, 'provider'> {
  provider: string;
  latency?: number;
}

const providerIcons: Record<string, string> = {
  gemini: '✦',
  laozhang: '◆',
};

const providerLabels: Record<string, string> = {
  gemini: 'Gemini',
  laozhang: 'LaoZhang',
};

function getProviderVariant(provider: string): ProviderVariant {
  const normalized = provider.toLowerCase();
  if (normalized.includes('gemini')) return 'gemini';
  if (normalized.includes('laozhang')) return 'laozhang';
  return 'default';
}

const ProviderBadge = React.forwardRef<HTMLSpanElement, ProviderBadgeProps>(
  ({ provider, latency, className, ...props }, ref) => {
    const variant = getProviderVariant(provider);
    const icon = providerIcons[variant] || '●';
    const label = providerLabels[variant] || provider;

    return (
      <span
        ref={ref}
        className={cn(providerBadgeVariants({ provider: variant }), className)}
        {...props}
      >
        <span className="opacity-70">{icon}</span>
        <span>{label}</span>
        {latency !== undefined && (
          <span className="opacity-60 tabular-nums">{latency}ms</span>
        )}
      </span>
    );
  }
);
ProviderBadge.displayName = 'ProviderBadge';

export { ProviderBadge, providerBadgeVariants };
