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 { useIngressesInfo, useKubectl, IngressInfo } from '@/hooks/useKubectl';
import { useToast } from '@/hooks/useToast';
import { useGlobalNamespace } from '@/hooks/useGlobalNamespace';
import {
  Loader2,
  Globe,
  AlertCircle,
  AlertTriangle,
  RefreshCw,
  Filter,
  CheckCircle,
  XCircle,
  Clock,
  Calendar,
  Tag,
  Activity,
  Server,
  Container,
  Zap,
  MoreVertical,
  Info,
  Trash2,
  ArrowUpDown,
  Plus,
  Minus,
  Pause,
  Play,
  Eye,
  Shield,
  Database,
  Key,
  Copy,
  ExternalLink,
  ChevronDown,
} from 'lucide-react';

export function IngressesPage() {
  const navigate = useNavigate();
  const {
    ingresses,
    namespaces,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  } = useIngressesInfo();
  const { executeCommand } = useKubectl();
  const { showToast } = useToast();
  const { selectedNamespace, setSelectedNamespace } = useGlobalNamespace();

  const [sortField, setSortField] = useState<string>('name');
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc');
  const [searchQuery, setSearchQuery] = useState('');
  const [autoRefresh, setAutoRefresh] = useState(true);
  const [ingressRefreshInterval, setIngressRefreshInterval] = useState(30000); // 30 segundos

  // Modal states
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [selectedIngress, setSelectedIngress] = useState<IngressInfo | null>(
    null,
  );
  const [deleting, setDeleting] = useState(false);

  // Auto-refresh effect
  useEffect(() => {
    if (!autoRefresh) return;

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

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

  // Filter and sort ingresses
  const filteredAndSortedIngresses = useMemo(() => {
    let filtered = ingresses;

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

    // Filter by search query
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(
        (ingress) =>
          ingress.name.toLowerCase().includes(query) ||
          ingress.namespace.toLowerCase().includes(query) ||
          ingress.hosts.some((host) => host.toLowerCase().includes(query)) ||
          ingress.addresses.some((addr) => addr.toLowerCase().includes(query)),
      );
    }

    // Sort
    return filtered.sort((a, b) => {
      let aValue: any;
      let bValue: any;

      switch (sortField) {
        case 'name':
          aValue = a.name;
          bValue = b.name;
          break;
        case 'namespace':
          aValue = a.namespace;
          bValue = b.namespace;
          break;
        case 'className':
          aValue = a.className || '';
          bValue = b.className || '';
          break;
        case 'hosts':
          aValue = a.hosts.length;
          bValue = b.hosts.length;
          break;
        case 'addresses':
          aValue = a.addresses.length;
          bValue = b.addresses.length;
          break;
        case 'age':
          aValue = new Date(a.creationTimestamp).getTime();
          bValue = new Date(b.creationTimestamp).getTime();
          break;
        default:
          aValue = a.name;
          bValue = b.name;
      }

      if (sortDirection === 'asc') {
        return aValue < bValue ? -1 : aValue > bValue ? 1 : 0;
      }
      return aValue > bValue ? -1 : aValue < bValue ? 1 : 0;
    });
  }, [ingresses, selectedNamespace, searchQuery, sortField, sortDirection]);

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

  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 getIngressStatus = (ingress: IngressInfo) => {
    if (ingress.addresses.length > 0) {
      return {
        label: 'Ready',
        color: 'text-green-600',
        bgColor: 'bg-green-100',
        icon: CheckCircle,
      };
    }

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

  const handleDeleteIngress = async () => {
    if (!selectedIngress) return;

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

      if (result.success) {
        showToast({
          title: 'Ingress Excluído',
          description: `Ingress "${selectedIngress.name}" foi excluído com sucesso`,
          variant: 'success',
        });

        backgroundRefetch();
      } else {
        showToast({
          title: 'Erro ao Excluir Ingress',
          description: result.error || 'Falha ao excluir o Ingress',
          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);
      setSelectedIngress(null);
    }
  };

  const handleDeleteClick = (ingress: IngressInfo) => {
    setSelectedIngress(ingress);
    setDeleteModalOpen(true);
  };

  const statusStats = useMemo(() => {
    const filtered =
      selectedNamespace === 'all'
        ? ingresses
        : ingresses.filter(
            (ingress) => ingress.namespace === selectedNamespace,
          );

    return {
      total: filtered.length,
      ready: filtered.filter((ingress) => ingress.addresses.length > 0).length,
      pending: filtered.filter((ingress) => ingress.addresses.length === 0)
        .length,
      withTLS: filtered.filter((ingress) => ingress.tls.length > 0).length,
      totalHosts: filtered.reduce(
        (sum, ingress) => sum + ingress.hosts.length,
        0,
      ),
    };
  }, [ingresses, selectedNamespace]);

  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 Ingresses...</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">
            <Globe className="h-8 w-8 mr-3 text-blue-600" />
            Ingresses
          </h1>
          <p className="text-muted-foreground">
            Gerencie e monitore todos os Ingresses do cluster
          </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 ({ingressRefreshInterval / 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={() => setIngressRefreshInterval(1000)}
                  className={
                    ingressRefreshInterval === 1000 ? 'bg-green-100' : ''
                  }
                >
                  1 segundo
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setIngressRefreshInterval(3000)}
                  className={
                    ingressRefreshInterval === 3000 ? 'bg-green-100' : ''
                  }
                >
                  3 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setIngressRefreshInterval(5000)}
                  className={
                    ingressRefreshInterval === 5000 ? 'bg-green-100' : ''
                  }
                >
                  5 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setIngressRefreshInterval(7000)}
                  className={
                    ingressRefreshInterval === 7000 ? 'bg-green-100' : ''
                  }
                >
                  7 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setIngressRefreshInterval(10000)}
                  className={
                    ingressRefreshInterval === 10000 ? 'bg-green-100' : ''
                  }
                >
                  10 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setIngressRefreshInterval(30000)}
                  className={
                    ingressRefreshInterval === 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 Ingress</DropdownMenuLabel>
              <DropdownMenuSeparator />
              <DropdownMenuItem onClick={() => navigate('/service-discovery/ingresses/create')}>
                <Plus className="h-4 w-4 mr-2" />
                Criar Ingress
              </DropdownMenuItem>
            </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>
            <Globe 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">
              Ingresses 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">Ready</CardTitle>
            <CheckCircle className="h-4 w-4 text-green-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">
              {statusStats.ready}
            </div>
            <p className="text-xs text-muted-foreground">Com endereços</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Pending</CardTitle>
            <Clock className="h-4 w-4 text-yellow-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-yellow-600">
              {statusStats.pending}
            </div>
            <p className="text-xs text-muted-foreground">Aguardando</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">With TLS</CardTitle>
            <Shield className="h-4 w-4 text-green-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-500">
              {statusStats.withTLS}
            </div>
            <p className="text-xs text-muted-foreground">Com HTTPS</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total Hosts</CardTitle>
            <Server className="h-4 w-4 text-blue-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-blue-500">
              {statusStats.totalHosts}
            </div>
            <p className="text-xs text-muted-foreground">Hosts configurados</p>
          </CardContent>
        </Card>
      </div>

      {/* Filters */}
      <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">Buscar</label>
              <input
                type="text"
                placeholder="Nome, namespace, host, endereço..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Ingresses Table */}
      <Card>
        <CardHeader>
          <CardTitle>
            {filteredAndSortedIngresses.length} Ingress(es) encontrado(s)
            {selectedNamespace !== 'all' && ` em ${selectedNamespace}`}
          </CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>
                  <Button
                    variant="ghost"
                    className="h-auto p-0 font-semibold"
                    onClick={() => handleSort('name')}
                  >
                    Nome
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                  </Button>
                </TableHead>
                <TableHead>
                  <Button
                    variant="ghost"
                    className="h-auto p-0 font-semibold"
                    onClick={() => handleSort('namespace')}
                  >
                    Namespace
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                  </Button>
                </TableHead>
                <TableHead>
                  <Button
                    variant="ghost"
                    className="h-auto p-0 font-semibold"
                    onClick={() => handleSort('className')}
                  >
                    Class
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                  </Button>
                </TableHead>
                <TableHead>
                  <Button
                    variant="ghost"
                    className="h-auto p-0 font-semibold"
                    onClick={() => handleSort('hosts')}
                  >
                    Hosts
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                  </Button>
                </TableHead>
                <TableHead>
                  <Button
                    variant="ghost"
                    className="h-auto p-0 font-semibold"
                    onClick={() => handleSort('addresses')}
                  >
                    Address
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                  </Button>
                </TableHead>
                <TableHead>Status</TableHead>
                <TableHead>
                  <Button
                    variant="ghost"
                    className="h-auto p-0 font-semibold"
                    onClick={() => handleSort('age')}
                  >
                    Idade
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                  </Button>
                </TableHead>
                <TableHead className="w-16">Ações</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredAndSortedIngresses.map((ingress) => {
                const status = getIngressStatus(ingress);
                const StatusIcon = status.icon;

                return (
                  <TableRow key={`${ingress.namespace}-${ingress.name}`}>
                    <TableCell>
                      <button
                        className="text-blue-600 hover:text-blue-800 hover:underline text-left font-medium"
                        onClick={() =>
                          navigate(
                            `/service-discovery/ingresses/${ingress.namespace}/${ingress.name}`,
                          )
                        }
                      >
                        {ingress.name}
                      </button>
                      {ingress.tls.length > 0 && (
                        <Badge
                          variant="outline"
                          className="ml-2 text-green-600 border-green-600"
                        >
                          <Shield className="h-3 w-3 mr-1" />
                          TLS
                        </Badge>
                      )}
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{ingress.namespace}</Badge>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm">
                        {ingress.className || '-'}
                      </span>
                    </TableCell>
                    <TableCell>
                      <div className="max-w-xs">
                        {ingress.hosts.length > 0 ? (
                          <div className="space-y-1">
                            {ingress.hosts.slice(0, 2).map((host, index) => (
                              <div key={index} className="flex items-center">
                                <Badge variant="secondary" className="text-xs">
                                  {host}
                                </Badge>
                              </div>
                            ))}
                            {ingress.hosts.length > 2 && (
                              <span className="text-xs text-muted-foreground">
                                +{ingress.hosts.length - 2} mais
                              </span>
                            )}
                          </div>
                        ) : (
                          <span className="text-sm text-muted-foreground">
                            *
                          </span>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="max-w-xs">
                        {ingress.addresses.length > 0 ? (
                          <div className="space-y-1">
                            {ingress.addresses
                              .slice(0, 2)
                              .map((address, index) => (
                                <div key={index} className="flex items-center">
                                  <span className="text-sm font-mono">
                                    {address}
                                  </span>
                                </div>
                              ))}
                            {ingress.addresses.length > 2 && (
                              <span className="text-xs text-muted-foreground">
                                +{ingress.addresses.length - 2} mais
                              </span>
                            )}
                          </div>
                        ) : (
                          <span className="text-sm text-muted-foreground">
                            -
                          </span>
                        )}
                      </div>
                    </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>
                      </div>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm text-muted-foreground">
                        {getAge(ingress.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(
                                `/service-discovery/ingresses/${ingress.namespace}/${ingress.name}`,
                              )
                            }
                          >
                            <Eye className="h-4 w-4 mr-2" />
                            Visualizar
                          </DropdownMenuItem>
                          {ingress.hosts.length > 0 && (
                            <DropdownMenuItem
                              onClick={() => {
                                const protocol =
                                  ingress.tls.length > 0 ? 'https' : 'http';
                                window.open(
                                  `${protocol}://${ingress.hosts[0]}`,
                                  '_blank',
                                );
                              }}
                            >
                              <ExternalLink className="h-4 w-4 mr-2" />
                              Abrir Site
                            </DropdownMenuItem>
                          )}
                          <DropdownMenuSeparator />
                          <DropdownMenuItem
                            onClick={() => handleDeleteClick(ingress)}
                            className="text-red-600"
                          >
                            <Trash2 className="h-4 w-4 mr-2" />
                            Excluir
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                );
              })}
              {filteredAndSortedIngresses.length === 0 && (
                <TableRow>
                  <TableCell colSpan={8} className="text-center py-8">
                    <div className="text-muted-foreground">
                      <Globe className="h-8 w-8 mx-auto mb-2 opacity-50" />
                      <p>Nenhum Ingress 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 Ingress</DialogTitle>
            <DialogDescription>
              Tem certeza que deseja excluir o Ingress{' '}
              <strong>{selectedIngress?.name}</strong> do namespace{' '}
              <strong>{selectedIngress?.namespace}</strong>?
              <br />
              <br />
              Esta ação não pode ser desfeita e removerá todas as regras de
              roteamento configuradas.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setDeleteModalOpen(false)}
              disabled={deleting}
            >
              Cancelar
            </Button>
            <Button
              variant="destructive"
              onClick={handleDeleteIngress}
              disabled={deleting}
            >
              {deleting ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  Excluindo...
                </>
              ) : (
                <>
                  <Trash2 className="h-4 w-4 mr-2" />
                  Excluir Ingress
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
