'use client';

import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import type { AsynqStats } from '@/types/monitoring';
import { Clock, AlertTriangle, CheckCircle, PlayCircle, RotateCcw, Archive } from 'lucide-react';

interface QueueStatsProps {
  stats?: AsynqStats;
}

export function QueueOverview({ stats }: QueueStatsProps) {
  if (!stats || !stats.queues) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>Queue Statistics</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="text-center py-4 text-muted-foreground">
            No queue statistics available
          </div>
        </CardContent>
      </Card>
    );
  }

  // Calculate totals from individual queues
  const totals = Object.values(stats.queues).reduce(
    (acc, queue) => ({
      pending: acc.pending + (queue.pending ?? 0),
      active: acc.active + (queue.active ?? 0),
      scheduled: acc.scheduled + (queue.scheduled ?? 0),
      retry: acc.retry + (queue.retry ?? 0),
      failed: acc.failed + (queue.failed ?? 0),
    }),
    { pending: 0, active: 0, scheduled: 0, retry: 0, failed: 0 }
  );

  return (
    <div className="grid gap-4 md:grid-cols-5">
      <Card>
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
          <CardTitle className="text-sm font-medium">Pending</CardTitle>
          <Clock className="h-4 w-4 text-muted-foreground" />
        </CardHeader>
        <CardContent>
          <div className="text-2xl font-bold">{totals.pending}</div>
          <p className="text-xs text-muted-foreground">tasks waiting</p>
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
          <CardTitle className="text-sm font-medium">Active</CardTitle>
          <PlayCircle className="h-4 w-4 text-blue-500" />
        </CardHeader>
        <CardContent>
          <div className="text-2xl font-bold text-blue-500">{totals.active}</div>
          <p className="text-xs text-muted-foreground">currently running</p>
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
          <CardTitle className="text-sm font-medium">Scheduled</CardTitle>
          <Clock className="h-4 w-4 text-muted-foreground" />
        </CardHeader>
        <CardContent>
          <div className="text-2xl font-bold">{totals.scheduled}</div>
          <p className="text-xs text-muted-foreground">future tasks</p>
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
          <CardTitle className="text-sm font-medium">Retry</CardTitle>
          <RotateCcw className="h-4 w-4 text-yellow-500" />
        </CardHeader>
        <CardContent>
          <div className="text-2xl font-bold text-yellow-500">{totals.retry}</div>
          <p className="text-xs text-muted-foreground">awaiting retry</p>
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
          <CardTitle className="text-sm font-medium">Failed</CardTitle>
          <AlertTriangle className="h-4 w-4 text-red-500" />
        </CardHeader>
        <CardContent>
          <div className="text-2xl font-bold text-red-500">{totals.failed}</div>
          <p className="text-xs text-muted-foreground">permanently failed</p>
        </CardContent>
      </Card>
    </div>
  );
}

export function QueueDetails({ stats }: QueueStatsProps) {
  if (!stats?.queues || Object.keys(stats.queues).length === 0) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>Queue Details</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="text-center py-4 text-muted-foreground">
            No queue details available
          </div>
        </CardContent>
      </Card>
    );
  }

  // Sort queues by priority (critical first)
  const priorityOrder = ['critical', 'default', 'low'];
  const sortedQueues = Object.entries(stats.queues).sort((a, b) => {
    const aIndex = priorityOrder.indexOf(a[0]);
    const bIndex = priorityOrder.indexOf(b[0]);
    if (aIndex === -1 && bIndex === -1) return a[0].localeCompare(b[0]);
    if (aIndex === -1) return 1;
    if (bIndex === -1) return -1;
    return aIndex - bIndex;
  });

  const getPriorityBadge = (queueName: string) => {
    switch (queueName) {
      case 'critical':
        return <Badge variant="destructive">Critical</Badge>;
      case 'default':
        return <Badge variant="default">Default</Badge>;
      case 'low':
        return <Badge variant="secondary">Low</Badge>;
      default:
        return <Badge variant="outline">{queueName}</Badge>;
    }
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle>Queue Details</CardTitle>
      </CardHeader>
      <CardContent>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Queue</TableHead>
              <TableHead className="text-right">Pending</TableHead>
              <TableHead className="text-right">Active</TableHead>
              <TableHead className="text-right">Scheduled</TableHead>
              <TableHead className="text-right">Retry</TableHead>
              <TableHead className="text-right">Archived</TableHead>
              <TableHead className="text-right">Completed</TableHead>
              <TableHead className="text-right">Failed</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {sortedQueues.map(([queueName, queue]) => (
              <TableRow key={queueName}>
                <TableCell>{getPriorityBadge(queueName)}</TableCell>
                <TableCell className="text-right">{queue.pending ?? 0}</TableCell>
                <TableCell className="text-right">
                  <span className={(queue.active ?? 0) > 0 ? 'text-blue-500 font-medium' : ''}>
                    {queue.active ?? 0}
                  </span>
                </TableCell>
                <TableCell className="text-right">{queue.scheduled ?? 0}</TableCell>
                <TableCell className="text-right">
                  <span className={(queue.retry ?? 0) > 0 ? 'text-yellow-500' : ''}>
                    {queue.retry ?? 0}
                  </span>
                </TableCell>
                <TableCell className="text-right">{queue.archived ?? 0}</TableCell>
                <TableCell className="text-right">
                  <span className="text-green-500">{queue.completed ?? 0}</span>
                </TableCell>
                <TableCell className="text-right">
                  <span className={(queue.failed ?? 0) > 0 ? 'text-red-500 font-medium' : ''}>
                    {queue.failed ?? 0}
                  </span>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </CardContent>
    </Card>
  );
}
