import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { useToast } from '@/hooks/useToast';
import { useKubeconfigs } from '@/hooks/useKubeconfigs';
import {
  ArrowLeft,
  Settings,
  FileText,
  Upload,
  CheckCircle,
  AlertTriangle,
  Loader2,
  FolderOpen,
  Copy,
  Save,
} from 'lucide-react';

type ImportMethod = 'file' | 'paste';

interface KubeconfigContent {
  apiVersion: string;
  kind: string;
  clusters?: Array<{
    name: string;
    cluster: {
      server: string;
      [key: string]: any;
    };
  }>;
  contexts?: Array<{
    name: string;
    context: {
      cluster: string;
      user: string;
      namespace?: string;
    };
  }>;
  users?: Array<{
    name: string;
    [key: string]: any;
  }>;
  'current-context'?: string;
}

export function KubeconfigWizardPage() {
  const navigate = useNavigate();
  const { showToast } = useToast();
  const { addKubeconfig, forceReload } = useKubeconfigs();

  const [step, setStep] = useState(1);
  const [importMethod, setImportMethod] = useState<ImportMethod>('file');
  const [configName, setConfigName] = useState('');
  const [configContent, setConfigContent] = useState('');
  const [selectedFilePath, setSelectedFilePath] = useState('');
  const [selectedFileFullPath, setSelectedFileFullPath] = useState('');
  const [parsedConfig, setParsedConfig] = useState<KubeconfigContent | null>(
    null,
  );
  const [parseError, setParseError] = useState('');
  const [isProcessing, setIsProcessing] = useState(false);
  const [configColor, setConfigColor] = useState('#6366f1');

  const handleFileSelect = async () => {
    try {
      const result = await window.electron?.ipcRenderer.selectKubeconfigFile();

      if (result.success) {
        setConfigContent(result.content);
        setSelectedFilePath(result.fileName);
        setSelectedFileFullPath(result.filePath);

        // Auto-parse o kubeconfig
        handleParseConfig(result.content);

        // Auto-preencher o nome se estiver vazio
        if (!configName) {
          const baseName = result.fileName.replace(/\.(yaml|yml|config)$/, '');
          setConfigName(
            baseName === 'config' ? 'kubeconfig-importado' : baseName,
          );
        }
      } else if (result.error) {
        showToast({
          title: 'Erro',
          description: result.error,
          variant: 'destructive',
        });
      }
    } catch (error) {
      showToast({
        title: 'Erro',
        description: 'Falha ao selecionar arquivo',
        variant: 'destructive',
      });
    }
  };

  // Função removida - não mais necessária com o novo método

  const handleParseConfig = (content: string) => {
    try {
      // Tentar fazer parse como YAML primeiro
      let parsed: any;

      // Simular parser YAML básico para kubeconfig
      if (content.includes('apiVersion:') && content.includes('kind:')) {
        // É um kubeconfig YAML
        // Para simplificar, vamos apenas verificar se contém as seções necessárias
        const hasApiVersion = content.includes('apiVersion:');
        const hasKind = content.includes('kind:');
        const hasClusters = content.includes('clusters:');
        const hasContexts = content.includes('contexts:');
        const hasUsers = content.includes('users:');

        if (hasApiVersion && hasKind && hasClusters && hasContexts) {
          // Parse básico para extrair informações
          const lines = content.split('\n');
          const clusters: string[] = [];
          const contexts: string[] = [];
          let currentContext = '';

          for (let i = 0; i < lines.length; i++) {
            const line = lines[i].trim();
            if (line.startsWith('- name:') && i > 0) {
              const prevSection = lines
                .slice(Math.max(0, i - 10), i)
                .join('\n');
              if (prevSection.includes('clusters:')) {
                clusters.push(line.replace('- name:', '').trim());
              } else if (prevSection.includes('contexts:')) {
                contexts.push(line.replace('- name:', '').trim());
              }
            } else if (line.startsWith('current-context:')) {
              currentContext = line.replace('current-context:', '').trim();
            }
          }

          parsed = {
            apiVersion: 'v1',
            kind: 'Config',
            clusters: clusters.map((name) => ({
              name,
              cluster: { server: 'parsed-from-config' },
            })),
            contexts: contexts.map((name) => ({
              name,
              context: { cluster: name, user: name },
            })),
            'current-context': currentContext,
          };
        } else {
          throw new Error('Kubeconfig incompleto');
        }
      } else {
        throw new Error('Formato de kubeconfig inválido');
      }

      setParsedConfig(parsed);
      setParseError('');
    } catch (error) {
      setParseError('Kubeconfig inválido. Verifique o formato YAML.');
      setParsedConfig(null);
    }
  };

  const handleParseContent = () => {
    handleParseConfig(configContent);
  };

  const handleNextStep = () => {
    if (step === 1) {
      setStep(2);
    } else if (step === 2) {
      if (importMethod === 'file' && !selectedFilePath) {
        showToast({
          title: 'Arquivo Necessário',
          description: 'Por favor, selecione um arquivo kubeconfig',
          variant: 'destructive',
        });
        return;
      }
      if (importMethod === 'paste' && !configContent.trim()) {
        showToast({
          title: 'Conteúdo Necessário',
          description: 'Por favor, cole o conteúdo do kubeconfig',
          variant: 'destructive',
        });
        return;
      }
      if (importMethod === 'paste' && !parsedConfig) {
        showToast({
          title: 'Validação Necessária',
          description: 'Por favor, valide o kubeconfig antes de continuar',
          variant: 'destructive',
        });
        return;
      }
      if (importMethod === 'paste') {
        handleParseConfig(configContent);
      }
      setStep(3);
    }
  };

  const handlePrevStep = () => {
    if (step > 1) {
      setStep(step - 1);
    }
  };

  const generateConfigPath = async (): Promise<string> => {
    if (importMethod === 'file') {
      // Se é um arquivo, retornar o caminho completo que já foi obtido
      return selectedFileFullPath;
    }
    // Se é conteúdo colado, criar um arquivo na pasta do usuário
    try {
      const result = await window.electron?.ipcRenderer.saveKubeconfigContent(
        configName,
        configContent,
      );

      if (result.success) {
        return result.filePath;
      }
      throw new Error(result.error || 'Falha ao salvar arquivo');
    } catch (error) {
      throw new Error('Falha ao salvar arquivo de configuração');
    }
  };

  const handleCreateConfig = async () => {
    if (!parsedConfig || !configName.trim()) return;

    setIsProcessing(true);
    try {
      const configPath = await generateConfigPath();

      const newConfig = addKubeconfig(
        configName.trim(),
        configPath,
        configColor,
      );

      // Forçar recarregamento para garantir sincronização
      forceReload();

      showToast({
        title: 'Configuração Adicionada',
        description: `Kubeconfig "${newConfig.name}" foi adicionado com sucesso`,
        variant: 'success',
      });

      // Navegar de volta para a página de configurações
      setTimeout(() => {
        navigate('/settings/kubeconfigs');
      }, 1500);
    } catch (error) {
      showToast({
        title: 'Erro',
        description: error instanceof Error ? error.message : 'Erro inesperado',
        variant: 'destructive',
      });
      setIsProcessing(false); // Só reabilita em caso de erro
    }
    // Não reabilita o botão em caso de sucesso - deixa processando até navegar
  };

  const getCurrentStepData = () => {
    switch (step) {
      case 1:
        return {
          title: 'Método de Importação',
          description: 'Como você deseja adicionar o kubeconfig?',
        };
      case 2:
        return {
          title:
            importMethod === 'file' ? 'Selecionar Arquivo' : 'Colar Conteúdo',
          description:
            importMethod === 'file'
              ? 'Selecione o arquivo kubeconfig do seu sistema'
              : 'Cole o conteúdo do seu arquivo kubeconfig',
        };
      case 3:
        return {
          title: 'Configuração',
          description: 'Configure o nome, cor e revise as informações',
        };
      default:
        return { title: '', description: '' };
    }
  };

  const stepData = getCurrentStepData();

  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">
              <Settings className="h-8 w-8 mr-3 text-blue-600" />
              Adicionar Kubeconfig
            </h1>
            <p className="text-muted-foreground">{stepData.description}</p>
          </div>
        </div>
      </div>

      {/* Wizard Steps */}
      <div className="flex items-center space-x-4 text-sm">
        <div className="flex items-center">
          <div
            className={`w-8 h-8 ${step >= 1 ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-600'} rounded-full flex items-center justify-center font-medium`}
          >
            1
          </div>
          <span
            className={`ml-2 ${step === 1 ? 'font-medium' : 'text-gray-600'}`}
          >
            Método
          </span>
        </div>
        <div className="h-px bg-gray-300 flex-1" />
        <div className="flex items-center">
          <div
            className={`w-8 h-8 ${step >= 2 ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-600'} rounded-full flex items-center justify-center font-medium`}
          >
            2
          </div>
          <span
            className={`ml-2 ${step === 2 ? 'font-medium' : 'text-gray-600'}`}
          >
            Importação
          </span>
        </div>
        <div className="h-px bg-gray-300 flex-1" />
        <div className="flex items-center">
          <div
            className={`w-8 h-8 ${step >= 3 ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-600'} rounded-full flex items-center justify-center font-medium`}
          >
            3
          </div>
          <span
            className={`ml-2 ${step === 3 ? 'font-medium' : 'text-gray-600'}`}
          >
            Configuração
          </span>
        </div>
      </div>

      {/* Step Content */}
      <Card>
        <CardHeader>
          <CardTitle>{stepData.title}</CardTitle>
        </CardHeader>
        <CardContent>
          {step === 1 && (
            <div className="space-y-4">
              <RadioGroup
                value={importMethod}
                onValueChange={(value: ImportMethod) => setImportMethod(value)}
              >
                <div className="flex items-center space-x-2 p-4 border rounded-lg hover:bg-gray-50">
                  <RadioGroupItem value="file" id="file" />
                  <Label htmlFor="file" className="flex-1 cursor-pointer">
                    <div className="flex items-center">
                      <FolderOpen className="h-5 w-5 mr-3 text-blue-600" />
                      <div>
                        <div className="font-medium">Selecionar Arquivo</div>
                        <div className="text-sm text-muted-foreground">
                          Escolha um arquivo kubeconfig existente do seu sistema
                        </div>
                      </div>
                    </div>
                  </Label>
                </div>
                <div className="flex items-center space-x-2 p-4 border rounded-lg hover:bg-gray-50">
                  <RadioGroupItem value="paste" id="paste" />
                  <Label htmlFor="paste" className="flex-1 cursor-pointer">
                    <div className="flex items-center">
                      <Copy className="h-5 w-5 mr-3 text-green-600" />
                      <div>
                        <div className="font-medium">Colar Conteúdo</div>
                        <div className="text-sm text-muted-foreground">
                          Cole o conteúdo YAML do kubeconfig diretamente
                        </div>
                      </div>
                    </div>
                  </Label>
                </div>
              </RadioGroup>
            </div>
          )}

          {step === 2 && importMethod === 'file' && (
            <div className="space-y-4">
              <div>
                <Label>Arquivo Kubeconfig</Label>
                <div className="mt-2">
                  <Button
                    onClick={handleFileSelect}
                    variant="outline"
                    className="w-full"
                  >
                    <FolderOpen className="h-4 w-4 mr-2" />
                    {selectedFilePath || 'Selecionar Arquivo Kubeconfig'}
                  </Button>
                </div>
              </div>

              {selectedFilePath && (
                <div className="p-4 bg-green-50 border border-green-200 rounded-lg">
                  <div className="flex items-center">
                    <CheckCircle className="h-5 w-5 text-green-600 mr-2" />
                    <div>
                      <div className="font-medium text-green-800">
                        Arquivo Selecionado
                      </div>
                      <div className="text-sm text-green-700">
                        {selectedFilePath}
                      </div>
                    </div>
                  </div>
                </div>
              )}

              {parseError && (
                <div className="flex items-center text-red-600 text-sm p-3 bg-red-50 border border-red-200 rounded-lg">
                  <AlertTriangle className="h-4 w-4 mr-2" />
                  {parseError}
                </div>
              )}
            </div>
          )}

          {step === 2 && importMethod === 'paste' && (
            <div className="space-y-4">
              <div>
                <Label htmlFor="config-content">Conteúdo do Kubeconfig</Label>
                <Textarea
                  id="config-content"
                  placeholder="apiVersion: v1
kind: Config
clusters:
- cluster:
    server: https://..."
                  value={configContent}
                  onChange={(e) => {
                    setConfigContent(e.target.value);
                    // Limpar validação anterior quando o conteúdo muda
                    setParsedConfig(null);
                    setParseError('');
                  }}
                  rows={12}
                  className="font-mono text-sm"
                />
              </div>

              <Button
                onClick={handleParseContent}
                disabled={!configContent.trim()}
              >
                <FileText className="h-4 w-4 mr-2" />
                Validar Kubeconfig
              </Button>

              {parseError && (
                <div className="flex items-center text-red-600 text-sm p-3 bg-red-50 border border-red-200 rounded-lg">
                  <AlertTriangle className="h-4 w-4 mr-2" />
                  {parseError}
                </div>
              )}

              {parsedConfig && (
                <div className="flex items-center text-green-600 text-sm p-3 bg-green-50 border border-green-200 rounded-lg">
                  <CheckCircle className="h-4 w-4 mr-2" />
                  Kubeconfig válido! {parsedConfig.clusters?.length || 0}{' '}
                  cluster(s) encontrado(s).
                </div>
              )}
            </div>
          )}

          {step === 3 && (
            <div className="space-y-6">
              <div>
                <Label htmlFor="config-name">Nome da Configuração</Label>
                <Input
                  id="config-name"
                  placeholder="Ex: Produção, Desenvolvimento, Staging"
                  value={configName}
                  onChange={(e) => setConfigName(e.target.value)}
                />
              </div>

              <div>
                <Label htmlFor="config-color">Cor do Ambiente</Label>
                <div className="flex items-center space-x-3 mt-2">
                  <input
                    id="config-color"
                    type="color"
                    value={configColor}
                    onChange={(e) => setConfigColor(e.target.value)}
                    className="w-12 h-10 rounded-md border border-input cursor-pointer"
                  />
                  <div className="flex-1">
                    <Input
                      value={configColor}
                      onChange={(e) => setConfigColor(e.target.value)}
                      placeholder="#6366f1"
                    />
                  </div>
                </div>
                <p className="text-sm text-muted-foreground mt-1">
                  Esta cor será aplicada ao menu lateral quando esta
                  configuração estiver ativa
                </p>
              </div>

              {parsedConfig && (
                <div className="p-4 bg-gray-50 rounded-lg">
                  <h4 className="font-medium mb-3">Preview da Configuração:</h4>
                  <div className="text-sm space-y-2">
                    <div>
                      <strong>Clusters:</strong>{' '}
                      {parsedConfig.clusters?.map((c) => c.name).join(', ') ||
                        'Nenhum'}
                    </div>
                    <div>
                      <strong>Contextos:</strong>{' '}
                      {parsedConfig.contexts?.map((c) => c.name).join(', ') ||
                        'Nenhum'}
                    </div>
                    <div>
                      <strong>Contexto Atual:</strong>{' '}
                      {parsedConfig['current-context'] || 'Não especificado'}
                    </div>
                    <div>
                      <strong>Método:</strong>{' '}
                      {importMethod === 'file'
                        ? 'Arquivo selecionado'
                        : 'Conteúdo colado'}
                    </div>
                    {importMethod === 'file' && (
                      <div>
                        <strong>Arquivo:</strong> {selectedFilePath}
                      </div>
                    )}
                    {importMethod === 'paste' && (
                      <div>
                        <strong>Será salvo em:</strong> ~/.kube-now/configs/
                      </div>
                    )}
                  </div>
                </div>
              )}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Navigation */}
      <div className="flex justify-between">
        <Button
          variant="outline"
          onClick={handlePrevStep}
          disabled={step === 1}
        >
          Anterior
        </Button>

        <div className="flex space-x-2">
          <Button
            variant="outline"
            onClick={() => navigate('/settings/kubeconfigs')}
          >
            Cancelar
          </Button>

          {step < 3 ? (
            <Button
              onClick={handleNextStep}
              disabled={
                (step === 2 && importMethod === 'file' && !selectedFilePath) ||
                (step === 2 &&
                  importMethod === 'paste' &&
                  (!configContent.trim() || !parsedConfig))
              }
            >
              Próximo
            </Button>
          ) : (
            <Button
              onClick={handleCreateConfig}
              disabled={!parsedConfig || !configName.trim() || isProcessing}
            >
              {isProcessing ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  Adicionando Configuração...
                </>
              ) : (
                <>
                  <Save className="h-4 w-4 mr-2" />
                  Adicionar Configuração
                </>
              )}
            </Button>
          )}
        </div>
      </div>
    </div>
  );
}
