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 {
  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 {
  useJobsInfo,
  useKubectl,
  JobInfo,
  useNamespacesInfo,
} from '@/hooks/useKubectl';
import { useToast } from '@/hooks/useToast';
import { useGlobalNamespace } from '@/hooks/useGlobalNamespace';
import {
  Loader2,
  Play,
  AlertCircle,
  RefreshCw,
  Search,
  MoreVertical,
  Trash2,
  Eye,
  CheckCircle,
  XCircle,
  Clock,
  Activity,
  Pause,
  AlertTriangle,
  Zap,
  Timer,
  Filter,
  ChevronDown,
} from 'lucide-react';
import { Input } from '@/components/ui/input';

export function JobsPage() {
  const navigate = useNavigate();
  const { showToast } = useToast();
  const { executeCommand } = useKubectl();
  const {
    jobs,
    namespaces: jobsNamespaces,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  } = useJobsInfo();
  const { namespaces: allNamespacesData } = useNamespacesInfo();
  const { selectedNamespace, setSelectedNamespace } = useGlobalNamespace();

  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [sortField, setSortField] = useState<keyof JobInfo>('name');
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc');
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [jobToDelete, setJobToDelete] = useState<JobInfo | null>(null);
  const [deleting, setDeleting] = useState(false);
  const [autoRefresh, setAutoRefresh] = useState(true);
  const [jobRefreshInterval, setJobRefreshInterval] = useState(8000); // 8 segundos

  // Usa todos os namespaces do cluster
  const namespaces = allNamespacesData.map((ns) => ns.name).sort();

  const getJobStatus = (job: JobInfo) => {
    if (job.active > 0) {
      return {
        label: 'Ativo',
        color: 'text-blue-600',
        bgColor: 'bg-blue-100',
        icon: Activity,
      };
    }

    if (job.failed > 0) {
      return {
        label: 'Falhou',
        color: 'text-red-600',
        bgColor: 'bg-red-100',
        icon: XCircle,
      };
    }

    if (job.succeeded > 0) {
      return {
        label: 'Sucesso',
        color: 'text-green-600',
        bgColor: 'bg-green-100',
        icon: CheckCircle,
      };
    }

    return {
      label: 'Pendente',
      color: 'text-gray-600',
      bgColor: 'bg-gray-100',
      icon: Clock,
    };
  };

  useEffect(() => {
    if (!autoRefresh) return;

    const interval = setInterval(() => {
      backgroundRefetch();
    }, jobRefreshInterval);

    return () => clearInterval(interval);
  }, [autoRefresh, jobRefreshInterval, backgroundRefetch]);

  const filteredAndSortedJobs = useMemo(() => {
    const filtered = jobs.filter((job) => {
      const matchesSearch =
        job.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
        job.namespace.toLowerCase().includes(searchQuery.toLowerCase());
      const matchesNamespace =
        selectedNamespace === 'all' || job.namespace === selectedNamespace;

      // Filter by status
      let matchesStatus = true;
      if (statusFilter !== 'all') {
        const jobStatus = getJobStatus(job);
        switch (statusFilter) {
          case 'active':
            matchesStatus = job.active > 0;
            break;
          case 'succeeded':
            matchesStatus =
              job.succeeded > 0 && job.failed === 0 && job.active === 0;
            break;
          case 'failed':
            matchesStatus = job.failed > 0;
            break;
          default:
            matchesStatus = true;
        }
      }

      return matchesSearch && matchesNamespace && matchesStatus;
    });

    filtered.sort((a, b) => {
      const aValue = a[sortField];
      const bValue = b[sortField];
      const multiplier = sortDirection === 'asc' ? 1 : -1;

      if (typeof aValue === 'string' && typeof bValue === 'string') {
        return aValue.localeCompare(bValue) * multiplier;
      }
      if (typeof aValue === 'number' && typeof bValue === 'number') {
        return (aValue - bValue) * multiplier;
      }
      return 0;
    });

    return filtered;
  }, [jobs, searchQuery, selectedNamespace, sortField, sortDirection]);

  const statusStats = useMemo(() => {
    return {
      total: jobs.length,
      succeeded: jobs.filter(
        (job) => job.succeeded > 0 && job.failed === 0 && job.active === 0,
      ).length,
      failed: jobs.filter((job) => job.failed > 0).length,
      active: jobs.filter((job) => job.active > 0).length,
      completed: jobs.filter((job) => job.completionTime !== null).length,
    };
  }, [jobs]);

  const getAge = (creationTimestamp: string) => {
    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 getDuration = (
    startTime: string | null,
    completionTime: string | null,
  ) => {
    if (!startTime) return '-';

    const start = new Date(startTime);
    const end = completionTime ? new Date(completionTime) : new Date();
    const diffMs = end.getTime() - start.getTime();
    const diffSeconds = Math.floor(diffMs / 1000);
    const diffMinutes = Math.floor(diffSeconds / 60);
    const diffHours = Math.floor(diffMinutes / 60);

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

  const handleSort = (field: keyof JobInfo) => {
    if (sortField === field) {
      setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc');
    } else {
      setSortField(field);
      setSortDirection('asc');
    }
  };

  const handleDeleteClick = (job: JobInfo) => {
    setJobToDelete(job);
    setDeleteModalOpen(true);
  };

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

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

      if (result.success) {
        showToast({
          title: 'Job Excluído',
          description: `Job "${jobToDelete.name}" foi excluído com sucesso`,
          variant: 'success',
        });
        refetch();
      } else {
        showToast({
          title: 'Erro ao Excluir Job',
          description: result.error || 'Falha ao excluir o Job',
          variant: 'destructive',
        });
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setDeleting(false);
      setDeleteModalOpen(false);
      setJobToDelete(null);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="text-center">
          <Loader2 className="h-8 w-8 animate-spin mx-auto mb-4" />
          <p className="text-muted-foreground">Carregando Jobs...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="text-center">
          <AlertCircle className="h-8 w-8 text-red-500 mx-auto mb-4" />
          <p className="text-red-600 mb-4">{error}</p>
          <Button onClick={() => refetch()}>
            <RefreshCw className="h-4 w-4 mr-2" />
            Tentar Novamente
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-foreground flex items-center">
            <Play className="h-8 w-8 mr-3 text-blue-600" />
            Jobs
          </h1>
          <p className="text-muted-foreground">
            Gerencie jobs batch no cluster Kubernetes
          </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 ({jobRefreshInterval / 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={() => setJobRefreshInterval(1000)}
                  className={jobRefreshInterval === 1000 ? 'bg-green-100' : ''}
                >
                  1 segundo
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setJobRefreshInterval(3000)}
                  className={jobRefreshInterval === 3000 ? 'bg-green-100' : ''}
                >
                  3 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setJobRefreshInterval(5000)}
                  className={jobRefreshInterval === 5000 ? 'bg-green-100' : ''}
                >
                  5 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setJobRefreshInterval(8000)}
                  className={jobRefreshInterval === 8000 ? 'bg-green-100' : ''}
                >
                  8 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setJobRefreshInterval(10000)}
                  className={jobRefreshInterval === 10000 ? 'bg-green-100' : ''}
                >
                  10 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setJobRefreshInterval(30000)}
                  className={jobRefreshInterval === 30000 ? 'bg-green-100' : ''}
                >
                  30 segundos
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline">
                <MoreVertical className="h-4 w-4 mr-2" />
                Ações
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuLabel>Ações de Job</DropdownMenuLabel>
              <DropdownMenuSeparator />
              {/* Placeholder para futuras ações */}
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </div>

      {/* Stats 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">Total</CardTitle>
            <Play className="h-4 w-4 text-blue-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{statusStats.total}</div>
            <p className="text-xs text-muted-foreground">Jobs no cluster</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Sucessos</CardTitle>
            <CheckCircle className="h-4 w-4 text-green-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">
              {statusStats.succeeded}
            </div>
            <p className="text-xs text-muted-foreground">
              Completados com sucesso
            </p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Falhas</CardTitle>
            <XCircle className="h-4 w-4 text-red-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-red-600">
              {statusStats.failed}
            </div>
            <p className="text-xs text-muted-foreground">Jobs com falha</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>
            <Activity className="h-4 w-4 text-blue-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-blue-600">
              {statusStats.active}
            </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">Completados</CardTitle>
            <Timer className="h-4 w-4 text-purple-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-purple-600">
              {statusStats.completed}
            </div>
            <p className="text-xs text-muted-foreground">Jobs finalizados</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="succeeded">Sucesso</SelectItem>
                  <SelectItem value="failed">Falhou</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 job, namespace..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full"
              />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Jobs Table */}
      <Card>
        <CardHeader>
          <CardTitle>Jobs ({filteredAndSortedJobs.length})</CardTitle>
          <CardDescription>Lista de Jobs no cluster Kubernetes</CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead
                  className="cursor-pointer hover:bg-muted/50"
                  onClick={() => handleSort('name')}
                >
                  Nome
                </TableHead>
                <TableHead
                  className="cursor-pointer hover:bg-muted/50"
                  onClick={() => handleSort('namespace')}
                >
                  Namespace
                </TableHead>
                <TableHead>Completions</TableHead>
                <TableHead>Paralelismo</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Duração</TableHead>
                <TableHead
                  className="cursor-pointer hover:bg-muted/50"
                  onClick={() => handleSort('creationTimestamp')}
                >
                  Idade
                </TableHead>
                <TableHead className="w-16">Ações</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredAndSortedJobs.map((job) => {
                const status = getJobStatus(job);
                const StatusIcon = status.icon;

                return (
                  <TableRow key={`${job.namespace}/${job.name}`}>
                    <TableCell className="font-medium">{job.name}</TableCell>
                    <TableCell>
                      <Badge variant="outline">{job.namespace}</Badge>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center space-x-1">
                        <span className="text-green-600 font-medium">
                          {job.succeeded}
                        </span>
                        <span className="text-muted-foreground">/</span>
                        <span className="text-muted-foreground">
                          {job.completions || '∞'}
                        </span>
                        {job.failed > 0 && (
                          <>
                            <span className="text-muted-foreground">•</span>
                            <span className="text-red-600">
                              {job.failed} falhas
                            </span>
                          </>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant="secondary">{job.parallelism || 1}</Badge>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center">
                        <StatusIcon
                          className={`h-4 w-4 mr-2 ${status.color}`}
                        />
                        <Badge className={`${status.bgColor} ${status.color}`}>
                          {status.label}
                        </Badge>
                        {job.active > 0 && (
                          <Badge
                            variant="outline"
                            className="ml-2 text-blue-600"
                          >
                            {job.active} ativo(s)
                          </Badge>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <span className="font-mono text-sm">
                        {getDuration(job.startTime, job.completionTime)}
                      </span>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm text-muted-foreground">
                        {getAge(job.creationTimestamp)}
                      </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</DropdownMenuLabel>
                          <DropdownMenuItem
                            onClick={() =>
                              navigate(
                                `/workloads/jobs/${job.namespace}/${job.name}`,
                              )
                            }
                          >
                            <Eye className="h-4 w-4 mr-2" />
                            Visualizar
                          </DropdownMenuItem>
                          <DropdownMenuSeparator />
                          <DropdownMenuItem
                            onClick={() => handleDeleteClick(job)}
                            className="text-red-600"
                          >
                            <Trash2 className="h-4 w-4 mr-2" />
                            Excluir
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                );
              })}
              {filteredAndSortedJobs.length === 0 && (
                <TableRow>
                  <TableCell colSpan={8} className="text-center py-8">
                    <div className="text-muted-foreground">
                      <Play className="h-8 w-8 mx-auto mb-2 opacity-50" />
                      <p>Nenhum Job encontrado</p>
                      {(searchQuery || selectedNamespace !== 'all') && (
                        <p className="text-sm mt-1">
                          Tente ajustar os filtros para ver mais resultados
                        </p>
                      )}
                    </div>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* Delete Confirmation Modal */}
      <Dialog open={deleteModalOpen} onOpenChange={setDeleteModalOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Excluir Job</DialogTitle>
            <DialogDescription>
              Tem certeza que deseja excluir o Job{' '}
              <strong>{jobToDelete?.name}</strong> do namespace{' '}
              <strong>{jobToDelete?.namespace}</strong>?
              <br />
              <br />
              Esta ação não pode ser desfeita e irá remover o job e todos os
              pods associados.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setDeleteModalOpen(false)}
              disabled={deleting}
            >
              Cancelar
            </Button>
            <Button
              variant="destructive"
              onClick={handleDeleteJob}
              disabled={deleting}
            >
              {deleting ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  Excluindo...
                </>
              ) : (
                <>
                  <Trash2 className="h-4 w-4 mr-2" />
                  Excluir Job
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
