'use client';

import React, { createContext, useContext, useState, useCallback, ReactNode } from 'react';
import { EarnLayerClient } from '../../core/EarnLayerClient';
import { ConversationOptions } from '../../core/types';

interface EarnLayerContextValue {
  client: EarnLayerClient;
  conversationId: string | null;
  isReady: boolean;
  error: string | null;
  initializeConversation: (options?: ConversationOptions) => Promise<string>;
}

const EarnLayerContext = createContext<EarnLayerContextValue | null>(null);

export interface EarnLayerProviderProps {
  children: ReactNode;
  proxyBaseUrl?: string;
  conversationOptions?: ConversationOptions;
  debug?: boolean;
}

export const EarnLayerProvider: React.FC<EarnLayerProviderProps> = ({ 
  children, 
  proxyBaseUrl,
  conversationOptions,
  debug = false
}) => {
  const [client] = useState(() => {
    return new EarnLayerClient({ proxyBaseUrl });
  });

  const [conversationId, setConversationId] = useState<string | null>(null);
  const [isReady, setIsReady] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const initializeConversation = useCallback(async (runtimeOptions?: ConversationOptions) => {
    try {
      setError(null);
      
      // Merge provider options with runtime options (runtime takes precedence)
      const mergedOptions: ConversationOptions = {
        ...conversationOptions,
        ...runtimeOptions
      };
      
      if (debug) {
        console.log('[EarnLayer SDK - Provider] Initializing conversation', {
          providerOptions: conversationOptions,
          runtimeOptions,
          mergedOptions,
          timestamp: new Date().toISOString()
        });
      }
      
      const response = await client.initializeConversation(mergedOptions);
      setConversationId(response.conversation_id);
      setIsReady(true);
      
      if (debug) {
        console.log('[EarnLayer SDK - Provider] Conversation initialized', {
          conversationId: response.conversation_id,
          timestamp: new Date().toISOString()
        });
      }
      
      return response.conversation_id;
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : String(err);
      setError(errorMessage);
      setIsReady(false);
      
      if (debug) {
        console.error('[EarnLayer SDK - Provider] Initialization error:', {
          error: errorMessage,
          timestamp: new Date().toISOString()
        });
      }
      
      throw err;
    }
  }, [client, conversationOptions, debug]);

  return (
    <EarnLayerContext.Provider value={{ client, conversationId, isReady, error, initializeConversation }}>
      {children}
    </EarnLayerContext.Provider>
  );
};

export const useEarnLayerClient = () => {
  const context = useContext(EarnLayerContext);
  if (!context) {
    throw new Error('useEarnLayerClient must be used within EarnLayerProvider');
  }
  return context;
};

export const useEarnLayer = useEarnLayerClient;
