import React, { useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useJobDetails, useKubectl } from '@/hooks/useKubectl';
import { useToast } from '@/hooks/useToast';
import {
  ArrowLeft,
  Container,
  Activity,
  Play,
  Pause,
  MoreVertical,
  Terminal,
  FileText,
  Eye,
  Trash2,
  CheckCircle,
  Calendar,
  Zap,
  Clock,
  XCircle,
  AlertTriangle,
  ChevronDown,
  ChevronUp,
  Settings,
} from 'lucide-react';

export function JobDetailsPage() {
  const { jobName, namespaceName } = useParams<{
    jobName: string;
    namespaceName: string;
  }>();
  const navigate = useNavigate();
  const { showToast } = useToast();
  const { executeCommand } = useKubectl();

  // Busca dados do job e seus pods
  const {
    jobInfo,
    pods,
    events,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  } = useJobDetails(jobName || '', namespaceName || '');

  const [autoRefresh, setAutoRefresh] = useState(true);
  const [expandedSections, setExpandedSections] = useState({
    config: true,
    pods: true,
    events: true,
  });
  const [cancelModalOpen, setCancelModalOpen] = useState(false);
  const [cancelling, setCancelling] = useState(false);

  // Debug: Log dos dados recebidos
  console.log('JobDetails - Current state:', {
    jobName,
    namespaceName,
    jobInfo,
    pods: pods?.length || 0,
    loading,
    error,
  });

  // Função para obter o status do pod
  const getPodStatus = (pod: any) => {
    if (!pod?.status?.phase)
      return {
        phase: 'Desconhecido',
        icon: AlertTriangle,
        color: 'text-gray-600',
      };

    const { phase } = pod.status;
    switch (phase) {
      case 'Running':
        return { phase: 'Executando', icon: Clock, color: 'text-blue-600' };
      case 'Succeeded':
        return {
          phase: 'Concluído',
          icon: CheckCircle,
          color: 'text-green-600',
        };
      case 'Failed':
        return { phase: 'Falhou', icon: XCircle, color: 'text-red-600' };
      case 'Pending':
        return { phase: 'Pendente', icon: Clock, color: 'text-yellow-600' };
      case 'Unknown':
        return {
          phase: 'Desconhecido',
          icon: AlertTriangle,
          color: 'text-gray-600',
        };
      case 'Terminating':
        return {
          phase: 'Finalizando',
          icon: AlertTriangle,
          color: 'text-orange-600',
        };
      case 'CrashLoopBackOff':
        return {
          phase: 'Erro Recorrente',
          icon: XCircle,
          color: 'text-red-600',
        };
      case 'ImagePullBackOff':
        return {
          phase: 'Erro na Imagem',
          icon: AlertTriangle,
          color: 'text-red-600',
        };
      case 'ContainerCreating':
        return {
          phase: 'Criando Container',
          icon: Clock,
          color: 'text-blue-600',
        };
      case 'PodInitializing':
        return { phase: 'Inicializando', icon: Clock, color: 'text-blue-600' };
      default:
        return { phase, icon: AlertTriangle, color: 'text-gray-600' };
    }
  };

  // Função para calcular a duração do pod
  const getPodDuration = (pod: any) => {
    if (!pod?.status?.startTime) return 'N/A';

    const startTime = new Date(pod.status.startTime);
    const endTime =
      pod.status.phase === 'Succeeded' || pod.status.phase === 'Failed'
        ? new Date(
            pod.status.containerStatuses?.[0]?.state?.terminated?.finishedAt ||
              new Date(),
          )
        : new Date();

    const diffMs = endTime.getTime() - startTime.getTime();
    const diffSeconds = Math.floor(diffMs / 1000);
    const diffMinutes = Math.floor(diffSeconds / 60);
    const diffHours = Math.floor(diffMinutes / 60);
    const diffDays = Math.floor(diffHours / 24);

    if (diffDays > 0) return `${diffDays}d ${diffHours % 24}h`;
    if (diffHours > 0) return `${diffHours}h ${diffMinutes % 60}m`;
    if (diffMinutes > 0) return `${diffMinutes}m ${diffSeconds % 60}s`;
    return `${diffSeconds}s`;
  };

  // Função para obter o número de restarts
  const getPodRestarts = (pod: any) => {
    if (!pod?.status?.containerStatuses) return 0;
    return pod.status.containerStatuses.reduce(
      (total: number, container: any) => {
        return total + (container.restartCount || 0);
      },
      0,
    );
  };

  // Função para cancelar o Job
  const handleCancelJob = async () => {
    if (!jobName || !namespaceName) return;

    setCancelling(true);
    try {
      // Para cancelar um Job no Kubernetes, deletamos ele
      const command = `kubectl delete job ${jobName} -n ${namespaceName}`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'Job Cancelado',
          description: `O job "${jobName}" foi cancelado e removido com sucesso`,
          variant: 'success',
        });

        // Aguarda um pouco e redireciona para a lista de CronJobs ou volta
        setTimeout(() => {
          navigate(-1);
        }, 2000);
      } else {
        showToast({
          title: 'Erro ao Cancelar Job',
          description: result.error || 'Falha ao cancelar o job',
          variant: 'destructive',
        });
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setCancelling(false);
      setCancelModalOpen(false);
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <Button variant="ghost" size="icon" onClick={() => navigate(-1)}>
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <div>
            <h1 className="text-3xl font-bold text-foreground flex items-center">
              <Container className="h-8 w-8 mr-3 text-blue-600" />
              {jobName}
            </h1>
            <div className="text-muted-foreground">
              Job no namespace <Badge variant="outline">{namespaceName}</Badge>
            </div>
          </div>
        </div>
        <div className="flex items-center space-x-2">
          <Button
            onClick={() => setAutoRefresh(!autoRefresh)}
            variant={autoRefresh ? 'default' : 'outline'}
            title={
              autoRefresh
                ? 'Pausar atualização automática'
                : 'Ativar atualização automática'
            }
          >
            {autoRefresh ? (
              <>
                <Pause className="h-4 w-4 mr-2" />
                Auto (10s)
              </>
            ) : (
              <>
                <Play className="h-4 w-4 mr-2" />
                Manual
              </>
            )}
          </Button>

          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline">
                <MoreVertical className="h-4 w-4 mr-2" />
                Ações
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuLabel>Ações do Job</DropdownMenuLabel>
              <DropdownMenuSeparator />
              <DropdownMenuItem disabled>
                <Terminal className="h-4 w-4 mr-2" />
                Console
              </DropdownMenuItem>
              <DropdownMenuItem disabled>
                <FileText className="h-4 w-4 mr-2" />
                Logs
              </DropdownMenuItem>
              <DropdownMenuItem disabled>
                <Eye className="h-4 w-4 mr-2" />
                YAML
              </DropdownMenuItem>
              <DropdownMenuSeparator />
              <DropdownMenuItem
                onClick={() => setCancelModalOpen(true)}
                className="text-red-600"
              >
                <Trash2 className="h-4 w-4 mr-2" />
                Cancelar Job
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </div>

      {/* Overview Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Status</CardTitle>
            <Activity className="h-4 w-4 text-blue-600" />
          </CardHeader>
          <CardContent>
            <Badge
              variant="default"
              className="bg-blue-100 text-blue-800 hover:bg-blue-200"
            >
              {loading ? 'Carregando...' : 'Ativo'}
            </Badge>
            <p className="text-xs text-muted-foreground mt-1">Estado atual</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Pods</CardTitle>
            <Container className="h-4 w-4 text-green-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {loading
                ? '-'
                : `${jobInfo?.status?.active || 0}/${jobInfo?.spec?.parallelism || 1}`}
            </div>
            <p className="text-xs text-muted-foreground">Ativo/Desejado</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Completions</CardTitle>
            <CheckCircle className="h-4 w-4 text-purple-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {loading
                ? '-'
                : `${jobInfo?.status?.succeeded || 0}/${jobInfo?.spec?.completions || 1}`}
            </div>
            <p className="text-xs text-muted-foreground">Completos/Total</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Idade</CardTitle>
            <Calendar className="h-4 w-4 text-orange-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {loading
                ? '-'
                : jobInfo?.metadata?.creationTimestamp
                  ? (() => {
                      const now = new Date();
                      const created = new Date(
                        jobInfo.metadata.creationTimestamp,
                      );
                      const diffMs = now.getTime() - created.getTime();
                      const diffDays = Math.floor(
                        diffMs / (1000 * 60 * 60 * 24),
                      );
                      const diffHours = Math.floor(
                        (diffMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60),
                      );
                      const diffMinutes = Math.floor(
                        (diffMs % (1000 * 60 * 60)) / (1000 * 60),
                      );

                      if (diffDays > 0) return `${diffDays}d`;
                      if (diffHours > 0) return `${diffHours}h`;
                      return `${diffMinutes}m`;
                    })()
                  : 'N/A'}
            </div>
            <p className="text-xs text-muted-foreground">Tempo de vida</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Duração</CardTitle>
            <Zap className="h-4 w-4 text-indigo-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {loading
                ? '-'
                : jobInfo?.status?.startTime && jobInfo?.status?.completionTime
                  ? `${Math.floor(
                      (new Date(jobInfo.status.completionTime).getTime() -
                        new Date(jobInfo.status.startTime).getTime()) /
                        1000,
                    )}s`
                  : jobInfo?.status?.startTime
                    ? `${Math.floor(
                        (new Date().getTime() -
                          new Date(jobInfo.status.startTime).getTime()) /
                          1000,
                      )}s`
                    : 'N/A'}
            </div>
            <p className="text-xs text-muted-foreground">Tempo execução</p>
          </CardContent>
        </Card>
      </div>

      {/* Job Configuration Section */}
      <Card>
        <CardHeader
          className="cursor-pointer"
          onClick={() =>
            setExpandedSections({
              ...expandedSections,
              config: !expandedSections.config,
            })
          }
        >
          <CardTitle className="flex items-center justify-between">
            <div className="flex items-center">
              <Settings className="h-5 w-5 mr-2 text-gray-600" />
              Configuração do Job
            </div>
            {expandedSections.config ? (
              <ChevronUp className="h-4 w-4" />
            ) : (
              <ChevronDown className="h-4 w-4" />
            )}
          </CardTitle>
        </CardHeader>
        {expandedSections.config && (
          <CardContent>
            {loading ? (
              <div className="flex items-center justify-center py-8">
                <div className="text-center">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-600 mx-auto mb-2" />
                  <p className="text-sm text-muted-foreground">
                    Carregando configuração...
                  </p>
                </div>
              </div>
            ) : jobInfo ? (
              <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
                {/* Basic Information */}
                <div className="space-y-5 pr-6 border-r border-gray-100 last:border-r-0">
                  <div className="flex justify-between items-start min-h-[20px]">
                    <span className="text-sm text-muted-foreground font-medium">
                      Nome:
                    </span>
                    <span className="text-sm font-medium text-right break-all">
                      {jobInfo.metadata?.name || 'N/A'}
                    </span>
                  </div>
                  <div className="flex justify-between items-start min-h-[20px]">
                    <span className="text-sm text-muted-foreground font-medium">
                      Namespace:
                    </span>
                    <span className="text-sm font-medium text-right">
                      {jobInfo.metadata?.namespace || 'N/A'}
                    </span>
                  </div>
                  <div className="flex justify-between items-start min-h-[20px]">
                    <span className="text-sm text-muted-foreground font-medium">
                      Parallelism:
                    </span>
                    <span className="text-sm font-medium text-right">
                      {jobInfo.spec?.parallelism || 1}
                    </span>
                  </div>
                  <div className="flex justify-between items-start min-h-[20px]">
                    <span className="text-sm text-muted-foreground font-medium">
                      Completions:
                    </span>
                    <span className="text-sm font-medium text-right">
                      {jobInfo.spec?.completions || 1}
                    </span>
                  </div>
                </div>

                {/* Job Spec */}
                <div className="space-y-5 pr-6 border-r border-gray-100 last:border-r-0">
                  <div className="flex justify-between items-start min-h-[20px]">
                    <span className="text-sm text-muted-foreground font-medium">
                      Backoff Limit:
                    </span>
                    <span className="text-sm font-medium text-right">
                      {jobInfo.spec?.backoffLimit ?? 6}
                    </span>
                  </div>
                  <div className="flex justify-between items-start min-h-[20px]">
                    <span className="text-sm text-muted-foreground font-medium">
                      Active Deadline:
                    </span>
                    <span className="text-sm font-medium text-right">
                      {jobInfo.spec?.activeDeadlineSeconds
                        ? `${jobInfo.spec.activeDeadlineSeconds}s`
                        : 'N/A'}
                    </span>
                  </div>
                  <div className="flex justify-between items-start min-h-[20px]">
                    <span className="text-sm text-muted-foreground font-medium">
                      Restart Policy:
                    </span>
                    <span className="text-sm font-medium text-right">
                      {jobInfo.spec?.template?.spec?.restartPolicy || 'Never'}
                    </span>
                  </div>
                  <div className="flex justify-between items-start min-h-[20px]">
                    <span className="text-sm text-muted-foreground font-medium">
                      TTL After Finished:
                    </span>
                    <span className="text-sm font-medium text-right">
                      {jobInfo.spec?.ttlSecondsAfterFinished
                        ? `${jobInfo.spec.ttlSecondsAfterFinished}s`
                        : 'N/A'}
                    </span>
                  </div>
                </div>

                {/* Status Information */}
                <div className="space-y-5">
                  <div className="flex justify-between items-start min-h-[20px]">
                    <span className="text-sm text-muted-foreground font-medium">
                      Pods Ativos:
                    </span>
                    <span className="text-sm font-medium text-right">
                      {jobInfo.status?.active || 0}
                    </span>
                  </div>
                  <div className="flex justify-between items-start min-h-[20px]">
                    <span className="text-sm text-muted-foreground font-medium">
                      Pods Concluídos:
                    </span>
                    <span className="text-sm font-medium text-right">
                      {jobInfo.status?.succeeded || 0}
                    </span>
                  </div>
                  <div className="flex justify-between items-start min-h-[20px]">
                    <span className="text-sm text-muted-foreground font-medium">
                      Pods Falharam:
                    </span>
                    <span className="text-sm font-medium text-right">
                      {jobInfo.status?.failed || 0}
                    </span>
                  </div>
                  <div className="flex justify-between items-start min-h-[20px]">
                    <span className="text-sm text-muted-foreground font-medium">
                      Início:
                    </span>
                    <span className="text-sm font-medium text-right">
                      {jobInfo.status?.startTime
                        ? new Date(jobInfo.status.startTime).toLocaleString(
                            'pt-BR',
                          )
                        : 'N/A'}
                    </span>
                  </div>
                </div>
              </div>
            ) : (
              <div className="text-center py-8">
                <div className="text-muted-foreground">
                  <Settings className="h-8 w-8 mx-auto mb-2 opacity-50" />
                  <p>Configuração não disponível</p>
                </div>
              </div>
            )}
          </CardContent>
        )}
      </Card>

      {/* Pods Section */}
      <Card>
        <CardHeader
          className="cursor-pointer"
          onClick={() =>
            setExpandedSections({
              ...expandedSections,
              pods: !expandedSections.pods,
            })
          }
        >
          <CardTitle className="flex items-center justify-between">
            <div className="flex items-center">
              <Container className="h-5 w-5 mr-2 text-blue-600" />
              Pods ({loading ? '...' : pods.length})
            </div>
            {expandedSections.pods ? (
              <ChevronUp className="h-4 w-4" />
            ) : (
              <ChevronDown className="h-4 w-4" />
            )}
          </CardTitle>
        </CardHeader>
        {expandedSections.pods && (
          <CardContent>
            {loading ? (
              <div className="flex items-center justify-center py-8">
                <div className="text-center">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-2" />
                  <p className="text-sm text-muted-foreground">
                    Carregando pods...
                  </p>
                </div>
              </div>
            ) : (
              <div className="space-y-4">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-12">Status</TableHead>
                      <TableHead>Nome</TableHead>
                      <TableHead>Início</TableHead>
                      <TableHead>Duração</TableHead>
                      <TableHead>Restarts</TableHead>
                      <TableHead className="w-16">Ações</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {pods.length > 0 ? (
                      pods.map((pod, index) => {
                        const status = getPodStatus(pod);
                        const StatusIcon = status.icon;

                        return (
                          <TableRow key={pod.metadata?.uid || index}>
                            <TableCell>
                              <div className="flex items-center">
                                <StatusIcon
                                  className={`h-4 w-4 mr-2 ${status.color}`}
                                />
                                <span
                                  className={`text-sm font-medium ${status.color}`}
                                >
                                  {status.phase}
                                </span>
                              </div>
                            </TableCell>
                            <TableCell>
                              <button
                                className="text-blue-600 hover:text-blue-800 hover:underline text-left"
                                onClick={() =>
                                  navigate(
                                    `/workloads/pods/${pod.metadata?.name}/${namespaceName}`,
                                  )
                                }
                              >
                                {pod.metadata?.name}
                              </button>
                            </TableCell>
                            <TableCell>
                              <span className="text-sm text-muted-foreground">
                                {pod.status?.startTime
                                  ? new Date(
                                      pod.status.startTime,
                                    ).toLocaleString('pt-BR', {
                                      day: '2-digit',
                                      month: '2-digit',
                                      year: 'numeric',
                                      hour: '2-digit',
                                      minute: '2-digit',
                                    })
                                  : 'N/A'}
                              </span>
                            </TableCell>
                            <TableCell>
                              <span className="text-sm">
                                {getPodDuration(pod)}
                              </span>
                            </TableCell>
                            <TableCell>
                              <span className="text-sm">
                                {getPodRestarts(pod)}
                              </span>
                            </TableCell>
                            <TableCell>
                              <DropdownMenu>
                                <DropdownMenuTrigger asChild>
                                  <Button
                                    variant="ghost"
                                    size="icon"
                                    className="h-8 w-8"
                                  >
                                    <MoreVertical className="h-4 w-4" />
                                  </Button>
                                </DropdownMenuTrigger>
                                <DropdownMenuContent align="end">
                                  <DropdownMenuLabel>
                                    Ações do Pod
                                  </DropdownMenuLabel>
                                  <DropdownMenuSeparator />
                                  <DropdownMenuItem
                                    onClick={() =>
                                      navigate(
                                        `/workloads/pods/${pod.metadata?.name}/${namespaceName}`,
                                      )
                                    }
                                  >
                                    <Eye className="h-4 w-4 mr-2" />
                                    Ver Detalhes
                                  </DropdownMenuItem>
                                  <DropdownMenuItem
                                    disabled={pod.status?.phase !== 'Running'}
                                  >
                                    <Terminal className="h-4 w-4 mr-2" />
                                    Console
                                  </DropdownMenuItem>
                                  <DropdownMenuItem>
                                    <FileText className="h-4 w-4 mr-2" />
                                    Logs
                                  </DropdownMenuItem>
                                </DropdownMenuContent>
                              </DropdownMenu>
                            </TableCell>
                          </TableRow>
                        );
                      })
                    ) : (
                      <TableRow>
                        <TableCell colSpan={6} className="text-center py-8">
                          <div className="text-muted-foreground">
                            <Container className="h-8 w-8 mx-auto mb-2 opacity-50" />
                            <p>Nenhum pod encontrado para este Job</p>
                          </div>
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>
            )}
          </CardContent>
        )}
      </Card>

      {/* Events Section */}
      <Card>
        <CardHeader
          className="cursor-pointer"
          onClick={() =>
            setExpandedSections({
              ...expandedSections,
              events: !expandedSections.events,
            })
          }
        >
          <CardTitle className="flex items-center justify-between">
            <div className="flex items-center">
              <Activity className="h-5 w-5 mr-2 text-orange-600" />
              Events ({loading ? '...' : events.length})
            </div>
            {expandedSections.events ? (
              <ChevronUp className="h-4 w-4" />
            ) : (
              <ChevronDown className="h-4 w-4" />
            )}
          </CardTitle>
        </CardHeader>
        {expandedSections.events && (
          <CardContent>
            {loading ? (
              <div className="flex items-center justify-center py-8">
                <div className="text-center">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-orange-600 mx-auto mb-2" />
                  <p className="text-sm text-muted-foreground">
                    Carregando eventos...
                  </p>
                </div>
              </div>
            ) : events.length > 0 ? (
              <div className="space-y-4">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-16">Tipo</TableHead>
                      <TableHead>Motivo</TableHead>
                      <TableHead>Mensagem</TableHead>
                      <TableHead className="w-32">Primeira Vez</TableHead>
                      <TableHead className="w-32">Última Vez</TableHead>
                      <TableHead className="w-16">Count</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {events.slice(0, 10).map((event, index) => (
                      <TableRow key={event.metadata?.uid || index}>
                        <TableCell>
                          <Badge
                            variant={
                              event.type === 'Warning'
                                ? 'destructive'
                                : 'default'
                            }
                            className={
                              event.type === 'Warning'
                                ? 'bg-red-100 text-red-800'
                                : 'bg-green-100 text-green-800'
                            }
                          >
                            {event.type}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <span className="font-medium text-sm">
                            {event.reason}
                          </span>
                        </TableCell>
                        <TableCell>
                          <span className="text-sm text-muted-foreground">
                            {event.message}
                          </span>
                        </TableCell>
                        <TableCell>
                          <span className="text-xs text-muted-foreground">
                            {event.firstTimestamp
                              ? new Date(event.firstTimestamp).toLocaleString(
                                  'pt-BR',
                                  {
                                    day: '2-digit',
                                    month: '2-digit',
                                    hour: '2-digit',
                                    minute: '2-digit',
                                  },
                                )
                              : 'N/A'}
                          </span>
                        </TableCell>
                        <TableCell>
                          <span className="text-xs text-muted-foreground">
                            {event.lastTimestamp
                              ? new Date(event.lastTimestamp).toLocaleString(
                                  'pt-BR',
                                  {
                                    day: '2-digit',
                                    month: '2-digit',
                                    hour: '2-digit',
                                    minute: '2-digit',
                                  },
                                )
                              : 'N/A'}
                          </span>
                        </TableCell>
                        <TableCell>
                          <span className="text-sm">{event.count || 1}</span>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            ) : (
              <div className="text-center py-8">
                <div className="text-muted-foreground">
                  <Activity className="h-8 w-8 mx-auto mb-2 opacity-50" />
                  <p>Nenhum evento encontrado para este Job</p>
                </div>
              </div>
            )}
          </CardContent>
        )}
      </Card>

      {/* Modal de Confirmação para Cancelar Job */}
      <Dialog open={cancelModalOpen} onOpenChange={setCancelModalOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Cancelar Job</DialogTitle>
            <DialogDescription>
              Tem certeza que deseja cancelar o job <strong>{jobName}</strong>?
              <br />
              <br />
              Esta ação irá:
              <ul className="list-disc list-inside mt-2 text-sm">
                <li>Parar todos os pods em execução</li>
                <li>Remover o job do cluster</li>
                <li>Não pode ser desfeita</li>
              </ul>
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setCancelModalOpen(false)}
              disabled={cancelling}
            >
              Cancelar
            </Button>
            <Button
              variant="destructive"
              onClick={handleCancelJob}
              disabled={cancelling}
            >
              {cancelling ? (
                <>
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2" />
                  Cancelando...
                </>
              ) : (
                <>
                  <Trash2 className="h-4 w-4 mr-2" />
                  Confirmar Cancelamento
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
