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 { useServicesInfo, useKubectl, ServiceInfo } from '@/hooks/useKubectl';
import { useToast } from '@/hooks/useToast';
import { useGlobalNamespace } from '@/hooks/useGlobalNamespace';
import {
  Loader2,
  GitBranch,
  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,
  Network,
  Globe,
  Layers,
  ChevronDown,
} from 'lucide-react';

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

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

  // Modal states
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [selectedService, setSelectedService] = useState<ServiceInfo | null>(
    null,
  );
  const [deleting, setDeleting] = useState(false);

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

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

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

  // Filter and sort services
  const filteredAndSortedServices = useMemo(() => {
    let filtered = services;

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

    // Filter by type
    if (typeFilter !== 'all') {
      filtered = filtered.filter((service) => service.type === typeFilter);
    }

    // Filter by search query
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(
        (service) =>
          service.name.toLowerCase().includes(query) ||
          service.namespace.toLowerCase().includes(query) ||
          service.type.toLowerCase().includes(query) ||
          service.clusterIP.toLowerCase().includes(query) ||
          service.ports.some((port) => port.port.toString().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 'type':
          aValue = a.type;
          bValue = b.type;
          break;
        case 'clusterIP':
          aValue = a.clusterIP;
          bValue = b.clusterIP;
          break;
        case 'ports':
          aValue = a.ports.length;
          bValue = b.ports.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;
    });
  }, [
    services,
    selectedNamespace,
    typeFilter,
    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 getServiceTypeColor = (type: string) => {
    switch (type) {
      case 'ClusterIP':
        return 'bg-blue-100 text-blue-800';
      case 'NodePort':
        return 'bg-green-100 text-green-800';
      case 'LoadBalancer':
        return 'bg-purple-100 text-purple-800';
      case 'ExternalName':
        return 'bg-orange-100 text-orange-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  const handleDeleteService = async () => {
    if (!selectedService) return;

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

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

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

  const handleDeleteClick = (service: ServiceInfo) => {
    setSelectedService(service);
    setDeleteModalOpen(true);
  };

  const statusStats = useMemo(() => {
    const filtered =
      selectedNamespace === 'all'
        ? services
        : services.filter((service) => service.namespace === selectedNamespace);

    return {
      total: filtered.length,
      clusterIP: filtered.filter((service) => service.type === 'ClusterIP')
        .length,
      nodePort: filtered.filter((service) => service.type === 'NodePort')
        .length,
      loadBalancer: filtered.filter(
        (service) => service.type === 'LoadBalancer',
      ).length,
      externalName: filtered.filter(
        (service) => service.type === 'ExternalName',
      ).length,
    };
  }, [services, 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 Services...</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">
            <GitBranch className="h-8 w-8 mr-3 text-blue-600" />
            Services
          </h1>
          <p className="text-muted-foreground">
            Gerencie e monitore todos os Services 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 ({serviceRefreshInterval / 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={() => setServiceRefreshInterval(1000)}
                  className={
                    serviceRefreshInterval === 1000 ? 'bg-green-100' : ''
                  }
                >
                  1 segundo
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setServiceRefreshInterval(3000)}
                  className={
                    serviceRefreshInterval === 3000 ? 'bg-green-100' : ''
                  }
                >
                  3 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setServiceRefreshInterval(5000)}
                  className={
                    serviceRefreshInterval === 5000 ? 'bg-green-100' : ''
                  }
                >
                  5 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setServiceRefreshInterval(7000)}
                  className={
                    serviceRefreshInterval === 7000 ? 'bg-green-100' : ''
                  }
                >
                  7 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setServiceRefreshInterval(10000)}
                  className={
                    serviceRefreshInterval === 10000 ? 'bg-green-100' : ''
                  }
                >
                  10 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setServiceRefreshInterval(30000)}
                  className={
                    serviceRefreshInterval === 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 Service</DropdownMenuLabel>
              <DropdownMenuSeparator />
              <DropdownMenuItem onClick={() => navigate('/service-discovery/services/create')}>
                <Plus className="h-4 w-4 mr-2" />
                Criar Service
              </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>
            <GitBranch 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">Services 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">ClusterIP</CardTitle>
            <Layers className="h-4 w-4 text-blue-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-blue-600">
              {statusStats.clusterIP}
            </div>
            <p className="text-xs text-muted-foreground">Internos</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">NodePort</CardTitle>
            <Server className="h-4 w-4 text-green-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">
              {statusStats.nodePort}
            </div>
            <p className="text-xs text-muted-foreground">Porta do nó</p>
          </CardContent>
        </Card>

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

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">ExternalName</CardTitle>
            <Globe className="h-4 w-4 text-orange-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-orange-600">
              {statusStats.externalName}
            </div>
            <p className="text-xs text-muted-foreground">Externos</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">Tipo</label>
              <Select value={typeFilter} onValueChange={setTypeFilter}>
                <SelectTrigger>
                  <SelectValue placeholder="Todos os tipos" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">Todos os tipos</SelectItem>
                  <SelectItem value="ClusterIP">ClusterIP</SelectItem>
                  <SelectItem value="NodePort">NodePort</SelectItem>
                  <SelectItem value="LoadBalancer">LoadBalancer</SelectItem>
                  <SelectItem value="ExternalName">ExternalName</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, tipo, IP, porta..."
                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>

      {/* Services Table */}
      <Card>
        <CardHeader>
          <CardTitle>
            {filteredAndSortedServices.length} Service(s) 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('type')}
                  >
                    Tipo
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                  </Button>
                </TableHead>
                <TableHead>
                  <Button
                    variant="ghost"
                    className="h-auto p-0 font-semibold"
                    onClick={() => handleSort('clusterIP')}
                  >
                    Cluster IP
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                  </Button>
                </TableHead>
                <TableHead>
                  <Button
                    variant="ghost"
                    className="h-auto p-0 font-semibold"
                    onClick={() => handleSort('ports')}
                  >
                    Portas
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                  </Button>
                </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>
              {filteredAndSortedServices.map((service) => {
                return (
                  <TableRow key={`${service.namespace}-${service.name}`}>
                    <TableCell>
                      <button
                        className="text-blue-600 hover:text-blue-800 hover:underline text-left font-medium"
                        onClick={() =>
                          navigate(
                            `/service-discovery/services/${service.namespace}/${service.name}`,
                          )
                        }
                      >
                        {service.name}
                      </button>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{service.namespace}</Badge>
                    </TableCell>
                    <TableCell>
                      <Badge className={getServiceTypeColor(service.type)}>
                        {service.type}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm font-mono">
                        {service.clusterIP === 'None' ? (
                          <span className="text-muted-foreground">None</span>
                        ) : (
                          service.clusterIP
                        )}
                      </span>
                    </TableCell>
                    <TableCell>
                      <div className="max-w-xs">
                        {service.ports.length > 0 ? (
                          <div className="space-y-1">
                            {service.ports.slice(0, 2).map((port, index) => (
                              <div key={index} className="flex items-center">
                                <Badge variant="secondary" className="text-xs">
                                  {port.port}
                                  {port.nodePort && `→${port.nodePort}`}/
                                  {port.protocol}
                                </Badge>
                              </div>
                            ))}
                            {service.ports.length > 2 && (
                              <span className="text-xs text-muted-foreground">
                                +{service.ports.length - 2} mais
                              </span>
                            )}
                          </div>
                        ) : (
                          <span className="text-sm text-muted-foreground">
                            -
                          </span>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm text-muted-foreground">
                        {getAge(service.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/services/${service.namespace}/${service.name}`,
                              )
                            }
                          >
                            <Eye className="h-4 w-4 mr-2" />
                            Visualizar
                          </DropdownMenuItem>
                          <DropdownMenuSeparator />
                          <DropdownMenuItem
                            onClick={() => handleDeleteClick(service)}
                            className="text-red-600"
                          >
                            <Trash2 className="h-4 w-4 mr-2" />
                            Excluir
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                );
              })}
              {filteredAndSortedServices.length === 0 && (
                <TableRow>
                  <TableCell colSpan={7} className="text-center py-8">
                    <div className="text-muted-foreground">
                      <GitBranch className="h-8 w-8 mx-auto mb-2 opacity-50" />
                      <p>Nenhum Service encontrado</p>
                      {(typeFilter !== 'all' ||
                        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 Service</DialogTitle>
            <DialogDescription>
              Tem certeza que deseja excluir o Service{' '}
              <strong>{selectedService?.name}</strong> do namespace{' '}
              <strong>{selectedService?.namespace}</strong>?
              <br />
              <br />
              Esta ação não pode ser desfeita e pode afetar a conectividade
              entre pods.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setDeleteModalOpen(false)}
              disabled={deleting}
            >
              Cancelar
            </Button>
            <Button
              variant="destructive"
              onClick={handleDeleteService}
              disabled={deleting}
            >
              {deleting ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  Excluindo...
                </>
              ) : (
                <>
                  <Trash2 className="h-4 w-4 mr-2" />
                  Excluir Service
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
