import React, { useState, useEffect } 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 {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { YamlEditor } from '@/components/ui/yaml-editor';
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/tooltip';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useKubectl } from '@/hooks/useKubectl';
import { useToast } from '@/hooks/useToast';
import {
  Loader2,
  Map,
  AlertCircle,
  RefreshCw,
  ArrowLeft,
  MoreVertical,
  Trash2,
  FileText,
  Settings,
  Copy,
  Key,
  Calendar,
  Tag,
  Database,
  Info,
  Edit3,
  Eye,
  Download,
  ExternalLink,
} from 'lucide-react';

interface ConfigMapData {
  name: string;
  namespace: string;
  creationTimestamp: string;
  labels: Record<string, string>;
  annotations: Record<string, string>;
  data: Record<string, string>;
  resourceVersion: string;
  uid: string;
}

export function ConfigMapDetailsPage() {
  const { namespaceName, configMapName } = useParams<{
    namespaceName: string;
    configMapName: string;
  }>();
  const navigate = useNavigate();
  const { executeCommand } = useKubectl();
  const { showToast } = useToast();

  const [configMap, setConfigMap] = useState<ConfigMapData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showYaml, setShowYaml] = useState(false);
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [deleting, setDeleting] = useState(false);

  const fetchConfigMapDetails = async () => {
    if (!namespaceName || !configMapName) return;

    try {
      setLoading(true);
      setError(null);

      const command = `kubectl get configmap ${configMapName} -n ${namespaceName} -o json`;
      const result = await executeCommand(command);

      if (result.success) {
        const data = JSON.parse(result.data);
        setConfigMap({
          name: data.metadata.name,
          namespace: data.metadata.namespace,
          creationTimestamp: data.metadata.creationTimestamp,
          labels: data.metadata.labels || {},
          annotations: data.metadata.annotations || {},
          data: data.data || {},
          resourceVersion: data.metadata.resourceVersion,
          uid: data.metadata.uid,
        });
      } else {
        setError(result.error || 'Falha ao buscar detalhes do ConfigMap');
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      setError(errorMsg);
    } finally {
      setLoading(false);
    }
  };

  const fetchYaml = () => {
    setShowYaml(true);
  };

  const handleDeleteConfigMap = async () => {
    if (!namespaceName || !configMapName) return;

    setDeleting(true);
    try {
      const command = `kubectl delete configmap ${configMapName} -n ${namespaceName}`;
      const result = await executeCommand(command);

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

        navigate('/storage/configmaps');
      } else {
        showToast({
          title: 'Erro ao Excluir ConfigMap',
          description: result.error || 'Falha ao excluir o ConfigMap',
          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);
    }
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
    showToast({
      title: 'Copiado',
      description: 'Conteúdo copiado para a área de transferência',
      variant: 'success',
    });
  };

  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`;
  };

  useEffect(() => {
    fetchConfigMapDetails();
  }, [namespaceName, configMapName]);

  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 detalhes do ConfigMap...
          </p>
        </div>
      </div>
    );
  }

  if (error || !configMap) {
    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 || 'ConfigMap não encontrado'}
          </p>
          <div className="space-x-2">
            <Button onClick={() => fetchConfigMapDetails()}>
              <RefreshCw className="h-4 w-4 mr-2" />
              Tentar Novamente
            </Button>
            <Button
              variant="outline"
              onClick={() => navigate('/storage/configmaps')}
            >
              <ArrowLeft className="h-4 w-4 mr-2" />
              Voltar
            </Button>
          </div>
        </div>
      </div>
    );
  }

  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>
            <h1 className="text-3xl font-bold text-foreground flex items-center">
              <Map className="h-8 w-8 mr-3 text-blue-600" />
              {configMap.name}
            </h1>
            <div className="text-muted-foreground">
              ConfigMap no namespace{' '}
              <Badge variant="outline" className="mx-1">
                {configMap.namespace}
              </Badge>
            </div>
          </div>
        </div>

        <div className="flex items-center space-x-2">
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline">
                <MoreVertical className="h-4 w-4 mr-2" />
                Ações
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuLabel>Navegação</DropdownMenuLabel>
              <DropdownMenuSeparator />
              <DropdownMenuItem onClick={() => navigate('/storage/configmaps')}>
                <ExternalLink className="h-4 w-4 mr-2" />
                Lista de ConfigMaps
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </div>

      {/* Informações Gerais */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center justify-between">
            <div className="flex items-center">
              <Info className="h-5 w-5 mr-2" />
              Informações Gerais
            </div>
            <div className="flex gap-2">
              <TooltipProvider>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Button onClick={fetchYaml} variant="outline" size="sm">
                      <Eye className="h-4 w-4 mr-2" />
                      YAML
                    </Button>
                  </TooltipTrigger>
                  <TooltipContent>
                    <p>Visualizar YAML completo</p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>

              <TooltipProvider>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Button
                      onClick={() =>
                        copyToClipboard(JSON.stringify(configMap, null, 2))
                      }
                      variant="outline"
                      size="sm"
                    >
                      <Copy className="h-4 w-4 mr-2" />
                      JSON
                    </Button>
                  </TooltipTrigger>
                  <TooltipContent>
                    <p>Copiar dados como JSON</p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>

              <TooltipProvider>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Button
                      onClick={() => setDeleteModalOpen(true)}
                      variant="destructive"
                      size="sm"
                    >
                      <Trash2 className="h-4 w-4 mr-2" />
                      Excluir
                    </Button>
                  </TooltipTrigger>
                  <TooltipContent>
                    <p>Excluir este ConfigMap</p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
            </div>
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            <div>
              <label className="text-sm font-medium text-muted-foreground">
                Nome
              </label>
              <div className="flex items-center justify-between mt-1">
                <span className="text-sm font-medium">{configMap.name}</span>
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-6 w-6"
                  onClick={() => copyToClipboard(configMap.name)}
                >
                  <Copy className="h-3 w-3" />
                </Button>
              </div>
            </div>
            <div>
              <label className="text-sm font-medium text-muted-foreground">
                Namespace
              </label>
              <div className="flex items-center justify-between mt-1">
                <Badge variant="outline">{configMap.namespace}</Badge>
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-6 w-6"
                  onClick={() => copyToClipboard(configMap.namespace)}
                >
                  <Copy className="h-3 w-3" />
                </Button>
              </div>
            </div>
            <div>
              <label className="text-sm font-medium text-muted-foreground">
                Data Keys
              </label>
              <div className="mt-1">
                <Badge variant="secondary">
                  {Object.keys(configMap.data).length}
                </Badge>
              </div>
            </div>
            <div>
              <label className="text-sm font-medium text-muted-foreground">
                Criado há
              </label>
              <div className="mt-1">
                <span className="text-sm">
                  {getAge(configMap.creationTimestamp)}
                </span>
              </div>
            </div>
          </div>

          <div className="mt-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label className="text-sm font-medium text-muted-foreground">
                  UID
                </label>
                <div className="flex items-center justify-between mt-1">
                  <span className="text-sm font-mono">{configMap.uid}</span>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-6 w-6"
                    onClick={() => copyToClipboard(configMap.uid)}
                  >
                    <Copy className="h-3 w-3" />
                  </Button>
                </div>
              </div>
              <div>
                <label className="text-sm font-medium text-muted-foreground">
                  Resource Version
                </label>
                <div className="mt-1">
                  <span className="text-sm">{configMap.resourceVersion}</span>
                </div>
              </div>
            </div>
          </div>

          {/* Labels e Annotations lado a lado */}
          {(Object.keys(configMap.labels).length > 0 ||
            Object.keys(configMap.annotations).length > 0) && (
            <div className="mt-6">
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {/* Labels */}
                {Object.keys(configMap.labels).length > 0 && (
                  <div>
                    <label className="text-sm font-medium text-muted-foreground flex items-center mb-3">
                      <Tag className="h-4 w-4 mr-2" />
                      Labels
                    </label>
                    <div className="space-y-2">
                      {Object.entries(configMap.labels).map(([key, value]) => (
                        <div
                          key={key}
                          className="flex items-center justify-between p-2 bg-muted rounded"
                        >
                          <div className="flex-1 min-w-0">
                            <div className="text-sm font-medium truncate">
                              {key}
                            </div>
                            <div className="text-xs text-muted-foreground truncate">
                              {value}
                            </div>
                          </div>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-6 w-6"
                            onClick={() => copyToClipboard(`${key}=${value}`)}
                          >
                            <Copy className="h-3 w-3" />
                          </Button>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* Annotations */}
                {Object.keys(configMap.annotations).length > 0 && (
                  <div>
                    <label className="text-sm font-medium text-muted-foreground flex items-center mb-3">
                      <Settings className="h-4 w-4 mr-2" />
                      Annotations
                    </label>
                    <div className="space-y-2">
                      {Object.entries(configMap.annotations).map(
                        ([key, value]) => (
                          <div
                            key={key}
                            className="flex items-center justify-between p-2 bg-muted rounded"
                          >
                            <div className="flex-1 min-w-0">
                              <div className="text-sm font-medium truncate">
                                {key}
                              </div>
                              <div className="text-xs text-muted-foreground truncate">
                                {value}
                              </div>
                            </div>
                            <Button
                              variant="ghost"
                              size="icon"
                              className="h-6 w-6"
                              onClick={() => copyToClipboard(`${key}=${value}`)}
                            >
                              <Copy className="h-3 w-3" />
                            </Button>
                          </div>
                        ),
                      )}
                    </div>
                  </div>
                )}
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Dados de Configuração */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Database className="h-5 w-5 mr-2" />
            Dados de Configuração
          </CardTitle>
          <CardDescription>
            {Object.keys(configMap.data).length} chave(s) de configuração
          </CardDescription>
        </CardHeader>
        <CardContent>
          {Object.keys(configMap.data).length > 0 ? (
            <Tabs defaultValue="table" className="w-full">
              <TabsList>
                <TabsTrigger value="table">Tabela</TabsTrigger>
                <TabsTrigger value="raw">Texto</TabsTrigger>
              </TabsList>

              <TabsContent value="table" className="mt-4">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Chave</TableHead>
                      <TableHead>Valor</TableHead>
                      <TableHead className="w-16">Ações</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {Object.entries(configMap.data).map(([key, value]) => (
                      <TableRow key={key}>
                        <TableCell>
                          <div className="flex items-center">
                            <Badge variant="outline" className="mr-2">
                              {key}
                            </Badge>
                            <Button
                              variant="ghost"
                              size="icon"
                              className="h-6 w-6"
                              onClick={() => copyToClipboard(key)}
                            >
                              <Copy className="h-3 w-3" />
                            </Button>
                          </div>
                        </TableCell>
                        <TableCell>
                          <div className="max-w-md">
                            <pre className="text-xs whitespace-pre-wrap break-words font-mono bg-muted p-2 rounded">
                              {value || '(vazio)'}
                            </pre>
                          </div>
                        </TableCell>
                        <TableCell>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-6 w-6"
                            onClick={() => copyToClipboard(value)}
                          >
                            <Copy className="h-3 w-3" />
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TabsContent>

              <TabsContent value="raw" className="mt-4">
                <div className="space-y-4">
                  {Object.entries(configMap.data).map(([key, value]) => (
                    <Card key={key}>
                      <CardHeader className="pb-2">
                        <div className="flex items-center justify-between">
                          <CardTitle className="text-base">{key}</CardTitle>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-6 w-6"
                            onClick={() => copyToClipboard(value)}
                          >
                            <Copy className="h-3 w-3" />
                          </Button>
                        </div>
                      </CardHeader>
                      <CardContent>
                        <pre className="text-sm whitespace-pre-wrap break-words font-mono bg-muted p-3 rounded max-h-96 overflow-y-auto">
                          {value || '(vazio)'}
                        </pre>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              </TabsContent>
            </Tabs>
          ) : (
            <div className="text-center py-8 text-muted-foreground">
              <Database className="h-8 w-8 mx-auto mb-2 opacity-50" />
              <p>Nenhum dado de configuração encontrado</p>
            </div>
          )}
        </CardContent>
      </Card>

      {/* YAML Modal */}
      <YamlEditor
        open={showYaml}
        onOpenChange={setShowYaml}
        resourceType="configmap"
        resourceName={configMap.name}
        namespace={configMap.namespace}
        title={`YAML do ConfigMap - ${configMap.name}`}
      />

      {/* Delete Confirmation Modal */}
      <Dialog open={deleteModalOpen} onOpenChange={setDeleteModalOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Excluir ConfigMap</DialogTitle>
            <DialogDescription>
              Tem certeza que deseja excluir o ConfigMap{' '}
              <strong>{configMap.name}</strong> do namespace{' '}
              <strong>{configMap.namespace}</strong>?
              <br />
              <br />
              Esta ação não pode ser desfeita e pode afetar pods que dependem
              dessas configurações.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setDeleteModalOpen(false)}
              disabled={deleting}
            >
              Cancelar
            </Button>
            <Button
              variant="destructive"
              onClick={handleDeleteConfigMap}
              disabled={deleting}
            >
              {deleting ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  Excluindo...
                </>
              ) : (
                <>
                  <Trash2 className="h-4 w-4 mr-2" />
                  Excluir ConfigMap
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
