import { Link, usePage } from '@inertiajs/react';

import { cn } from '@/lib/utils';
import type { PageProps } from '@/types';

/**
 * Shows bundled AI draft quota remaining.
 * Reads ai_status from shared Inertia props.
 * Returns null for BYOK users (they have unlimited quota).
 */
export default function AiQuotaBadge() {
  const { ai_status } = usePage<PageProps>().props;

  if (!ai_status || ai_status.mode !== 'bundled') {
    return null;
  }

  const remaining = ai_status.bundled_remaining ?? 0;
  const limit = ai_status.bundled_limit ?? 0;

  if (limit <= 0) {
    return null;
  }

  const percent = Math.round((remaining / limit) * 100);

  // Color thresholds: green ≥4 remaining, yellow 2–3, red ≤1
  const colorClass =
    remaining >= 4
      ? 'text-green-600 dark:text-green-400'
      : remaining >= 2
        ? 'text-yellow-600 dark:text-yellow-500'
        : 'text-destructive';

  const statusLabel =
    remaining >= 4 ? 'Plenty left' : remaining >= 2 ? 'Running low' : remaining === 1 ? 'Almost gone' : 'No drafts left';

  return (
    <div className="flex items-center gap-2 text-sm">
      <div className="flex items-center gap-1.5">
        <span className={cn('font-medium tabular-nums', colorClass)}>
          {remaining}/{limit}
        </span>
        <span className="text-muted-foreground">drafts remaining</span>
        <span className="sr-only">{statusLabel}</span>
      </div>
      <div
        role="progressbar"
        aria-valuenow={remaining}
        aria-valuemin={0}
        aria-valuemax={limit}
        aria-label="AI draft quota"
        className="relative h-1.5 w-16 rounded-full bg-muted overflow-hidden"
      >
        <div
          className={cn('h-full rounded-full transition-all duration-300', {
            'bg-green-500 dark:bg-green-400': remaining >= 4,
            'bg-yellow-500 dark:bg-yellow-400': remaining >= 2 && remaining < 4,
            'bg-destructive': remaining < 2,
          })}
          style={{ width: `${percent}%` }}
        />
      </div>
      {remaining <= 2 && remaining > 0 && (
        <Link href={route('billing.index')} className="text-xs text-primary hover:underline">
          Upgrade
        </Link>
      )}
    </div>
  );
}
