import { useState, useCallback } from 'react';
import { aiApi } from '@/services/api';
import type { TradingPlan } from './types';

export interface UsePlanGenerationReturn {
  generating: boolean;
  error: string | null;
  generatePlan: (currentPrice: number, currentPlan: TradingPlan) => Promise<TradingPlan | null>;
  clearError: () => void;
}

/**
 * Hook for AI-powered trading plan generation
 */
export function usePlanGeneration(
  openRouterReady?: boolean
): UsePlanGenerationReturn {
  const [generating, setGenerating] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const clearError = useCallback(() => {
    setError(null);
  }, []);

  const generatePlan = useCallback(
    async (currentPrice: number, currentPlan: TradingPlan): Promise<TradingPlan | null> => {
      if (openRouterReady === false) {
        setError(
          'AI plan generation requires an OpenRouter API key. Please set OPENROUTER_API_KEY on the backend and restart.'
        );
        return null;
      }

      setGenerating(true);
      setError(null);

      try {
        const aiPlanResponse = await aiApi.generateTradingPlan({
          symbol: 'XAUUSD',
          timeframe: '1m',
          limit: 400,
          current_price: currentPrice,
          user_capital: 100000,
          risk_tolerance: 'MODERATE',
          use_indicator_preferences: true,
        });

        if (!aiPlanResponse) {
          throw new Error('No response from AI plan generation API');
        }

        const generatedPlan: TradingPlan = {
          ...currentPlan,
          date: new Date().toDateString(),
          bias: aiPlanResponse.market_bias || 'NEUTRAL',
          dailyTarget: aiPlanResponse.daily_target ?? currentPlan.dailyTarget,
          maxLoss: aiPlanResponse.max_loss ?? currentPlan.maxLoss,
          entryZone: {
            min: aiPlanResponse.entry_zone_min ?? currentPrice - 10,
            max: aiPlanResponse.entry_zone_max ?? currentPrice + 10,
          },
          targetPrice: aiPlanResponse.target_price ?? currentPrice + 20,
          stopLoss: aiPlanResponse.stop_loss ?? currentPrice - 15,
          keyLevels: {
            support: aiPlanResponse.support_levels?.slice(0, 3) || currentPlan.keyLevels.support,
            resistance:
              aiPlanResponse.resistance_levels?.slice(0, 3) || currentPlan.keyLevels.resistance,
          },
          tradingNotes: aiPlanResponse.trading_notes || aiPlanResponse.reasoning || '',
          maxTrades: aiPlanResponse.max_trades ?? currentPlan.maxTrades,
          contextMetrics: aiPlanResponse.context_metrics || currentPlan.contextMetrics,
        };

        return generatedPlan;
      } catch (err) {
        if (err instanceof Error && err.message.includes('OPENROUTER_API_KEY')) {
          setError(
            'AI plan generation requires an OpenRouter API key. Set OPENROUTER_API_KEY on the backend and restart the server.'
          );
        } else {
          const message = err instanceof Error ? err.message : 'Failed to generate AI plan';
          setError(message);
        }
        return null;
      } finally {
        setGenerating(false);
      }
    },
    [openRouterReady]
  );

  return {
    generating,
    error,
    generatePlan,
    clearError,
  };
}
