import React, { useState, useEffect } 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 { YamlEditor } from '@/components/ui/yaml-editor';
import { LogsModal } from '@/components/ui/logs-modal';
import { TooltipProvider } from '@/components/ui/tooltip';
import { useCronJobDetails, useKubectl } from '@/hooks/useKubectl';
import { useToast } from '@/hooks/useToast';
import {
  Loader2,
  ArrowLeft,
  XCircle,
  Clock,
  Container,
  Activity,
  AlertTriangle,
  Info,
  Play,
  Pause,
  ChevronDown,
  ChevronUp,
  Eye,
  AlertCircle,
  MoreVertical,
  Trash2,
  CheckCircle,
  Calendar,
  Zap,
  Settings,
  Terminal,
  FileText,
} from 'lucide-react';

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

  const {
    cronJobInfo,
    jobs,
    events,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  } = useCronJobDetails(cronJobName || '', namespaceName || '');

  const [autoRefresh, setAutoRefresh] = useState(true);
  const [cronJobRefreshInterval, setCronJobRefreshInterval] = useState(5000);
  const [expandedSections, setExpandedSections] = useState({
    jobs: true,
    events: true,
  });
  const [suspending, setSuspending] = useState(false);
  const [resuming, setResuming] = useState(false);
  const [triggering, setTriggering] = useState(false);
  const [yamlDrawerOpen, setYamlDrawerOpen] = useState(false);

  const [deleteJobModalOpen, setDeleteJobModalOpen] = useState(false);
  const [jobToDelete, setJobToDelete] = useState<{
    name: string;
    namespace: string;
  } | null>(null);
  const [deletingJob, setDeletingJob] = useState(false);
  const [selectedEvent, setSelectedEvent] = useState<any>(null);
  const [deleteEventModalOpen, setDeleteEventModalOpen] = useState(false);
  const [eventToDelete, setEventToDelete] = useState<any>(null);
  const [deletingEvent, setDeletingEvent] = useState(false);
  const [selectedJobForLogs, setSelectedJobForLogs] = useState<any>(null);
  const [logsModalOpen, setLogsModalOpen] = useState(false);

  // Auto-refresh with configurable interval
  useEffect(() => {
    if (!autoRefresh) return;

    const intervalId = setInterval(async () => {
      if (
        !suspending &&
        !resuming &&
        !triggering &&
        !yamlDrawerOpen &&
        !isRefreshing &&
        !deleteJobModalOpen &&
        !deletingJob
      ) {
        await backgroundRefetch();
      }
    }, cronJobRefreshInterval);

    return () => {
      clearInterval(intervalId);
    };
  }, [
    autoRefresh,
    cronJobRefreshInterval,
    suspending,
    resuming,
    triggering,
    yamlDrawerOpen,
    isRefreshing,
    deleteJobModalOpen,
    deletingJob,
    backgroundRefetch,
  ]);

  const toggleSection = (section: keyof typeof expandedSections) => {
    setExpandedSections((prev) => ({
      ...prev,
      [section]: !prev[section],
    }));
  };

  const handleSuspend = async () => {
    if (!cronJobName || !namespaceName) return;

    setSuspending(true);
    try {
      const command = `kubectl patch cronjob ${cronJobName} -n ${namespaceName} -p '{"spec":{"suspend":true}}'`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'CronJob Suspenso',
          description: `O cronjob "${cronJobName}" foi suspenso com sucesso`,
          variant: 'success',
        });
        setTimeout(() => {
          backgroundRefetch();
        }, 2000);
      } else {
        showToast({
          title: 'Erro ao Suspender',
          description: result.error || 'Falha ao suspender cronjob',
          variant: 'destructive',
        });
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setSuspending(false);
    }
  };

  const handleResume = async () => {
    if (!cronJobName || !namespaceName) return;

    setResuming(true);
    try {
      const command = `kubectl patch cronjob ${cronJobName} -n ${namespaceName} -p '{"spec":{"suspend":false}}'`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'CronJob Retomado',
          description: `O cronjob "${cronJobName}" foi retomado com sucesso`,
          variant: 'success',
        });
        setTimeout(() => {
          backgroundRefetch();
        }, 2000);
      } else {
        showToast({
          title: 'Erro ao Retomar',
          description: result.error || 'Falha ao retomar cronjob',
          variant: 'destructive',
        });
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setResuming(false);
    }
  };

  const handleTrigger = async () => {
    if (!cronJobName || !namespaceName) return;

    setTriggering(true);
    try {
      const timestamp = new Date().getTime();
      const command = `kubectl create job --from=cronjob/${cronJobName} ${cronJobName}-manual-${timestamp} -n ${namespaceName}`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'Job Criado',
          description: `Job manual criado para o cronjob "${cronJobName}"`,
          variant: 'success',
        });
        setTimeout(() => {
          backgroundRefetch();
        }, 2000);
      } else {
        showToast({
          title: 'Erro ao Criar Job',
          description: result.error || 'Falha ao criar job manual',
          variant: 'destructive',
        });
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setTriggering(false);
    }
  };

  const handleDeleteJobClick = (jobName: string, jobNamespace: string) => {
    setJobToDelete({ name: jobName, namespace: jobNamespace });
    setDeleteJobModalOpen(true);
  };

  const handleViewJob = async (job: any) => {
    // Check if job still exists before navigating
    const jobName = job.metadata?.name;
    const jobNamespace = job.metadata?.namespace;

    if (!jobName || !jobNamespace) {
      showToast({
        title: 'Erro',
        description: 'Informações do job não disponíveis',
        variant: 'destructive',
      });
      return;
    }

    // Try to get job to see if it still exists
    const result = await executeCommand(
      `kubectl get job ${jobName} -n ${jobNamespace} -o json`,
    );

    if (result.success) {
      // Job exists, navigate to details page
      navigate(`/workloads/jobs/${jobNamespace}/${jobName}`);
    } else {
      // Job doesn't exist, show error and refresh the page
      showToast({
        title: 'Job não encontrado',
        description: `O job "${jobName}" não foi encontrado. Pode ter sido deletado ou completado.`,
        variant: 'destructive',
      });
      // Refresh the page to update the jobs list
      backgroundRefetch();
    }
  };

  const handleJobLogs = (job: any) => {
    setSelectedJobForLogs(job);
    setLogsModalOpen(true);
  };

  const handleConfirmDeleteJob = async () => {
    if (!jobToDelete) return;

    setDeletingJob(true);
    try {
      const command = `kubectl delete job ${jobToDelete.name} -n ${jobToDelete.namespace}`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'Job Deletado',
          description: `Job "${jobToDelete.name}" foi deletado com sucesso`,
          variant: 'success',
        });
        setDeleteJobModalOpen(false);
        setJobToDelete(null);
        setTimeout(() => {
          backgroundRefetch();
        }, 1000);
      } else {
        showToast({
          title: 'Erro ao Deletar',
          description: result.error || 'Falha ao deletar job',
          variant: 'destructive',
        });
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setDeletingJob(false);
    }
  };

  const handleDeleteEventClick = (event: any) => {
    setEventToDelete(event);
    setDeleteEventModalOpen(true);
  };

  const handleConfirmDeleteEvent = async () => {
    if (!eventToDelete) return;

    setDeletingEvent(true);
    try {
      const command = `kubectl delete event ${eventToDelete.metadata.name} -n ${namespaceName}`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'Evento Deletado',
          description: 'Evento foi deletado com sucesso',
          variant: 'success',
        });
        setDeleteEventModalOpen(false);
        setEventToDelete(null);
        setTimeout(() => {
          backgroundRefetch();
        }, 1000);
      } else {
        showToast({
          title: 'Erro ao Deletar',
          description: result.error || 'Falha ao deletar evento',
          variant: 'destructive',
        });
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setDeletingEvent(false);
    }
  };

  const formatTimestamp = (timestamp: string): string => {
    if (!timestamp) return 'N/A';
    const date = new Date(timestamp);
    return new Intl.DateTimeFormat('pt-BR', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
    }).format(date);
  };

  const getAge = (creationTimestamp: string): string => {
    if (!creationTimestamp) return 'N/A';
    const now = new Date();
    const created = new Date(creationTimestamp);
    const diffMs = now.getTime() - created.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`;
    if (diffHours > 0) return `${diffHours}h`;
    if (diffMinutes > 0) return `${diffMinutes}m`;
    return `${diffSeconds}s`;
  };

  const getJobStatus = (status: string) => {
    switch (status?.toLowerCase()) {
      case 'running':
        return { icon: CheckCircle, color: 'text-blue-600' };
      case 'succeeded':
        return { icon: CheckCircle, color: 'text-green-600' };
      case 'failed':
        return { icon: XCircle, color: 'text-red-600' };
      case 'pending':
        return { icon: Clock, color: 'text-yellow-600' };
      default:
        return { icon: AlertTriangle, color: 'text-gray-600' };
    }
  };

  const getStatusBadge = (status: string) => {
    const statusInfo = getJobStatus(status);
    const StatusIcon = statusInfo.icon;

    return (
      <div className="flex items-center space-x-2">
        <StatusIcon className={`h-4 w-4 ${statusInfo.color}`} />
        <Badge variant="outline" className="text-xs">
          {status || 'Unknown'}
        </Badge>
      </div>
    );
  };

  const getCronJobStatusBadge = (cronJob: any) => {
    if (!cronJob) return <Badge variant="secondary">Unknown</Badge>;

    if (cronJob.spec?.suspend) {
      return <Badge className="bg-gray-100 text-gray-800">Suspended</Badge>;
    }

    return <Badge className="bg-green-100 text-green-800">Active</Badge>;
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="h-8 w-8 animate-spin" />
        <span className="ml-2">Carregando detalhes do CronJob...</span>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex flex-col items-center justify-center h-64">
        <XCircle className="h-8 w-8 text-red-500 mb-2" />
        <span className="text-red-600">{error}</span>
        <Button onClick={refetch} className="mt-4">
          Tentar Novamente
        </Button>
      </div>
    );
  }

  if (!cronJobInfo) {
    return (
      <div className="flex flex-col items-center justify-center h-64">
        <AlertCircle className="h-8 w-8 text-yellow-500 mb-2" />
        <span>CronJob não encontrado</span>
      </div>
    );
  }

  return (
    <TooltipProvider>
      <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">
                <Clock className="h-8 w-8 mr-3 text-blue-600" />
                {cronJobName}
              </h1>
              <div className="text-muted-foreground">
                CronJob no namespace{' '}
                <Badge variant="outline">{namespaceName}</Badge>
              </div>
            </div>
          </div>
          <div className="flex items-center space-x-2">
            {/* Split button - Live/Manual com dropdown de tempo */}
            <div className="flex">
              {/* Botão principal - Play/Pause */}
              <Button
                onClick={() => setAutoRefresh(!autoRefresh)}
                variant="ghost"
                className="rounded-r-none border-r-0 text-muted-foreground hover:text-foreground hover:bg-muted/50"
                title={
                  autoRefresh
                    ? 'Pausar atualização automática'
                    : 'Ativar atualização automática'
                }
              >
                {autoRefresh ? (
                  <>
                    <Pause className="h-4 w-4 mr-2" />
                    Live ({cronJobRefreshInterval / 1000}s)
                  </>
                ) : (
                  <>
                    <Play className="h-4 w-4 mr-2" />
                    Atualizar
                  </>
                )}
              </Button>

              {/* Dropdown de tempo */}
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button
                    variant="ghost"
                    className="rounded-l-none px-2 h-10 text-muted-foreground hover:text-foreground hover:bg-muted/50"
                    title="Configurar intervalo de refresh"
                  >
                    <ChevronDown className="h-4 w-4" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                  <DropdownMenuLabel>
                    Intervalo de atualização
                  </DropdownMenuLabel>
                  <DropdownMenuSeparator />
                  <DropdownMenuItem
                    onClick={() => setCronJobRefreshInterval(3000)}
                    className={
                      cronJobRefreshInterval === 3000 ? 'bg-green-100' : ''
                    }
                  >
                    3 segundos
                  </DropdownMenuItem>
                  <DropdownMenuItem
                    onClick={() => setCronJobRefreshInterval(5000)}
                    className={
                      cronJobRefreshInterval === 5000 ? 'bg-green-100' : ''
                    }
                  >
                    5 segundos
                  </DropdownMenuItem>
                  <DropdownMenuItem
                    onClick={() => setCronJobRefreshInterval(10000)}
                    className={
                      cronJobRefreshInterval === 10000 ? 'bg-green-100' : ''
                    }
                  >
                    10 segundos
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
          </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={cronJobInfo?.spec?.suspend ? 'destructive' : 'default'}
                className={
                  cronJobInfo?.spec?.suspend
                    ? ''
                    : 'bg-blue-100 text-blue-800 hover:bg-blue-200'
                }
              >
                {cronJobInfo?.spec?.suspend ? 'Suspenso' : '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">
                Última Execução
              </CardTitle>
              <CheckCircle className="h-4 w-4 text-green-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {cronJobInfo?.status?.lastScheduleTime
                  ? new Date(
                      cronJobInfo.status.lastScheduleTime,
                    ).toLocaleDateString('pt-BR')
                  : 'N/A'}
              </div>
              <p className="text-xs text-muted-foreground">
                {cronJobInfo?.status?.lastScheduleTime
                  ? new Date(
                      cronJobInfo.status.lastScheduleTime,
                    ).toLocaleTimeString('pt-BR')
                  : 'Nunca executado'}
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Jobs Ativos</CardTitle>
              <Container className="h-4 w-4 text-purple-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{jobs?.length || 0}</div>
              <p className="text-xs text-muted-foreground">Jobs em execução</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">
                {cronJobInfo?.metadata?.creationTimestamp
                  ? (() => {
                      const now = new Date();
                      const created = new Date(
                        cronJobInfo.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} dias`;
                      if (diffHours > 0) return `${diffHours}h`;
                      return `${diffMinutes}m`;
                    })()
                  : 'N/A'}
              </div>
              <p className="text-xs text-muted-foreground">
                {cronJobInfo?.metadata?.creationTimestamp
                  ? new Date(
                      cronJobInfo.metadata.creationTimestamp,
                    ).toLocaleDateString('pt-BR')
                  : 'Data não disponível'}
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Schedule</CardTitle>
              <Zap className="h-4 w-4 text-indigo-600" />
            </CardHeader>
            <CardContent>
              <div className="text-lg font-bold font-mono">
                {cronJobInfo?.spec?.schedule || 'N/A'}
              </div>
              <p className="text-xs text-muted-foreground">Expressão cron</p>
            </CardContent>
          </Card>
        </div>

        {/* CronJob Configuration */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <CardTitle className="flex items-center">
                <Settings className="h-5 w-5 mr-2" />
                Configuração do CronJob
              </CardTitle>
              <div className="flex gap-2">
                {cronJobInfo?.spec?.suspend ? (
                  <Button
                    onClick={handleResume}
                    disabled={resuming}
                    size="sm"
                    className="bg-green-600 hover:bg-green-700"
                  >
                    {resuming ? (
                      <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                    ) : (
                      <Play className="h-4 w-4 mr-2" />
                    )}
                    {resuming ? 'Retomando...' : 'Retomar'}
                  </Button>
                ) : (
                  <Button
                    onClick={handleSuspend}
                    disabled={suspending}
                    variant="outline"
                    size="sm"
                  >
                    {suspending ? (
                      <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                    ) : (
                      <Pause className="h-4 w-4 mr-2" />
                    )}
                    {suspending ? 'Suspendendo...' : 'Suspender'}
                  </Button>
                )}
                <Button
                  onClick={handleTrigger}
                  disabled={triggering}
                  variant="outline"
                  size="sm"
                >
                  {triggering ? (
                    <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  ) : (
                    <Play className="h-4 w-4 mr-2" />
                  )}
                  {triggering ? 'Criando...' : 'Trigger Manual'}
                </Button>
                <Button variant="outline" size="sm" disabled>
                  <Terminal className="h-4 w-4 mr-2" />
                  Terminal
                </Button>
                <Button variant="outline" size="sm" disabled>
                  <FileText className="h-4 w-4 mr-2" />
                  Logs
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setYamlDrawerOpen(true)}
                >
                  <Eye className="h-4 w-4 mr-2" />
                  YAML
                </Button>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-12">
              {/* Coluna 1: Informações Básicas */}
              <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-semibold text-right ml-4">
                    {cronJobInfo?.metadata?.name}
                  </span>
                </div>
                <div className="flex justify-between items-start min-h-[20px]">
                  <span className="text-sm text-muted-foreground font-medium">
                    Schedule:
                  </span>
                  <span className="text-sm font-semibold text-right ml-4 font-mono">
                    {cronJobInfo?.spec?.schedule || 'N/A'}
                  </span>
                </div>
                <div className="flex justify-between items-start min-h-[20px]">
                  <span className="text-sm text-muted-foreground font-medium">
                    Status:
                  </span>
                  <span className="text-sm font-semibold text-right ml-4">
                    {cronJobInfo?.spec?.suspend ? 'Suspenso' : 'Ativo'}
                  </span>
                </div>
              </div>

              {/* Coluna 2: Configurações de Execução */}
              <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">
                    Concurrency Policy:
                  </span>
                  <span className="text-sm font-semibold text-right ml-4">
                    {cronJobInfo?.spec?.concurrencyPolicy || 'Allow'}
                  </span>
                </div>
                <div className="flex justify-between items-start min-h-[20px]">
                  <span className="text-sm text-muted-foreground font-medium">
                    Starting Deadline:
                  </span>
                  <span className="text-sm font-semibold text-right ml-4">
                    {cronJobInfo?.spec?.startingDeadlineSeconds
                      ? `${cronJobInfo.spec.startingDeadlineSeconds}s`
                      : 'Sem limite'}
                  </span>
                </div>
                <div className="flex justify-between items-start min-h-[20px]">
                  <span className="text-sm text-muted-foreground font-medium">
                    Success Jobs History:
                  </span>
                  <span className="text-sm font-semibold text-right ml-4">
                    {cronJobInfo?.spec?.successfulJobsHistoryLimit ?? '3'}
                  </span>
                </div>
              </div>

              {/* Coluna 3: Histórico e Políticas */}
              <div className="space-y-5">
                <div className="flex justify-between items-start min-h-[20px]">
                  <span className="text-sm text-muted-foreground font-medium">
                    Failed Jobs History:
                  </span>
                  <span className="text-sm font-semibold text-right ml-4">
                    {cronJobInfo?.spec?.failedJobsHistoryLimit ?? '1'}
                  </span>
                </div>
                <div className="flex justify-between items-start min-h-[20px]">
                  <span className="text-sm text-muted-foreground font-medium">
                    Última Execução:
                  </span>
                  <span className="text-sm font-semibold text-right ml-4">
                    {cronJobInfo?.status?.lastScheduleTime
                      ? new Date(
                          cronJobInfo.status.lastScheduleTime,
                        ).toLocaleDateString('pt-BR')
                      : 'Nunca'}
                  </span>
                </div>
                <div className="flex justify-between items-start min-h-[20px]">
                  <span className="text-sm text-muted-foreground font-medium">
                    Jobs Ativos:
                  </span>
                  <span className="text-sm font-semibold text-right ml-4">
                    {cronJobInfo?.status?.active?.length || 0}
                  </span>
                </div>
              </div>
            </div>

            {/* Labels Section */}
            <div className="mt-6 pt-4 border-t">
              <h4 className="font-medium text-sm text-muted-foreground mb-2">
                Labels
              </h4>
              <div className="flex flex-wrap gap-1">
                {Object.entries(cronJobInfo?.metadata?.labels || {}).length >
                0 ? (
                  Object.entries(cronJobInfo?.metadata?.labels || {}).map(
                    ([key, value]) => (
                      <Badge key={key} variant="secondary" className="text-xs">
                        {key}: {value}
                      </Badge>
                    ),
                  )
                ) : (
                  <span className="text-sm text-muted-foreground">
                    Nenhum label definido
                  </span>
                )}
              </div>
            </div>

            {/* Annotations Section */}
            <div className="mt-4">
              <h4 className="font-medium text-sm text-muted-foreground mb-2">
                Annotations
              </h4>
              <div className="flex flex-wrap gap-1">
                {Object.entries(cronJobInfo?.metadata?.annotations || {})
                  .length > 0 ? (
                  Object.entries(cronJobInfo?.metadata?.annotations || {}).map(
                    ([key, value]) => (
                      <Badge key={key} variant="outline" className="text-xs">
                        {key}: {value}
                      </Badge>
                    ),
                  )
                ) : (
                  <span className="text-sm text-muted-foreground">
                    Nenhuma annotation definida
                  </span>
                )}
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Jobs Section */}
        <Card>
          <CardHeader>
            <CardTitle
              className="flex items-center justify-between cursor-pointer"
              onClick={() => toggleSection('jobs')}
            >
              <div className="flex items-center">
                <Container className="h-5 w-5 mr-2" />
                Jobs ({jobs?.length || 0})
              </div>
              {expandedSections.jobs ? (
                <ChevronUp className="h-4 w-4" />
              ) : (
                <ChevronDown className="h-4 w-4" />
              )}
            </CardTitle>
          </CardHeader>
          {expandedSections.jobs && (
            <CardContent>
              {jobs && jobs.length > 0 ? (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Nome</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead>Início</TableHead>
                      <TableHead>Duração</TableHead>
                      <TableHead>Idade</TableHead>
                      <TableHead>Ações</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {jobs.map((job: any, index: number) => (
                      <TableRow key={index}>
                        <TableCell className="font-medium">
                          <span
                            className="cursor-pointer hover:text-blue-600 transition-colors hover:underline"
                            onClick={() => handleViewJob(job)}
                            title={`${job.metadata?.name} - Clique para ver detalhes do job`}
                          >
                            {job.metadata?.name}
                          </span>
                        </TableCell>
                        <TableCell>
                          {getStatusBadge(
                            job.status?.conditions?.[0]?.type === 'Complete'
                              ? 'Succeeded'
                              : job.status?.conditions?.[0]?.type === 'Failed'
                                ? 'Failed'
                                : job.status?.active > 0
                                  ? 'Running'
                                  : 'Pending',
                          )}
                        </TableCell>
                        <TableCell>
                          {job.status?.startTime
                            ? formatTimestamp(job.status.startTime)
                            : 'N/A'}
                        </TableCell>
                        <TableCell>
                          {job.status?.startTime && job.status?.completionTime
                            ? `${Math.floor(
                                (new Date(job.status.completionTime).getTime() -
                                  new Date(job.status.startTime).getTime()) /
                                  1000,
                              )}s`
                            : job.status?.startTime
                              ? `${Math.floor(
                                  (new Date().getTime() -
                                    new Date(job.status.startTime).getTime()) /
                                    1000,
                                )}s`
                              : 'N/A'}
                        </TableCell>
                        <TableCell>
                          {getAge(job.metadata?.creationTimestamp || '')}
                        </TableCell>
                        <TableCell>
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <Button variant="ghost" size="sm">
                                <MoreVertical className="h-4 w-4" />
                              </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                              <DropdownMenuLabel>Ações</DropdownMenuLabel>
                              <DropdownMenuSeparator />
                              <DropdownMenuItem
                                onClick={() => handleViewJob(job)}
                              >
                                <Eye className="h-4 w-4 mr-2" />
                                Visualizar Job
                              </DropdownMenuItem>
                              <DropdownMenuItem
                                onClick={() => handleJobLogs(job)}
                              >
                                <FileText className="h-4 w-4 mr-2" />
                                Visualizar Logs
                              </DropdownMenuItem>
                              <DropdownMenuSeparator />
                              <DropdownMenuItem
                                onClick={() =>
                                  handleDeleteJobClick(
                                    job.metadata?.name,
                                    job.metadata?.namespace,
                                  )
                                }
                                className="text-red-600"
                              >
                                <Trash2 className="h-4 w-4 mr-2" />
                                Deletar
                              </DropdownMenuItem>
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              ) : (
                <div className="text-center py-8 text-gray-500">
                  Nenhum job encontrado
                </div>
              )}
            </CardContent>
          )}
        </Card>

        {/* Events Section */}
        <Card>
          <CardHeader>
            <CardTitle
              className="flex items-center justify-between cursor-pointer"
              onClick={() => toggleSection('events')}
            >
              <div className="flex items-center">
                <Activity className="h-5 w-5 mr-2" />
                Eventos ({events?.length || 0})
              </div>
              {expandedSections.events ? (
                <ChevronUp className="h-4 w-4" />
              ) : (
                <ChevronDown className="h-4 w-4" />
              )}
            </CardTitle>
          </CardHeader>
          {expandedSections.events && (
            <CardContent>
              {events && events.length > 0 ? (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Tipo</TableHead>
                      <TableHead>Razão</TableHead>
                      <TableHead>Mensagem</TableHead>
                      <TableHead>Primeira Vez</TableHead>
                      <TableHead>Última Vez</TableHead>
                      <TableHead>Ações</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {events.map((event: any, index: number) => (
                      <TableRow key={index}>
                        <TableCell>
                          <div className="flex items-center">
                            {event.type === 'Warning' ? (
                              <AlertTriangle className="h-4 w-4 text-yellow-500 mr-2" />
                            ) : (
                              <Info className="h-4 w-4 text-blue-500 mr-2" />
                            )}
                            {event.type}
                          </div>
                        </TableCell>
                        <TableCell>{event.reason}</TableCell>
                        <TableCell className="max-w-md truncate">
                          {event.message}
                        </TableCell>
                        <TableCell>
                          {formatTimestamp(event.firstTimestamp)}
                        </TableCell>
                        <TableCell>
                          {formatTimestamp(event.lastTimestamp)}
                        </TableCell>
                        <TableCell>
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <Button variant="ghost" size="sm">
                                <MoreVertical className="h-4 w-4" />
                              </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                              <DropdownMenuLabel>Ações</DropdownMenuLabel>
                              <DropdownMenuSeparator />
                              <DropdownMenuItem
                                onClick={() => setSelectedEvent(event)}
                              >
                                <Eye className="h-4 w-4 mr-2" />
                                Ver Detalhes
                              </DropdownMenuItem>
                              <DropdownMenuItem
                                onClick={() => handleDeleteEventClick(event)}
                                className="text-red-600"
                              >
                                <Trash2 className="h-4 w-4 mr-2" />
                                Deletar
                              </DropdownMenuItem>
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              ) : (
                <div className="text-center py-8 text-gray-500">
                  Nenhum evento encontrado
                </div>
              )}
            </CardContent>
          )}
        </Card>

        {/* Delete Job Confirmation Modal */}
        <Dialog open={deleteJobModalOpen} onOpenChange={setDeleteJobModalOpen}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Confirmar Exclusão do Job</DialogTitle>
              <DialogDescription>
                Tem certeza que deseja deletar o job{' '}
                <strong>"{jobToDelete?.name}"</strong>? Esta ação não pode ser
                desfeita.
              </DialogDescription>
            </DialogHeader>
            <DialogFooter>
              <Button
                variant="outline"
                onClick={() => {
                  setDeleteJobModalOpen(false);
                  setJobToDelete(null);
                }}
                disabled={deletingJob}
              >
                Cancelar
              </Button>
              <Button
                variant="destructive"
                onClick={handleConfirmDeleteJob}
                disabled={deletingJob}
              >
                {deletingJob && (
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                )}
                {deletingJob ? 'Deletando...' : 'Sim, Deletar'}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Delete Event Confirmation Modal */}
        <Dialog
          open={deleteEventModalOpen}
          onOpenChange={setDeleteEventModalOpen}
        >
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Confirmar Exclusão do Evento</DialogTitle>
              <DialogDescription>
                Tem certeza que deseja deletar este evento? Esta ação não pode
                ser desfeita.
              </DialogDescription>
            </DialogHeader>
            <DialogFooter>
              <Button
                variant="outline"
                onClick={() => {
                  setDeleteEventModalOpen(false);
                  setEventToDelete(null);
                }}
                disabled={deletingEvent}
              >
                Cancelar
              </Button>
              <Button
                variant="destructive"
                onClick={handleConfirmDeleteEvent}
                disabled={deletingEvent}
              >
                {deletingEvent && (
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                )}
                {deletingEvent ? 'Deletando...' : 'Sim, Deletar'}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Event Details Modal */}
        <Dialog
          open={!!selectedEvent}
          onOpenChange={() => setSelectedEvent(null)}
        >
          <DialogContent className="max-w-2xl">
            <DialogHeader>
              <DialogTitle>Detalhes do Evento</DialogTitle>
            </DialogHeader>
            {selectedEvent && (
              <div className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <p className="text-sm font-medium text-gray-500">Tipo</p>
                    <p className="text-sm">{selectedEvent.type}</p>
                  </div>
                  <div>
                    <p className="text-sm font-medium text-gray-500">Razão</p>
                    <p className="text-sm">{selectedEvent.reason}</p>
                  </div>
                  <div>
                    <p className="text-sm font-medium text-gray-500">
                      Primeira Vez
                    </p>
                    <p className="text-sm">
                      {formatTimestamp(selectedEvent.firstTimestamp)}
                    </p>
                  </div>
                  <div>
                    <p className="text-sm font-medium text-gray-500">
                      Última Vez
                    </p>
                    <p className="text-sm">
                      {formatTimestamp(selectedEvent.lastTimestamp)}
                    </p>
                  </div>
                </div>
                <div>
                  <p className="text-sm font-medium text-gray-500 mb-2">
                    Mensagem
                  </p>
                  <p className="text-sm bg-gray-50 p-3 rounded border">
                    {selectedEvent.message}
                  </p>
                </div>
              </div>
            )}
          </DialogContent>
        </Dialog>

        {/* Logs Modal */}
        <LogsModal
          open={logsModalOpen}
          onOpenChange={setLogsModalOpen}
          podName={selectedJobForLogs?.metadata?.name || ''}
          namespace={namespaceName || ''}
          title={`Logs do Job - ${selectedJobForLogs?.metadata?.name || ''}`}
        />

        {/* YAML Editor */}
        <YamlEditor
          open={yamlDrawerOpen}
          onOpenChange={setYamlDrawerOpen}
          resourceType="cronjob"
          resourceName={cronJobName || ''}
          namespace={namespaceName || ''}
          title={`YAML do CronJob - ${cronJobName}`}
          onSave={() => {
            setTimeout(() => {
              backgroundRefetch();
            }, 1000);
          }}
        />
      </div>
    </TooltipProvider>
  );
}
