import { useState, useEffect, useCallback } from 'react';

export interface KubeconfigItem {
  id: string;
  name: string;
  path: string;
  isDefault: boolean;
  isActive: boolean;
  context?: string;
  cluster?: string;
  user?: string;
  createdAt: string;
  skipTLSVerify?: boolean;
  color?: string;
}

const STORAGE_KEY = 'kubeconfigs';
const ACTIVE_CONFIG_KEY = 'activeKubeconfig';

const defaultKubeconfig: KubeconfigItem = {
  id: 'default',
  name: 'Kubeconfig Padrão',
  path: '~/.kube/config',
  isDefault: true,
  isActive: true,
  context: 'docker-desktop',
  cluster: 'docker-desktop',
  user: 'docker-desktop',
  createdAt: new Date().toISOString(),
  color: '#3b82f6',
};

// Estado global compartilhado
let globalKubeconfigs: KubeconfigItem[] = [];
let globalActiveConfig: KubeconfigItem | null = null;
let isInitialized = false;
const subscribers: Set<() => void> = new Set();

// Função para notificar todos os subscribers
const notifySubscribers = () => {
  subscribers.forEach((callback) => callback());
};

// Função para inicializar dados do localStorage
const initializeData = () => {
  if (isInitialized) return; // Já inicializado

  const savedConfigs = localStorage.getItem(STORAGE_KEY);
  const savedActiveId = localStorage.getItem(ACTIVE_CONFIG_KEY);

  console.log('🔍 Initializing kubeconfigs from localStorage:', {
    savedConfigs: savedConfigs ? 'found' : 'not found',
    savedActiveId,
  });

  let configs: KubeconfigItem[] = [];

  if (savedConfigs) {
    try {
      configs = JSON.parse(savedConfigs);
      console.log('📋 Loaded', configs.length, 'configs from localStorage');

      // Verificar se o padrão existe, se não, adicionar
      const hasDefault = configs.some((config) => config.isDefault);
      if (!hasDefault) {
        console.log('➕ Adding missing default config');
        configs.unshift(defaultKubeconfig);
      }

      // Garantir que todos os configs têm cor
      configs = configs.map((config) => ({
        ...config,
        color: config.color || (config.isDefault ? '#3b82f6' : '#6366f1'),
      }));
    } catch (error) {
      console.error(
        '❌ Error parsing localStorage configs, resetting to default only',
      );
      configs = [defaultKubeconfig];
    }
  } else {
    // Primeira vez - criar apenas com o padrão
    configs = [defaultKubeconfig];
    console.log('🆕 First time, using default config only');
  }

  // Definir qual está ativo, com fallback para padrão se não encontrar
  let active = configs.find((config) => config.id === savedActiveId);
  if (!active) {
    // Se o ativo salvo não existe, usar o padrão
    active = configs.find((config) => config.isDefault) || configs[0];
    if (savedActiveId) {
      console.warn(
        '⚠️ Active kubeconfig not found:',
        savedActiveId,
        'falling back to:',
        active?.name,
      );
    }
  }

  console.log('✅ Active config set to:', active?.name, active?.id);

  // Atualizar flags de ativo
  configs = configs.map((config) => ({
    ...config,
    isActive: config.id === active!.id,
  }));

  globalKubeconfigs = configs;
  globalActiveConfig = active;
  isInitialized = true;

  // Salvar no localStorage apenas se algo mudou
  const currentSaved = localStorage.getItem(STORAGE_KEY);
  const newConfigsJson = JSON.stringify(globalKubeconfigs);

  if (currentSaved !== newConfigsJson) {
    localStorage.setItem(STORAGE_KEY, newConfigsJson);
    console.log(
      '💾 Saved',
      globalKubeconfigs.length,
      'configs to localStorage',
    );
  }

  if (localStorage.getItem(ACTIVE_CONFIG_KEY) !== globalActiveConfig!.id) {
    localStorage.setItem(ACTIVE_CONFIG_KEY, globalActiveConfig!.id);
    console.log(
      '💾 Saved active config:',
      globalActiveConfig!.name,
      globalActiveConfig!.id,
    );
  }
};

export function useKubeconfigs() {
  const [, forceUpdate] = useState({});

  // Força re-render quando o estado global muda
  const triggerUpdate = useCallback(() => {
    forceUpdate({});
  }, []);

  // Registrar/desregistrar subscriber
  useEffect(() => {
    initializeData();
    subscribers.add(triggerUpdate);

    return () => {
      subscribers.delete(triggerUpdate);
    };
  }, [triggerUpdate]);

  // Salvar no localStorage sempre que houver mudanças
  const saveToStorage = (configs: KubeconfigItem[], activeId: string) => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(configs));
    localStorage.setItem(ACTIVE_CONFIG_KEY, activeId);
  };

  const addKubeconfig = (name: string, path: string, color?: string) => {
    const newConfig: KubeconfigItem = {
      id: Date.now().toString(),
      name: name.trim(),
      path: path.trim(),
      isDefault: false,
      isActive: false,
      createdAt: new Date().toISOString(),
      color: color || '#6366f1',
    };

    globalKubeconfigs = [...globalKubeconfigs, newConfig];
    saveToStorage(globalKubeconfigs, globalActiveConfig?.id || 'default');
    notifySubscribers();

    return newConfig;
  };

  const updateKubeconfig = useCallback(
    (id: string, name: string, path: string, color?: string) => {
      globalKubeconfigs = globalKubeconfigs.map((config) =>
        config.id === id
          ? {
              ...config,
              name: name.trim(),
              path: path.trim(),
              color: color || config.color,
            }
          : config,
      );

      // Atualizar activeConfig se for o mesmo que está sendo editado
      if (globalActiveConfig?.id === id) {
        const updatedActive = globalKubeconfigs.find((c) => c.id === id);
        if (updatedActive) {
          console.log('Updating active config:', updatedActive); // Debug
          globalActiveConfig = updatedActive;
        }
      }

      saveToStorage(globalKubeconfigs, globalActiveConfig?.id || 'default');
      notifySubscribers();
    },
    [],
  );

  const removeKubeconfig = (id: string) => {
    const configToRemove = globalKubeconfigs.find((c) => c.id === id);

    // Não permitir remover o padrão
    if (configToRemove?.isDefault) {
      throw new Error('Não é possível remover a configuração padrão');
    }

    const updatedConfigs = globalKubeconfigs.filter(
      (config) => config.id !== id,
    );

    // Se estava ativo, ativar o padrão
    let newActiveId = globalActiveConfig?.id || 'default';
    if (globalActiveConfig?.id === id) {
      const defaultConfig = updatedConfigs.find((c) => c.isDefault);
      newActiveId = defaultConfig?.id || updatedConfigs[0]?.id || 'default';
      globalActiveConfig = defaultConfig || updatedConfigs[0] || null;
    }

    // Atualizar flags de ativo
    globalKubeconfigs = updatedConfigs.map((config) => ({
      ...config,
      isActive: config.id === newActiveId,
    }));

    saveToStorage(globalKubeconfigs, newActiveId);
    notifySubscribers();
  };

  const setActiveKubeconfig = (id: string) => {
    const selectedConfig = globalKubeconfigs.find((config) => config.id === id);
    if (!selectedConfig) return;

    console.log(
      '🔄 Changing active kubeconfig to:',
      selectedConfig.name,
      selectedConfig.path,
    );

    globalKubeconfigs = globalKubeconfigs.map((config) => ({
      ...config,
      isActive: config.id === id,
    }));

    globalActiveConfig = selectedConfig;
    saveToStorage(globalKubeconfigs, id);
    notifySubscribers();

    console.log(
      '✅ Active kubeconfig changed to:',
      globalActiveConfig?.name,
      globalActiveConfig?.path,
    );
  };

  const getActiveKubeconfig = () => {
    return globalActiveConfig;
  };

  const getAllKubeconfigs = () => {
    return globalKubeconfigs;
  };

  const resetToDefault = () => {
    // Reset para configuração padrão e limpa localStorage
    const defaultConfig = {
      ...defaultKubeconfig,
      isActive: true,
      color: '#3b82f6',
    };
    globalKubeconfigs = [defaultConfig];
    globalActiveConfig = defaultConfig;

    localStorage.setItem(STORAGE_KEY, JSON.stringify([defaultConfig]));
    localStorage.setItem(ACTIVE_CONFIG_KEY, defaultConfig.id);

    notifySubscribers();
  };

  const forceReload = () => {
    // Força recarregamento dos dados do localStorage
    console.log('🔄 Force reloading kubeconfigs...');

    // Preservar dados existentes se houver algum problema
    const currentConfigs = globalKubeconfigs;
    const currentActive = globalActiveConfig;

    isInitialized = false;
    globalKubeconfigs = [];
    globalActiveConfig = null;

    try {
      initializeData();
    } catch (error) {
      console.error(
        '❌ Error during force reload, restoring previous state:',
        error,
      );
      // Restaurar estado anterior se houver erro
      globalKubeconfigs = currentConfigs;
      globalActiveConfig = currentActive;
      isInitialized = true;
    }

    notifySubscribers();
  };

  const cleanupInvalidConfigs = () => {
    // Remove apenas configurações específicas problemáticas
    const validConfigs = globalKubeconfigs.filter((config) => {
      // Sempre manter a configuração padrão
      if (config.isDefault) return true;

      // Remover apenas configurações específicas problemáticas
      if (
        config.path === 'integrada.yaml' ||
        config.path.includes('integrada')
      ) {
        console.log('🗑️ Manually removing integrada config:', config.name);
        return false;
      }
      if (config.id === 'prod-auto' || config.name === 'Produção OCI') {
        console.log('🗑️ Manually removing prod-auto config:', config.name);
        return false;
      }

      // Manter todas as outras configurações válidas
      return true;
    });

    if (validConfigs.length !== globalKubeconfigs.length) {
      console.log('🧹 Cleaned up invalid configs');
      globalKubeconfigs = validConfigs;

      // Se o ativo foi removido, usar o padrão
      if (!validConfigs.find((c) => c.id === globalActiveConfig?.id)) {
        globalActiveConfig =
          validConfigs.find((c) => c.isDefault) || validConfigs[0];
      }

      // Atualizar flags de ativo
      globalKubeconfigs = validConfigs.map((config) => ({
        ...config,
        isActive: config.id === globalActiveConfig!.id,
      }));

      saveToStorage(globalKubeconfigs, globalActiveConfig!.id);
      notifySubscribers();
    }
  };

  return {
    kubeconfigs: globalKubeconfigs,
    activeConfig: globalActiveConfig,
    addKubeconfig,
    updateKubeconfig,
    removeKubeconfig,
    setActiveKubeconfig,
    getActiveKubeconfig,
    getAllKubeconfigs,
    resetToDefault,
    forceReload,
    cleanupInvalidConfigs,
  };
}
