import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { useToast } from '@/hooks/useToast';
import { useKubectl } from '@/hooks/useKubectl';
import {
  FileCode,
  Edit,
  Save,
  Copy,
  Download,
  Maximize2,
  Minimize2,
  X,
  Loader2,
  RotateCcw,
} from 'lucide-react';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import {
  vscDarkPlus,
  oneDark,
  materialDark,
} from 'react-syntax-highlighter/dist/esm/styles/prism';
import { github } from 'react-syntax-highlighter/dist/esm/styles/hljs';

interface YamlEditorProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  resourceType: string; // 'deployment', 'pod', 'service', etc.
  resourceName: string;
  namespace: string;
  title?: string;
  onSave?: (yamlContent: string) => void; // Callback opcional para quando salvar
}

export function YamlEditor({
  open,
  onOpenChange,
  resourceType,
  resourceName,
  namespace,
  title,
  onSave,
}: YamlEditorProps) {
  const { showToast } = useToast();
  const { executeCommand } = useKubectl();

  // Estados do editor
  const [yamlFullscreen, setYamlFullscreen] = useState(false);
  const [yamlContent, setYamlContent] = useState<string>('');
  const [loadingYaml, setLoadingYaml] = useState(false);
  const [yamlEditing, setYamlEditing] = useState(false);
  const [editedYaml, setEditedYaml] = useState<string>('');
  const [savingYaml, setSavingYaml] = useState(false);
  const [editorHeight, setEditorHeight] = useState<number | null>(null);

  // Tema do YAML
  const [yamlTheme, setYamlTheme] = useState(() => {
    return localStorage.getItem('yaml-theme-preference') || 'oneDark';
  });

  // Salvar preferência do tema
  useEffect(() => {
    localStorage.setItem('yaml-theme-preference', yamlTheme);
  }, [yamlTheme]);

  // Reset fullscreen quando fechar modal
  useEffect(() => {
    if (!open) {
      setYamlFullscreen(false);
      setYamlEditing(false);
      setYamlContent('');
      setEditedYaml('');
    }
  }, [open]);

  // Carregar YAML quando o modal abrir
  useEffect(() => {
    if (open && resourceName && namespace && resourceType) {
      loadYaml();
    }
  }, [open, resourceName, namespace, resourceType]);

  // Capturar altura do SyntaxHighlighter quando não está editando
  useEffect(() => {
    if (!yamlEditing && !loadingYaml) {
      setTimeout(() => {
        const syntaxHighlighter = document.querySelector(
          '.yaml-syntax-highlighter',
        );
        if (syntaxHighlighter) {
          const { height } = syntaxHighlighter.getBoundingClientRect();
          setEditorHeight(height > 0 ? height : null);
        }
      }, 100);
    }
  }, [yamlEditing, loadingYaml, yamlContent]);

  const loadYaml = async () => {
    setLoadingYaml(true);
    setYamlContent('');

    try {
      const command = `kubectl get ${resourceType} ${resourceName} -n ${namespace} -o yaml`;
      const result = await executeCommand(command);

      if (result.success) {
        setYamlContent(result.data || '');
      } else {
        setYamlContent(
          `# Erro ao carregar YAML\n# ${result.error || 'Erro desconhecido'}`,
        );
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      setYamlContent(`# Erro ao carregar YAML\n# ${errorMsg}`);
    } finally {
      setLoadingYaml(false);
    }
  };

  const getYamlTheme = () => {
    switch (yamlTheme) {
      case 'vscDarkPlus':
        return vscDarkPlus;
      case 'github':
        return github;
      case 'oneDark':
        return oneDark;
      case 'materialDark':
        return materialDark;
      default:
        return oneDark;
    }
  };

  const handleStartEdit = () => {
    setEditedYaml(yamlContent);
    setYamlEditing(true);
  };

  const handleCancelEdit = () => {
    setYamlEditing(false);
    setEditedYaml('');
  };

  const handleSaveYaml = async () => {
    if (!resourceName || !namespace || !editedYaml) return;

    setSavingYaml(true);
    try {
      // Usar aquivo temporário para aplicar o YAML
      const tempFile = `/tmp/k8s-resource-${Date.now()}.yaml`;

      // Escrever o YAML editado em um arquivo temporário
      const writeCommand = `cat > ${tempFile} << 'EOF'\n${editedYaml}\nEOF`;
      const writeResult = await executeCommand(writeCommand);

      if (!writeResult.success) {
        throw new Error('Falha ao criar arquivo temporário');
      }

      // Aplicar o YAML usando kubectl apply
      const applyCommand = `kubectl apply -f ${tempFile}`;
      const applyResult = await executeCommand(applyCommand);

      // Limpar arquivo temporário
      executeCommand(`rm -f ${tempFile}`);

      if (applyResult.success) {
        // Atualizar o YAML local com a versão editada
        setYamlContent(editedYaml);
        setYamlEditing(false);

        // Chamar callback se fornecido
        if (onSave) {
          onSave(editedYaml);
        }

        showToast({
          title: 'YAML Salvo',
          description: `${resourceType} atualizado com sucesso!`,
          variant: 'success',
        });

        // Recarregar o YAML após um breve delay para pegar mudanças do servidor
        setTimeout(() => {
          loadYaml();
        }, 1000);
      } else {
        throw new Error(applyResult.error || 'Falha ao aplicar YAML');
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      showToast({
        title: 'Erro ao Salvar YAML',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setSavingYaml(false);
    }
  };

  const handleCopyYaml = () => {
    const yamlToCopy = yamlEditing ? editedYaml : yamlContent;
    navigator.clipboard.writeText(yamlToCopy);
    showToast({
      title: 'YAML Copiado',
      description: 'Conteúdo YAML copiado para a área de transferência',
      variant: 'success',
    });
  };

  const handleDownloadYaml = () => {
    const yamlToDownload = yamlEditing ? editedYaml : yamlContent;
    const blob = new Blob([yamlToDownload], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${resourceType}-${resourceName}-${namespace}.yaml`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);

    showToast({
      title: 'Download Iniciado',
      description: 'Arquivo YAML baixado com sucesso',
      variant: 'success',
    });
  };

  const handleRefresh = () => {
    if (yamlEditing) {
      // Se está editando, perguntar se quer descartar mudanças
      if (confirm('Isso irá descartar as alterações não salvas. Continuar?')) {
        setYamlEditing(false);
        setEditedYaml('');
        loadYaml();
      }
    } else {
      loadYaml();
    }
  };

  const getDisplayTitle = () => {
    if (title) return title;
    return `YAML do ${resourceType} - ${resourceName}`;
  };

  return (
    <Dialog
      open={open}
      onOpenChange={(openState) => {
        if (!openState && yamlEditing) {
          // Se está tentando fechar enquanto edita, confirmar
          if (confirm('Você tem alterações não salvas. Deseja descartar?')) {
            onOpenChange(openState);
          }
        } else {
          onOpenChange(openState);
        }
      }}
    >
      <DialogContent
        className={
          yamlFullscreen
            ? 'max-w-none h-screen w-screen overflow-hidden m-0 rounded-none [&>button]:hidden'
            : 'max-w-6xl w-[90vw] h-[85vh] overflow-hidden'
        }
      >
        <DialogHeader>
          <DialogTitle className="flex items-center justify-between">
            <div className="flex items-center">
              <FileCode className="h-5 w-5 mr-2" />
              {getDisplayTitle()}
            </div>
            {yamlFullscreen && (
              <Button
                variant="ghost"
                size="sm"
                onClick={() => setYamlFullscreen(false)}
                title="Sair da tela cheia"
              >
                <X className="h-4 w-4" />
              </Button>
            )}
          </DialogTitle>
          <DialogDescription>
            {resourceType}: {resourceName} • Namespace: {namespace}
            {yamlEditing && (
              <span className="text-orange-600 ml-2">• Modo de Edição</span>
            )}
          </DialogDescription>
        </DialogHeader>

        {loadingYaml ? (
          <div className="flex-1 flex items-center justify-center">
            <div className="flex items-center space-x-2">
              <Loader2 className="h-6 w-6 animate-spin" />
              <span>Carregando YAML...</span>
            </div>
          </div>
        ) : (
          <div
            className="flex-1 flex flex-col overflow-hidden"
            style={{ height: yamlFullscreen ? '100vh' : 'calc(85vh - 120px)' }}
          >
            <div className="flex items-center justify-between mb-3">
              <div className="flex items-center space-x-2">
                {yamlEditing ? (
                  <>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={handleSaveYaml}
                      disabled={savingYaml}
                    >
                      {savingYaml && (
                        <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                      )}
                      <Save className="h-4 w-4 mr-2" />
                      {savingYaml ? 'Salvando...' : 'Salvar'}
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={handleCancelEdit}
                      disabled={savingYaml}
                    >
                      <X className="h-4 w-4 mr-2" />
                      Cancelar
                    </Button>
                  </>
                ) : (
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={handleStartEdit}
                    disabled={yamlContent.startsWith('# Erro')}
                  >
                    <Edit className="h-4 w-4 mr-2" />
                    Editar
                  </Button>
                )}

                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleRefresh}
                  disabled={savingYaml}
                  title="Recarregar YAML"
                >
                  <RotateCcw className="h-4 w-4" />
                </Button>
              </div>

              <div className="flex items-center space-x-2">
                <Select value={yamlTheme} onValueChange={setYamlTheme}>
                  <SelectTrigger className="w-[140px]">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="vscDarkPlus">VS Code Dark</SelectItem>
                    <SelectItem value="github">GitHub Light</SelectItem>
                    <SelectItem value="oneDark">One Dark</SelectItem>
                    <SelectItem value="materialDark">Material Dark</SelectItem>
                  </SelectContent>
                </Select>

                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleCopyYaml}
                  disabled={!yamlContent && !editedYaml}
                >
                  <Copy className="h-4 w-4 mr-2" />
                  Copiar
                </Button>

                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleDownloadYaml}
                  disabled={!yamlContent && !editedYaml}
                >
                  <Download className="h-4 w-4 mr-2" />
                  Download
                </Button>

                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setYamlFullscreen(!yamlFullscreen)}
                  title={
                    yamlFullscreen
                      ? 'Sair da tela cheia'
                      : 'Abrir em tela cheia'
                  }
                >
                  {yamlFullscreen ? (
                    <Minimize2 className="h-4 w-4" />
                  ) : (
                    <Maximize2 className="h-4 w-4" />
                  )}
                </Button>
              </div>
            </div>

            <div
              className="flex-1 rounded-lg border overflow-hidden"
              style={{ height: 0 }}
            >
              {yamlEditing ? (
                <pre
                  style={{
                    margin: 0,
                    padding: '16px',
                    fontSize: '14px',
                    height: editorHeight || '100%',
                    overflow: 'auto',
                    borderRadius: '8px',
                    backgroundColor:
                      yamlTheme === 'github' ? '#ffffff' : '#282c34',
                    position: 'relative',
                  }}
                >
                  <div
                    style={{
                      position: 'absolute',
                      top: 0,
                      left: 0,
                      bottom: 0,
                      width: '3em',
                      backgroundColor:
                        yamlTheme === 'github' ? '#f6f8fa' : '#262626',
                      color: yamlTheme === 'github' ? '#6B7280' : '#5c6370',
                      borderRight:
                        yamlTheme === 'github'
                          ? '1px solid #E5E7EB'
                          : '1px solid #374151',
                      fontSize: 'inherit',
                      lineHeight: '1.5',
                      paddingTop: '16px',
                      paddingLeft: '8px',
                      paddingRight: '8px',
                      overflow: 'hidden',
                      userSelect: 'none',
                      textAlign: 'right',
                    }}
                  >
                    {editedYaml.split('\n').map((_, i) => (
                      <div key={i + 1}>{i + 1}</div>
                    ))}
                  </div>
                  <textarea
                    value={editedYaml}
                    onChange={(e) => setEditedYaml(e.target.value)}
                    style={{
                      width: '100%',
                      height: '100%',
                      border: 'none',
                      outline: 'none',
                      resize: 'none',
                      fontFamily:
                        'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace',
                      fontSize: '14px',
                      lineHeight: '1.5',
                      paddingLeft: '4em',
                      paddingTop: '0',
                      paddingRight: '0',
                      paddingBottom: '0',
                      backgroundColor: 'transparent',
                      color: yamlTheme === 'github' ? '#24292e' : '#abb2bf',
                      whiteSpace: 'pre',
                      overflowWrap: 'normal',
                      tabSize: 2,
                    }}
                    spellCheck={false}
                    autoComplete="off"
                    autoCorrect="off"
                    autoCapitalize="off"
                  />
                </pre>
              ) : (
                <SyntaxHighlighter
                  language="yaml"
                  style={getYamlTheme()}
                  showLineNumbers
                  wrapLines
                  className="yaml-syntax-highlighter"
                  customStyle={{
                    margin: 0,
                    padding: '16px',
                    fontSize: '14px',
                    height: '100%',
                    overflow: 'auto',
                    borderRadius: '8px',
                  }}
                  lineNumberStyle={{
                    minWidth: '3em',
                    paddingRight: '1em',
                    color: yamlTheme === 'github' ? '#6B7280' : '#9CA3AF',
                    borderRight:
                      yamlTheme === 'github'
                        ? '1px solid #E5E7EB'
                        : '1px solid #374151',
                    marginRight: '1em',
                  }}
                >
                  {yamlContent || '# Nenhum conteúdo YAML disponível'}
                </SyntaxHighlighter>
              )}
            </div>

            {/* Informações na parte inferior */}
            <div className="flex items-center justify-between mt-2 px-2">
              <span className="text-sm text-muted-foreground">
                {yamlEditing
                  ? `${editedYaml.split('\n').length} linhas`
                  : `${yamlContent.split('\n').length} linhas`}
                {yamlEditing && ' (editando)'}
              </span>

              <span className="text-sm text-muted-foreground">
                Recurso: {resourceType} • {yamlTheme}
              </span>
            </div>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}
