import React from 'react';
import { useParams, 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 {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { useNamespaceDetails } from '@/hooks/useKubectl';
import {
  ArrowLeft,
  Loader2,
  AlertCircle,
  RefreshCw,
  FolderOpen,
  Calendar,
  Tag,
  Settings,
  Box,
  Globe,
  Key,
  Shield,
  Database,
  Layers,
  Activity,
  CheckCircle,
  XCircle,
  Clock,
  Zap,
} from 'lucide-react';

export function NamespaceDetailsPage() {
  const { namespaceName } = useParams<{ namespaceName: string }>();
  const navigate = useNavigate();
  const { namespaceInfo, resources, loading, error, refetch } =
    useNamespaceDetails(namespaceName || '');
  const [expandedConfigMaps, setExpandedConfigMaps] = React.useState(false);
  const [expandedSecrets, setExpandedSecrets] = React.useState(false);

  const getNamespaceAge = (creationTimestamp: string) => {
    const creationTime = new Date(creationTimestamp);
    const now = new Date();
    const diffMs = now.getTime() - creationTime.getTime();
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

    if (diffDays === 0) {
      const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
      return `${diffHours}h`;
    }
    return `${diffDays} dias`;
  };

  const getPodStatus = (pod: any) => {
    const phase = pod.status?.phase;
    switch (phase) {
      case 'Running':
        return <Badge className="bg-green-500">Running</Badge>;
      case 'Pending':
        return <Badge variant="secondary">Pending</Badge>;
      case 'Failed':
        return <Badge variant="destructive">Failed</Badge>;
      case 'Succeeded':
        return <Badge className="bg-blue-500">Succeeded</Badge>;
      default:
        return <Badge variant="outline">{phase || 'Unknown'}</Badge>;
    }
  };

  const getServiceType = (service: any) => {
    const type = service.spec?.type;
    switch (type) {
      case 'ClusterIP':
        return <Badge variant="outline">ClusterIP</Badge>;
      case 'NodePort':
        return <Badge className="bg-blue-500">NodePort</Badge>;
      case 'LoadBalancer':
        return <Badge className="bg-purple-500">LoadBalancer</Badge>;
      case 'ExternalName':
        return <Badge className="bg-orange-500">ExternalName</Badge>;
      default:
        return <Badge variant="outline">{type || 'Unknown'}</Badge>;
    }
  };

  const getDeploymentStatus = (deployment: any) => {
    const readyReplicas = deployment.status?.readyReplicas || 0;
    const replicas = deployment.spec?.replicas || 0;

    if (readyReplicas === replicas && replicas > 0) {
      return <Badge className="bg-green-500">Ready</Badge>;
    }
    if (readyReplicas > 0) {
      return <Badge className="bg-yellow-500">Partial</Badge>;
    }
    return <Badge variant="destructive">Not Ready</Badge>;
  };

  if (loading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center space-x-4">
          <Button variant="ghost" size="icon" onClick={() => navigate(-1)}>
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <div>
            <h1 className="text-3xl font-bold text-foreground">Namespace</h1>
            <p className="text-muted-foreground">Carregando detalhes...</p>
          </div>
        </div>
        <div className="flex items-center justify-center h-64">
          <Loader2 className="h-8 w-8 animate-spin" />
          <span className="ml-2">Carregando informações do namespace...</span>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="space-y-6">
        <div className="flex items-center space-x-4">
          <Button variant="ghost" size="icon" onClick={() => navigate(-1)}>
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <div>
            <h1 className="text-3xl font-bold text-foreground">Namespace</h1>
            <p className="text-muted-foreground">Erro ao carregar detalhes</p>
          </div>
        </div>
        <Card className="border-red-200">
          <CardHeader>
            <CardTitle className="text-red-600 flex items-center">
              <AlertCircle className="h-5 w-5 mr-2" />
              Erro ao carregar namespace
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-red-500 mb-4">{error}</p>
            <Button onClick={refetch} variant="outline">
              <RefreshCw className="h-4 w-4 mr-2" />
              Tentar novamente
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  const totalPods = resources.pods.length;
  const runningPods = resources.pods.filter(
    (pod) => pod.status?.phase === 'Running',
  ).length;
  const totalServices = resources.services.length;
  const totalDeployments = resources.deployments.length;
  const totalConfigMaps = resources.configMaps.length;
  const totalSecrets = resources.secrets.length;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <Button variant="ghost" size="icon" onClick={() => navigate(-1)}>
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <div className="flex items-center space-x-3">
            <FolderOpen className="h-8 w-8 text-blue-600" />
            <div>
              <h1 className="text-3xl font-bold text-foreground">
                {namespaceName}
              </h1>
              <p className="text-muted-foreground">
                Namespace criado há{' '}
                {getNamespaceAge(namespaceInfo?.metadata?.creationTimestamp)}
              </p>
            </div>
          </div>
        </div>
        <Button onClick={refetch} variant="outline">
          <RefreshCw className="h-4 w-4 mr-2" />
          Atualizar
        </Button>
      </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">Pods</CardTitle>
            <Box className="h-4 w-4 text-blue-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {runningPods}/{totalPods}
            </div>
            <p className="text-xs text-muted-foreground">Running/Total</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Services</CardTitle>
            <Globe className="h-4 w-4 text-green-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{totalServices}</div>
            <p className="text-xs text-muted-foreground">Serviços ativos</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Deployments</CardTitle>
            <Layers className="h-4 w-4 text-purple-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{totalDeployments}</div>
            <p className="text-xs text-muted-foreground">Aplicações</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">ConfigMaps</CardTitle>
            <Settings className="h-4 w-4 text-orange-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{totalConfigMaps}</div>
            <p className="text-xs text-muted-foreground">Configurações</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Secrets</CardTitle>
            <Key className="h-4 w-4 text-red-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{totalSecrets}</div>
            <p className="text-xs text-muted-foreground">Segredos</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Status</CardTitle>
            <Activity className="h-4 w-4 text-cyan-600" />
          </CardHeader>
          <CardContent>
            <div className="text-lg font-bold">
              <Badge className="bg-green-500">Active</Badge>
            </div>
            <p className="text-xs text-muted-foreground">Namespace ativo</p>
          </CardContent>
        </Card>
      </div>

      {/* Namespace Info */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Tag className="h-5 w-5 mr-2" />
            Informações do Namespace
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <p className="text-sm font-medium text-muted-foreground">Nome</p>
              <p className="text-lg">{namespaceInfo?.metadata?.name}</p>
            </div>
            <div>
              <p className="text-sm font-medium text-muted-foreground">
                Status
              </p>
              <Badge className="bg-green-500">
                {namespaceInfo?.status?.phase}
              </Badge>
            </div>
            <div>
              <p className="text-sm font-medium text-muted-foreground">
                Data de Criação
              </p>
              <div className="flex items-center space-x-2">
                <Calendar className="h-4 w-4 text-muted-foreground" />
                <p>
                  {new Date(
                    namespaceInfo?.metadata?.creationTimestamp,
                  ).toLocaleString('pt-BR')}
                </p>
              </div>
            </div>
            <div>
              <p className="text-sm font-medium text-muted-foreground">UID</p>
              <p className="text-sm font-mono">
                {namespaceInfo?.metadata?.uid}
              </p>
            </div>
          </div>

          {/* Labels */}
          {namespaceInfo?.metadata?.labels &&
            Object.keys(namespaceInfo.metadata.labels).length > 0 && (
              <div className="mt-4">
                <p className="text-sm font-medium text-muted-foreground mb-2">
                  Labels
                </p>
                <div className="flex flex-wrap gap-2">
                  {Object.entries(namespaceInfo.metadata.labels).map(
                    ([key, value]) => (
                      <Badge key={key} variant="outline" className="text-xs">
                        {key}={value as string}
                      </Badge>
                    ),
                  )}
                </div>
              </div>
            )}
        </CardContent>
      </Card>

      {/* Resources Tables */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Pods */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center">
              <Box className="h-5 w-5 mr-2 text-blue-600" />
              Pods ({totalPods})
            </CardTitle>
          </CardHeader>
          <CardContent>
            {totalPods > 0 ? (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Nome</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Ready</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {resources.pods.slice(0, 5).map((pod, index) => (
                    <TableRow key={index} className="h-8">
                      <TableCell className="font-medium text-sm">
                        {pod.metadata?.name}
                      </TableCell>
                      <TableCell>{getPodStatus(pod)}</TableCell>
                      <TableCell className="text-sm">
                        {pod.status?.containerStatuses?.filter(
                          (c: any) => c.ready,
                        ).length || 0}
                        /{pod.status?.containerStatuses?.length || 0}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            ) : (
              <p className="text-muted-foreground text-center py-4">
                Nenhum pod encontrado
              </p>
            )}
          </CardContent>
        </Card>

        {/* Services */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center">
              <Globe className="h-5 w-5 mr-2 text-green-600" />
              Services ({totalServices})
            </CardTitle>
          </CardHeader>
          <CardContent>
            {totalServices > 0 ? (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Nome</TableHead>
                    <TableHead>Tipo</TableHead>
                    <TableHead>ClusterIP</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {resources.services.slice(0, 5).map((service, index) => (
                    <TableRow key={index} className="h-8">
                      <TableCell className="font-medium text-sm">
                        {service.metadata?.name}
                      </TableCell>
                      <TableCell>{getServiceType(service)}</TableCell>
                      <TableCell className="text-sm">
                        {service.spec?.clusterIP || 'None'}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            ) : (
              <p className="text-muted-foreground text-center py-4">
                Nenhum service encontrado
              </p>
            )}
          </CardContent>
        </Card>

        {/* Deployments */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center">
              <Layers className="h-5 w-5 mr-2 text-purple-600" />
              Deployments ({totalDeployments})
            </CardTitle>
          </CardHeader>
          <CardContent>
            {totalDeployments > 0 ? (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Nome</TableHead>
                    <TableHead>Ready</TableHead>
                    <TableHead>Status</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {resources.deployments
                    .slice(0, 5)
                    .map((deployment, index) => (
                      <TableRow key={index} className="h-8">
                        <TableCell className="font-medium text-sm">
                          {deployment.metadata?.name}
                        </TableCell>
                        <TableCell className="text-sm">
                          {deployment.status?.readyReplicas || 0}/
                          {deployment.spec?.replicas || 0}
                        </TableCell>
                        <TableCell>{getDeploymentStatus(deployment)}</TableCell>
                      </TableRow>
                    ))}
                </TableBody>
              </Table>
            ) : (
              <p className="text-muted-foreground text-center py-4">
                Nenhum deployment encontrado
              </p>
            )}
          </CardContent>
        </Card>

        {/* ConfigMaps & Secrets */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center">
              <Settings className="h-5 w-5 mr-2 text-orange-600" />
              Configurações
            </CardTitle>
          </CardHeader>
          <CardContent className="h-[300px] overflow-y-auto">
            <div className="space-y-4">
              <div>
                <p className="text-sm font-medium mb-2">
                  ConfigMaps ({totalConfigMaps})
                </p>
                {totalConfigMaps > 0 ? (
                  <div className="space-y-1">
                    {(expandedConfigMaps
                      ? resources.configMaps
                      : resources.configMaps.slice(0, 3)
                    ).map((cm, index) => (
                      <div key={index} className="flex items-center space-x-2">
                        <Settings className="h-3 w-3 text-orange-600" />
                        <span className="text-sm">{cm.metadata?.name}</span>
                      </div>
                    ))}
                    {totalConfigMaps > 3 && !expandedConfigMaps && (
                      <button
                        onClick={() => setExpandedConfigMaps(true)}
                        className="text-xs text-blue-600 hover:text-blue-800 hover:underline cursor-pointer"
                      >
                        +{totalConfigMaps - 3} mais
                      </button>
                    )}
                    {expandedConfigMaps && (
                      <button
                        onClick={() => setExpandedConfigMaps(false)}
                        className="text-xs text-blue-600 hover:text-blue-800 hover:underline cursor-pointer"
                      >
                        Mostrar menos
                      </button>
                    )}
                  </div>
                ) : (
                  <p className="text-xs text-muted-foreground">
                    Nenhum encontrado
                  </p>
                )}
              </div>

              <div>
                <p className="text-sm font-medium mb-2">
                  Secrets ({totalSecrets})
                </p>
                {totalSecrets > 0 ? (
                  <div className="space-y-1">
                    {(expandedSecrets
                      ? resources.secrets
                      : resources.secrets.slice(0, 3)
                    ).map((secret, index) => (
                      <div key={index} className="flex items-center space-x-2">
                        <Key className="h-3 w-3 text-red-600" />
                        <span className="text-sm">{secret.metadata?.name}</span>
                      </div>
                    ))}
                    {totalSecrets > 3 && !expandedSecrets && (
                      <button
                        onClick={() => setExpandedSecrets(true)}
                        className="text-xs text-blue-600 hover:text-blue-800 hover:underline cursor-pointer"
                      >
                        +{totalSecrets - 3} mais
                      </button>
                    )}
                    {expandedSecrets && (
                      <button
                        onClick={() => setExpandedSecrets(false)}
                        className="text-xs text-blue-600 hover:text-blue-800 hover:underline cursor-pointer"
                      >
                        Mostrar menos
                      </button>
                    )}
                  </div>
                ) : (
                  <p className="text-xs text-muted-foreground">
                    Nenhum encontrado
                  </p>
                )}
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
