'use client';

import { useParams, useRouter } from 'next/navigation';
import { cn } from '@/lib/utils';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import type { QueueStatus } from '@/lib/services/system-monitoring.service';

interface QueueOverviewProps {
  queues: QueueStatus[];
}

interface StatPillProps {
  label: string;
  value: number;
  highlight?: boolean;
}

function StatPill({ label, value, highlight }: StatPillProps) {
  return (
    <div className="flex flex-col items-center">
      <span
        className={cn(
          'text-lg font-bold leading-none',
          highlight && value > 0 ? 'text-destructive' : 'text-foreground',
        )}
      >
        {value}
      </span>
      <span className="text-[10px] text-muted-foreground mt-0.5 uppercase tracking-wide">
        {label}
      </span>
    </div>
  );
}

export function QueueOverview({ queues }: QueueOverviewProps) {
  const router = useRouter();
  const params = useParams<{ portSlug: string }>();

  function handleQueueClick(queueName: string) {
    router.push(`/${params.portSlug}/admin/monitoring/${queueName}`);
  }

  return (
    <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
      {queues.map((queue) => (
        <Card
          key={queue.name}
          className="cursor-pointer hover:border-primary/50 transition-colors"
          onClick={() => handleQueueClick(queue.name)}
          role="button"
          tabIndex={0}
          onKeyDown={(e) => e.key === 'Enter' && handleQueueClick(queue.name)}
        >
          <CardHeader className="p-3 pb-0">
            <CardTitle className="text-xs font-semibold capitalize truncate">
              {queue.name}
            </CardTitle>
          </CardHeader>
          <CardContent className="p-3 pt-2">
            <div className="grid grid-cols-2 gap-x-2 gap-y-1">
              <StatPill label="wait" value={queue.waiting} />
              <StatPill label="active" value={queue.active} />
              <StatPill label="done" value={queue.completed} />
              <StatPill label="failed" value={queue.failed} highlight />
            </div>
            {queue.delayed > 0 && (
              <p className="text-[10px] text-muted-foreground text-center mt-1">
                {queue.delayed} delayed
              </p>
            )}
          </CardContent>
        </Card>
      ))}
    </div>
  );
}
