import React, { useState, useMemo, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  useCronJobsInfo,
  useKubectl,
  useClusterEvents,
} from '@/hooks/useKubectl';
import { useToast } from '@/hooks/useToast';
import { useGlobalNamespace } from '@/hooks/useGlobalNamespace';
import {
  Loader2,
  Clock,
  AlertCircle,
  AlertTriangle,
  RefreshCw,
  Filter,
  CheckCircle,
  XCircle,
  Calendar,
  Tag,
  Activity,
  Server,
  Container,
  Zap,
  MoreVertical,
  Info,
  Trash2,
  ArrowUpDown,
  Plus,
  Minus,
  Pause,
  Play,
  Eye,
  Shield,
  Database,
  Key,
  Copy,
  ChevronDown,
} from 'lucide-react';

export function CronJobsPage() {
  const navigate = useNavigate();
  const {
    cronJobs,
    namespaces,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  } = useCronJobsInfo();
  // const { events: clusterEvents } = useClusterEvents();
  const { executeCommand } = useKubectl();
  const { showToast } = useToast();
  const { selectedNamespace, setSelectedNamespace } = useGlobalNamespace();
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [cronJobToDelete, setCronJobToDelete] = useState<{
    name: string;
    namespace: string;
  } | null>(null);
  const [deleting, setDeleting] = useState(false);
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [autoRefresh, setAutoRefresh] = useState(true);
  const [cronJobRefreshInterval, setCronJobRefreshInterval] = useState(10000); // 10 segundos
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [searchQuery, setSearchQuery] = useState('');

  // Debug logging
  // console.log(
  //   'CronJobsPage render - loading:',
  //   loading,
  //   'error:',
  //   error,
  //   'cronjobs count:',
  //   cronJobs.length,
  // );

  // Validate that saved namespace still exists, otherwise reset to 'all'
  useEffect(() => {
    if (namespaces.length > 0 && selectedNamespace !== 'all') {
      if (!namespaces.includes(selectedNamespace)) {
        setSelectedNamespace('all');
      }
    }
  }, [namespaces, selectedNamespace, setSelectedNamespace]);

  // Intelligent auto-refresh that waits for previous request to complete
  useEffect(() => {
    if (!autoRefresh) return undefined;

    let timeoutId: ReturnType<typeof setTimeout>;

    const scheduleNextRefresh = () => {
      timeoutId = setTimeout(async () => {
        // Only refresh if no modals are open and no actions are in progress
        if (!deleteModalOpen && !deleting && !actionLoading && !isRefreshing) {
          await backgroundRefetch();
        }
        // Schedule the next refresh after this one completes
        scheduleNextRefresh();
      }, cronJobRefreshInterval);
    };

    // Start the first refresh cycle
    scheduleNextRefresh();

    return () => {
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
    };
  }, [
    autoRefresh,
    cronJobRefreshInterval,
    deleteModalOpen,
    deleting,
    actionLoading,
    isRefreshing,
    backgroundRefetch,
  ]);

  const handleDeleteClick = (cronJobName: string, namespaceName: string) => {
    setCronJobToDelete({ name: cronJobName, namespace: namespaceName });
    setDeleteModalOpen(true);
  };

  const handleConfirmDelete = async () => {
    if (!cronJobToDelete) return;

    setDeleting(true);
    try {
      const command = `kubectl delete cronjob ${cronJobToDelete.name} -n ${cronJobToDelete.namespace}`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'CronJob Deletado',
          description: `O cronjob "${cronJobToDelete.name}" foi deletado com sucesso`,
          variant: 'success',
        });
        setDeleteModalOpen(false);
        setCronJobToDelete(null);
        await refetch();
      } else {
        showToast({
          title: 'Erro ao Deletar CronJob',
          description: result.error || 'Falha ao deletar cronjob',
          variant: 'destructive',
        });
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setDeleting(false);
    }
  };

  const handleCronJobAction = async (
    cronJobName: string,
    namespaceName: string,
    action: string,
  ) => {
    if (action === 'visualizar') {
      navigate(`/workloads/cronjobs/${namespaceName}/${cronJobName}`);
      return;
    }

    setActionLoading(`${namespaceName}/${cronJobName}`);
    try {
      let command = '';
      let successMessage = '';

      switch (action) {
        case 'suspend':
          command = `kubectl patch cronjob ${cronJobName} -n ${namespaceName} -p '{"spec":{"suspend":true}}'`;
          successMessage = `CronJob "${cronJobName}" foi suspenso`;
          break;
        case 'resume':
          command = `kubectl patch cronjob ${cronJobName} -n ${namespaceName} -p '{"spec":{"suspend":false}}'`;
          successMessage = `CronJob "${cronJobName}" foi retomado`;
          break;
        case 'trigger':
          // Create a job from the cronjob template
          const timestamp = new Date().getTime();
          command = `kubectl create job --from=cronjob/${cronJobName} ${cronJobName}-manual-${timestamp} -n ${namespaceName}`;
          successMessage = `Job manual criado para o CronJob "${cronJobName}"`;
          break;
        default:
          throw new Error(`Ação desconhecida: ${action}`);
      }

      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'Ação Executada',
          description: successMessage,
          variant: 'success',
        });

        // Aguardar um tempo antes de atualizar para dar tempo do Kubernetes processar
        setTimeout(async () => {
          await backgroundRefetch();
        }, 2000);
      } else {
        showToast({
          title: 'Erro na Ação',
          description: result.error || 'Falha na ação do cronjob',
          variant: 'destructive',
        });
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setActionLoading(null);
    }
  };

  // Filter cronjobs by namespace, status, and search query
  const filteredCronJobs = useMemo(() => {
    let filtered = cronJobs;

    // Filter by namespace
    if (selectedNamespace !== 'all') {
      filtered = filtered.filter(
        (cronJob) => cronJob.namespace === selectedNamespace,
      );
    }

    // Filter by status
    if (statusFilter !== 'all') {
      filtered = filtered.filter((cronJob) => {
        const state = getCronJobState(cronJob);
        switch (statusFilter) {
          case 'active':
            return state === 'active';
          case 'suspended':
            return state === 'suspended';
          case 'waiting':
            return state === 'waiting';
          default:
            return true;
        }
      });
    }

    // Filter by search query
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(
        (cronJob) =>
          cronJob.name.toLowerCase().includes(query) ||
          cronJob.namespace.toLowerCase().includes(query) ||
          cronJob.schedule.toLowerCase().includes(query),
      );
    }

    return filtered;
  }, [cronJobs, selectedNamespace, statusFilter, searchQuery]);

  const totalCronJobs = filteredCronJobs.length;

  // Calculate time since last schedule
  const getLastScheduleInfo = (cronJob: any) => {
    if (!cronJob.lastScheduleTime) {
      return { text: 'Nunca executado', variant: 'secondary' as const };
    }

    const lastSchedule = new Date(cronJob.lastScheduleTime);
    const now = new Date();
    const diffMinutes = Math.floor(
      (now.getTime() - lastSchedule.getTime()) / (1000 * 60),
    );

    if (diffMinutes < 1) {
      return { text: 'Agora mesmo', variant: 'default' as const };
    }
    if (diffMinutes < 60) {
      return { text: `${diffMinutes}m atrás`, variant: 'default' as const };
    }
    if (diffMinutes < 1440) {
      const hours = Math.floor(diffMinutes / 60);
      return { text: `${hours}h atrás`, variant: 'default' as const };
    }
    const days = Math.floor(diffMinutes / 1440);
    return { text: `${days}d atrás`, variant: 'secondary' as const };
  };

  // Get cronjob status
  const getCronJobState = (cronJob: any) => {
    if (cronJob.suspend) {
      return 'suspended';
    }
    if (cronJob.active > 0) {
      return 'active';
    }
    return 'waiting';
  };

  const activeCronJobs = filteredCronJobs.filter(
    (cj) => getCronJobState(cj) === 'active',
  ).length;
  const suspendedCronJobs = filteredCronJobs.filter(
    (cj) => getCronJobState(cj) === 'suspended',
  ).length;
  const waitingCronJobs = filteredCronJobs.filter(
    (cj) => getCronJobState(cj) === 'waiting',
  ).length;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-foreground">CronJobs</h1>
          <p className="text-muted-foreground">
            Gerenciar {totalCronJobs} cronjob(s){' '}
            {selectedNamespace !== 'all'
              ? `no namespace ${selectedNamespace}`
              : 'em todos os namespaces'}
          </p>
        </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 Refresh</DropdownMenuLabel>
                <DropdownMenuSeparator />
                <DropdownMenuItem
                  onClick={() => setCronJobRefreshInterval(1000)}
                  className={
                    cronJobRefreshInterval === 1000 ? 'bg-green-100' : ''
                  }
                >
                  1 segundo
                </DropdownMenuItem>
                <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>
                <DropdownMenuItem
                  onClick={() => setCronJobRefreshInterval(30000)}
                  className={
                    cronJobRefreshInterval === 30000 ? 'bg-green-100' : ''
                  }
                >
                  30 segundos
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>
      </div>

      {/* Overview Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-6 gap-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total</CardTitle>
            <Clock className="h-4 w-4 text-blue-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{totalCronJobs}</div>
            <p className="text-xs text-muted-foreground">CronJobs</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Ativos</CardTitle>
            <CheckCircle className="h-4 w-4 text-green-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{activeCronJobs}</div>
            <p className="text-xs text-muted-foreground">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">Suspensos</CardTitle>
            <AlertTriangle className="h-4 w-4 text-red-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{suspendedCronJobs}</div>
            <p className="text-xs text-muted-foreground">Pausados</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Aguardando</CardTitle>
            <RefreshCw className="h-4 w-4 text-orange-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{waitingCronJobs}</div>
            <p className="text-xs text-muted-foreground">Próxima 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">Schedule</CardTitle>
            <Calendar className="h-4 w-4 text-yellow-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{totalCronJobs}</div>
            <p className="text-xs text-muted-foreground">Agendados</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</CardTitle>
            <Activity className="h-4 w-4 text-purple-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{activeCronJobs}</div>
            <p className="text-xs text-muted-foreground">Jobs ativos</p>
          </CardContent>
        </Card>
      </div>

      {/* Filters Card */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Filter className="h-5 w-5 mr-2" />
            Filtros
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex flex-wrap gap-4">
            <div className="flex-1 min-w-[200px]">
              <label className="text-sm font-medium mb-2 block">
                Namespace
              </label>
              <Select
                value={selectedNamespace}
                onValueChange={setSelectedNamespace}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Selecione um namespace" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">Todos os namespaces</SelectItem>
                  {namespaces.map((ns) => (
                    <SelectItem key={ns} value={ns}>
                      {ns}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="flex-1 min-w-[200px]">
              <label className="text-sm font-medium mb-2 block">Status</label>
              <Select value={statusFilter} onValueChange={setStatusFilter}>
                <SelectTrigger>
                  <SelectValue placeholder="Todos os status" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">Todos os status</SelectItem>
                  <SelectItem value="active">Ativo</SelectItem>
                  <SelectItem value="suspended">Suspenso</SelectItem>
                  <SelectItem value="waiting">Aguardando</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="flex-1 min-w-[200px]">
              <label className="text-sm font-medium mb-2 block">Buscar</label>
              <Input
                type="text"
                placeholder="Nome do cronjob, namespace, schedule..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full"
              />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* CronJobs Table */}
      <Card>
        <CardHeader>
          <CardTitle>Lista de CronJobs</CardTitle>
          <CardDescription>
            {filteredCronJobs.length} cronjob(s) encontrado(s)
            {selectedNamespace !== 'all' && ` em ${selectedNamespace}`}
            {statusFilter !== 'all' && ` com status ${statusFilter}`}
            {searchQuery && ` contendo "${searchQuery}"`}
          </CardDescription>
        </CardHeader>
        <CardContent>
          {loading && !isRefreshing ? (
            <div className="flex items-center justify-center p-8">
              <Loader2 className="h-8 w-8 animate-spin" />
              <span className="ml-2">Carregando cronjobs...</span>
            </div>
          ) : error ? (
            <div className="flex items-center justify-center p-8 text-red-600">
              <AlertCircle className="h-8 w-8 mr-2" />
              <span>Erro: {error}</span>
            </div>
          ) : filteredCronJobs.length === 0 ? (
            <div className="text-center py-8 text-muted-foreground">
              <Clock className="h-8 w-8 mx-auto mb-2 opacity-50" />
              <p>Nenhum cronjob encontrado</p>
              {(statusFilter !== 'all' ||
                searchQuery ||
                selectedNamespace !== 'all') && (
                <p className="text-sm mt-1">
                  Tente ajustar os filtros para ver mais resultados
                </p>
              )}
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Nome</TableHead>
                  <TableHead>Namespace</TableHead>
                  <TableHead>Schedule</TableHead>
                  <TableHead>Estado</TableHead>
                  <TableHead>Última Execução</TableHead>
                  <TableHead>Próxima Execução</TableHead>
                  <TableHead>Jobs Ativos</TableHead>
                  <TableHead className="text-right">Ações</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredCronJobs.map((cronJob, index) => {
                  const state = getCronJobState(cronJob);
                  const lastScheduleInfo = getLastScheduleInfo(cronJob);

                  return (
                    <TableRow key={index} className="h-8">
                      <TableCell className="font-medium">
                        <div
                          className="flex items-center space-x-2 cursor-pointer hover:text-blue-600 transition-colors"
                          onClick={() =>
                            navigate(
                              `/workloads/cronjobs/${cronJob.namespace}/${cronJob.name}`,
                            )
                          }
                          title="Clique para ver detalhes"
                        >
                          <Clock className="h-4 w-4 text-blue-600" />
                          <span className="hover:underline">
                            {cronJob.name}
                          </span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge variant="outline" className="text-xs">
                          {cronJob.namespace}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <code className="text-sm bg-muted px-1 py-0.5 rounded">
                          {cronJob.schedule}
                        </code>
                      </TableCell>
                      <TableCell>
                        <Badge
                          variant={
                            state === 'active'
                              ? 'default'
                              : state === 'suspended'
                                ? 'secondary'
                                : 'outline'
                          }
                          className={
                            state === 'active'
                              ? 'bg-green-100 text-green-800 border-green-300'
                              : state === 'suspended'
                                ? 'bg-orange-100 text-orange-800 border-orange-300'
                                : 'bg-blue-100 text-blue-800 border-blue-300'
                          }
                        >
                          {state === 'active'
                            ? 'Ativo'
                            : state === 'suspended'
                              ? 'Suspenso'
                              : 'Aguardando'}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <Badge variant={lastScheduleInfo.variant}>
                          {lastScheduleInfo.text}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        {cronJob.nextScheduleTime ? (
                          <span className="text-sm">
                            {new Date(
                              cronJob.nextScheduleTime,
                            ).toLocaleString()}
                          </span>
                        ) : (
                          <span className="text-sm text-muted-foreground">
                            -
                          </span>
                        )}
                      </TableCell>
                      <TableCell>
                        <Badge
                          variant={cronJob.active > 0 ? 'default' : 'secondary'}
                        >
                          {cronJob.active}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex items-center justify-end space-x-2">
                          {actionLoading ===
                            `${cronJob.namespace}/${cronJob.name}` && (
                            <Loader2 className="h-4 w-4 animate-spin text-blue-600" />
                          )}
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <Button variant="ghost" size="icon">
                                <MoreVertical className="h-4 w-4" />
                              </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                              <DropdownMenuLabel>
                                Ações do CronJob
                              </DropdownMenuLabel>
                              <DropdownMenuSeparator />
                              <DropdownMenuItem
                                onClick={() =>
                                  handleCronJobAction(
                                    cronJob.name,
                                    cronJob.namespace,
                                    'visualizar',
                                  )
                                }
                                disabled={
                                  actionLoading ===
                                  `${cronJob.namespace}/${cronJob.name}`
                                }
                              >
                                <Info className="h-4 w-4 mr-2" />
                                Visualizar
                              </DropdownMenuItem>
                              <DropdownMenuItem
                                onClick={() =>
                                  handleCronJobAction(
                                    cronJob.name,
                                    cronJob.namespace,
                                    'trigger',
                                  )
                                }
                                disabled={
                                  actionLoading ===
                                  `${cronJob.namespace}/${cronJob.name}`
                                }
                              >
                                <Play className="h-4 w-4 mr-2" />
                                Executar Agora
                              </DropdownMenuItem>
                              {cronJob.suspend ? (
                                <DropdownMenuItem
                                  onClick={() =>
                                    handleCronJobAction(
                                      cronJob.name,
                                      cronJob.namespace,
                                      'resume',
                                    )
                                  }
                                  disabled={
                                    actionLoading ===
                                    `${cronJob.namespace}/${cronJob.name}`
                                  }
                                >
                                  <Play className="h-4 w-4 mr-2" />
                                  Retomar
                                </DropdownMenuItem>
                              ) : (
                                <DropdownMenuItem
                                  onClick={() =>
                                    handleCronJobAction(
                                      cronJob.name,
                                      cronJob.namespace,
                                      'suspend',
                                    )
                                  }
                                  disabled={
                                    actionLoading ===
                                    `${cronJob.namespace}/${cronJob.name}`
                                  }
                                >
                                  <Pause className="h-4 w-4 mr-2" />
                                  Suspender
                                </DropdownMenuItem>
                              )}
                              <DropdownMenuSeparator />
                              <DropdownMenuItem
                                onClick={() =>
                                  handleDeleteClick(
                                    cronJob.name,
                                    cronJob.namespace,
                                  )
                                }
                                disabled={
                                  actionLoading ===
                                  `${cronJob.namespace}/${cronJob.name}`
                                }
                                className="text-red-600"
                              >
                                <Trash2 className="h-4 w-4 mr-2" />
                                Deletar
                              </DropdownMenuItem>
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </div>
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      {/* Delete Confirmation Modal */}
      <Dialog open={deleteModalOpen} onOpenChange={setDeleteModalOpen}>
        <DialogContent className="sm:max-w-[425px]">
          <DialogHeader>
            <DialogTitle className="text-red-600">
              Confirmar Exclusão
            </DialogTitle>
            <DialogDescription>
              Tem certeza que deseja deletar o cronjob{' '}
              <strong>"{cronJobToDelete?.name}"</strong> do namespace{' '}
              <strong>"{cronJobToDelete?.namespace}"</strong>?
            </DialogDescription>
          </DialogHeader>
          <div className="py-4">
            <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
              <div className="flex items-start">
                <AlertCircle className="h-5 w-5 text-yellow-600 mt-0.5 mr-2 flex-shrink-0" />
                <div className="text-sm text-yellow-800">
                  <p className="font-medium mb-1">⚠️ Atenção:</p>
                  <p>Esta ação é irreversível e irá deletar:</p>
                  <ul className="list-disc list-inside mt-2 space-y-1">
                    <li>O cronjob e sua configuração</li>
                    <li>Todos os jobs agendados futuros</li>
                    <li>Jobs ativos em execução</li>
                    <li>Possível interrupção das tarefas programadas</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => {
                setDeleteModalOpen(false);
                setCronJobToDelete(null);
              }}
              disabled={deleting}
            >
              Cancelar
            </Button>
            <Button
              variant="destructive"
              onClick={handleConfirmDelete}
              disabled={deleting}
            >
              {deleting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
              {deleting ? 'Deletando...' : 'Sim, Deletar'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
