import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';

interface ApiKeyContextType {
  apiKey: string;
  setApiKey: (key: string) => void;
  geminiApiKey: string;
  setGeminiApiKey: (key: string) => void;
  isApiKeyValid: boolean;
  googleMapsApiKey: string;
  setGoogleMapsApiKey: (key: string) => void;
  isGoogleMapsKeyValid: boolean;
  reloadMapsApi: () => Promise<void>;
}

const ApiKeyContext = createContext<ApiKeyContextType | undefined>(undefined);

const readStorage = (key: string) =>
  typeof window !== 'undefined' ? window.localStorage?.getItem(key) : null;

const writeStorage = (key: string, value: string) => {
  if (typeof window === 'undefined') return;
  window.localStorage?.setItem(key, value);
};

const removeStorage = (key: string) => {
  if (typeof window === 'undefined') return;
  window.localStorage?.removeItem(key);
};

interface ApiKeyProviderProps {
  children: ReactNode;
  initialApiKey?: string;
  initialGeminiApiKey?: string;
  initialGoogleMapsApiKey?: string;
}

export function ApiKeyProvider({
  children,
  initialApiKey,
  initialGeminiApiKey,
  initialGoogleMapsApiKey,
}: ApiKeyProviderProps) {
  // Lista de chaves conhecidas como vazadas (para limpeza automática)
  const LEAKED_KEYS = [
    'AIzaSyCMsAMytBeOK0Qd7RKFyA5IW9eWt2WTJg',
    'AIzaSyAiYWEIEmx212Up9zfM8kqyMXB4jLs8gq0',
  ];

  const [apiKey, setApiKeyState] = useState<string>(() => {
    if (initialApiKey) return initialApiKey;
    const saved = readStorage('xertica-api-key');
    return saved || '';
  });

  const [geminiApiKey, setGeminiApiKeyState] = useState<string>(() => {
    if (initialGeminiApiKey) return initialGeminiApiKey;
    const saved = readStorage('xertica-gemini-api-key');

    // Se a chave salva estiver na lista de vazadas, removê-la
    if (saved && LEAKED_KEYS.includes(saved)) {
      removeStorage('xertica-gemini-api-key');
      return '';
    }

    return saved || '';
  });

  const [googleMapsApiKey, setGoogleMapsApiKeyState] = useState<string>(() => {
    if (initialGoogleMapsApiKey) return initialGoogleMapsApiKey;
    const saved = readStorage('xertica-googlemaps-api-key');
    return saved || '';
  });

  const [isApiKeyValid, setIsApiKeyValid] = useState(false);
  const [isGoogleMapsKeyValid, setIsGoogleMapsKeyValid] = useState(false);

  useEffect(() => {
    if (initialApiKey !== undefined) {
      setApiKeyState(initialApiKey.trim());
    }
  }, [initialApiKey]);

  useEffect(() => {
    if (initialGeminiApiKey !== undefined) {
      setGeminiApiKeyState(initialGeminiApiKey.trim());
    }
  }, [initialGeminiApiKey]);

  useEffect(() => {
    if (initialGoogleMapsApiKey !== undefined) {
      setGoogleMapsApiKeyState(initialGoogleMapsApiKey.trim());
    }
  }, [initialGoogleMapsApiKey]);

  useEffect(() => {
    if (apiKey) {
      writeStorage('xertica-api-key', apiKey);
      setIsApiKeyValid(apiKey.length > 0);
    } else {
      removeStorage('xertica-api-key');
      setIsApiKeyValid(false);
    }
  }, [apiKey]);

  useEffect(() => {
    if (geminiApiKey) {
      writeStorage('xertica-gemini-api-key', geminiApiKey);
      // Validação básica do formato da chave
      setIsApiKeyValid(geminiApiKey.startsWith('AIzaSy') && geminiApiKey.length > 20);
    } else {
      removeStorage('xertica-gemini-api-key');
      setIsApiKeyValid(false);
    }
  }, [geminiApiKey]);

  useEffect(() => {
    if (googleMapsApiKey) {
      writeStorage('xertica-googlemaps-api-key', googleMapsApiKey);
      // Validação básica do formato da chave do Google Maps
      setIsGoogleMapsKeyValid(
        googleMapsApiKey.startsWith('AIzaSy') && googleMapsApiKey.length > 20
      );

      // Recarregar automaticamente o Google Maps quando a chave mudar
      const reloadMaps = async () => {
        if (googleMapsApiKey.length < 10) return;

        try {
          const { reloadGoogleMaps } = await import('../components/ui/google-maps-loader');
          await reloadGoogleMaps(googleMapsApiKey);
          console.log('[ApiKeyContext] Google Maps recarregado com sucesso');
        } catch (error) {
          console.error('[ApiKeyContext] Erro ao recarregar Google Maps:', error);
        }
      };

      reloadMaps();
    } else {
      removeStorage('xertica-googlemaps-api-key');
      setIsGoogleMapsKeyValid(false);
    }
  }, [googleMapsApiKey]);

  const setApiKey = (key: string) => {
    setApiKeyState(key.trim());
  };

  const setGeminiApiKey = (key: string) => {
    setGeminiApiKeyState(key.trim());
  };

  const setGoogleMapsApiKey = (key: string) => {
    setGoogleMapsApiKeyState(key.trim());
  };

  const reloadMapsApi = async () => {
    if (!googleMapsApiKey || googleMapsApiKey.length < 10) {
      return;
    }

    try {
      // Importar dinamicamente a função de reload
      const { reloadGoogleMaps } = await import('../components/ui/google-maps-loader');
      await reloadGoogleMaps(googleMapsApiKey);
      console.log('[ApiKeyContext] Google Maps recarregado manualmente');
    } catch (error) {
      console.error('[ApiKeyContext] Erro ao recarregar Google Maps:', error);
    }
  };

  return (
    <ApiKeyContext.Provider
      value={{
        apiKey,
        setApiKey,
        geminiApiKey,
        setGeminiApiKey,
        isApiKeyValid,
        googleMapsApiKey,
        setGoogleMapsApiKey,
        isGoogleMapsKeyValid,
        reloadMapsApi,
      }}
    >
      {children}
    </ApiKeyContext.Provider>
  );
}

export function useApiKey() {
  const context = useContext(ApiKeyContext);
  if (!context) {
    throw new Error('useApiKey must be used within ApiKeyProvider');
  }
  return context;
}
