import {useQuery} from '@tanstack/react-query'
import React, {useEffect, useState} from 'react'
import {type SubmitHandler, useForm} from 'react-hook-form'

import useApiUrlStore from '../../../app/store/apiStore'
import useBacktestStore from '../../../app/store/backtestStore'
import {useCustomMoneyManagement} from '../../../app/store/customMoneyManagement'
import {useCustomScenario} from '../../../app/store/customScenario'
import {
  AccountClient,
  BacktestClient,
  BotClient,
  DataClient,
  LightBacktestResponse,
  LightScenario,
  MoneyManagement,
  MoneyManagementClient,
  RiskManagement,
  RiskToleranceLevel,
  RunBacktestRequest,
  ScenarioClient,
  ScenarioRequest,
  SignalType,
  StartBotRequest,
  Ticker,
  Timeframe,
  TradingBotConfigRequest,
  UpdateBotConfigRequest,
} from '../../../generated/ManagingApi'
import type {IUnifiedTradingConfigInput, UnifiedTradingModalProps} from '../../../global/type'
import {Loader} from '../../atoms'
import {Modal, Toast} from '../../mollecules'
import FormInput from '../../mollecules/FormInput/FormInput'
import CustomMoneyManagement from '../CustomMoneyManagement/CustomMoneyManagement'
import CustomScenario from '../CustomScenario/CustomScenario'

const UnifiedTradingModal: React.FC<UnifiedTradingModalProps> = ({
  showModal,
  closeModal,
  mode,
  setBacktests,
  backtest,
  existingBot,
  onBacktestComplete,
}) => {
  // Default dates for backtests
  const defaultStartDate = new Date();
  defaultStartDate.setDate(defaultStartDate.getDate() - 15);
  const defaultStartDateString = defaultStartDate.toISOString().split('T')[0];
  
  const defaultEndDate = new Date();
  const defaultEndDateString = defaultEndDate.toISOString().split('T')[0];

  const [startDate, setStartDate] = useState<string>(defaultStartDateString);
  const [endDate, setEndDate] = useState<string>(defaultEndDateString);

  // Initialize default risk management
  const getDefaultRiskManagement = (): RiskManagement => ({
    adverseProbabilityThreshold: 0.20,
    favorableProbabilityThreshold: 0.30,
    riskAversion: 1.0,
    kellyMinimumThreshold: 0.01,
    kellyMaximumCap: 0.25,
    maxLiquidationProbability: 0.10,
    signalValidationTimeHorizonHours: 24,
    positionMonitoringTimeHorizonHours: 6,
    positionWarningThreshold: 0.20,
    positionAutoCloseThreshold: 0.50,
    kellyFractionalMultiplier: 1.0,
    riskTolerance: RiskToleranceLevel.Moderate,
    useExpectedUtility: true,
    useKellyCriterion: true,
  });

  // Default form values based on mode
  const getDefaultFormValues = (): Partial<IUnifiedTradingConfigInput> => {
    const base = {
      startDate: defaultStartDateString,
      endDate: defaultEndDateString,
      cooldownPeriod: 10,
      maxLossStreak: 0,
      maxPositionTimeHours: null,
      flipOnlyWhenInProfit: true,
      balance: 10000,
      closeEarlyWhenProfitable: false,
      useSynthApi: false,
      useForPositionSizing: true,
      useForSignalFiltering: true,
      useForDynamicStopLoss: true,
      useCustomRiskManagement: false,
      riskManagement: getDefaultRiskManagement(),
    };

    if (mode === 'backtest') {
      return {
        ...base,
        save: true, // Changed from false to true
      };
    } else {
      return {
        ...base,
        name: `${mode === 'createBot' ? 'Bot' : 'Updated-Bot'}-${new Date().toISOString().slice(0, 19).replace(/[-:]/g, '')}`,
        isForWatchingOnly: false,
        flipPosition: false,
      };
    }
  };

  const { register, handleSubmit, setValue, watch, getValues } = useForm<IUnifiedTradingConfigInput>({
    defaultValues: getDefaultFormValues(),
  });

  // Watch important values
  const useSynthApi = watch('useSynthApi');
  const useCustomRiskManagement = watch('useCustomRiskManagement');
  const selectedTimeframe = watch('timeframe');

  // State management continues below...

  // State for collapsible sections
  const [showAdvancedParams, setShowAdvancedParams] = useState(false);
  const [showRiskManagement, setShowRiskManagement] = useState(false);
  const [showJsonImport, setShowJsonImport] = useState(false);



  // Custom components state
  const [customMoneyManagement, setCustomMoneyManagement] = useState<MoneyManagement | undefined>(undefined);
  const [selectedMoneyManagement, setSelectedMoneyManagement] = useState<string>();
  const [showCustomMoneyManagement, setShowCustomMoneyManagement] = useState(false);

  const [customScenario, setCustomScenario] = useState<LightScenario | undefined>(undefined);
  const [selectedScenario, setSelectedScenario] = useState<string>();
  const [showCustomScenario, setShowCustomScenario] = useState(false);
  
  // Selected ticker for bots (separate from form tickers for backtests)
  const [selectedTicker, setSelectedTicker] = useState<Ticker | undefined>(undefined);

  // JSON import state
  const [jsonConfig, setJsonConfig] = useState('');
  const [importError, setImportError] = useState('');

  const { apiUrl } = useApiUrlStore();
  const { addBacktest } = useBacktestStore();
  const { setCustomMoneyManagement: setGlobalCustomMoneyManagement } = useCustomMoneyManagement();
  const { setCustomScenario: setGlobalCustomScenario } = useCustomScenario();

  // API clients
  const scenarioClient = new ScenarioClient({}, apiUrl);
  const accountClient = new AccountClient({}, apiUrl);
  const dataClient = new DataClient({}, apiUrl);
  const moneyManagementClient = new MoneyManagementClient({}, apiUrl);
  const backtestClient = new BacktestClient({}, apiUrl);
  const botClient = new BotClient({}, apiUrl);

  // Data fetching
  const { data: accounts } = useQuery({
    queryFn: () => accountClient.account_GetAccounts(),
    queryKey: ['accounts'],
  });

  const { data: scenarios } = useQuery({
    queryFn: () => scenarioClient.scenario_GetScenarios(),
    queryKey: ['scenarios'],
  });

  const { data: moneyManagements } = useQuery({
    queryFn: async () => {
      return await moneyManagementClient.moneyManagement_GetMoneyManagements();
    },
    queryKey: ['moneyManagements'],
  });

  const { data: tickers, refetch: refetchTickers } = useQuery({
    enabled: !!selectedTimeframe && mode === 'backtest',
    queryFn: () => {
      if (selectedTimeframe) {
        return dataClient.data_GetTickers(selectedTimeframe);
      }
    },
    queryKey: ['tickers', selectedTimeframe],
  });

  // Initialize form based on mode and props
  useEffect(() => {
    if (mode === 'createBot' && backtest) {
      // Initialize from backtest
      setValue('name', `Bot-${backtest.config.scenarioName || 'Custom'}-${new Date().toISOString().slice(0, 19).replace(/[-:]/g, '')}`);
      setValue('accountName', backtest.config.accountName);
      // For bots, we'll use the first ticker from the backtest
      if (backtest.config.ticker) {
        // Store ticker in state for bot submission
        setSelectedTicker(backtest.config.ticker);
      }
      setValue('scenarioName', backtest.config.scenarioName || '');
      
      // Handle custom scenario from backtest
      if ((backtest.config as any).scenario) {
        setShowCustomScenario(true);
        setCustomScenario((backtest.config as any).scenario);
        setGlobalCustomScenario((backtest.config as any).scenario); // Also update global store for prefilling
        setSelectedScenario('custom');
      } else if (backtest.config.scenarioName) {
              setSelectedScenario(backtest.config.scenarioName);
      setShowCustomScenario(false);
      }
      
      setValue('timeframe', backtest.config.timeframe);
      setValue('cooldownPeriod', backtest.config.cooldownPeriod);
      setValue('maxLossStreak', backtest.config.maxLossStreak);
      setValue('maxPositionTimeHours', backtest.config.maxPositionTimeHours);
      setValue('flipOnlyWhenInProfit', backtest.config.flipOnlyWhenInProfit || false);
      setValue('closeEarlyWhenProfitable', backtest.config.closeEarlyWhenProfitable || false);
      setValue('balance', 1000); // Default for bots
      setValue('isForWatchingOnly', false);
      setValue('useSynthApi', backtest.config.useSynthApi || false);
      setValue('useForPositionSizing', backtest.config.useForPositionSizing ?? true);
      setValue('useForSignalFiltering', backtest.config.useForSignalFiltering ?? true);
      setValue('useForDynamicStopLoss', backtest.config.useForDynamicStopLoss ?? true);
      
      // Use backtest's money management as custom
      if (backtest.config.moneyManagement) {
        setShowCustomMoneyManagement(true);
        setCustomMoneyManagement(backtest.config.moneyManagement);
        
        // Convert decimal values to percentages for UI display
        const formattedMoneyManagement = {
          ...backtest.config.moneyManagement,
          stopLoss: backtest.config.moneyManagement.stopLoss * 100,
          takeProfit: backtest.config.moneyManagement.takeProfit * 100,
        };
        setGlobalCustomMoneyManagement(formattedMoneyManagement);
      }
    } else if (mode === 'backtest' && backtest) {
      // Initialize from existing backtest for re-running
      setValue('accountName', backtest.config.accountName);
      setValue('scenarioName', backtest.config.scenarioName || '');
      
      // Handle custom scenario from backtest
      if ((backtest.config as any).scenario) {
        setShowCustomScenario(true);
        setCustomScenario((backtest.config as any).scenario);
        setGlobalCustomScenario((backtest.config as any).scenario); // Also update global store for prefilling
        setSelectedScenario('custom');
      } else if (backtest.config.scenarioName) {
        setSelectedScenario(backtest.config.scenarioName);
        setShowCustomScenario(false);
      }
      
      setValue('timeframe', backtest.config.timeframe);
      setValue('cooldownPeriod', backtest.config.cooldownPeriod);
      setValue('maxLossStreak', backtest.config.maxLossStreak);
      setValue('maxPositionTimeHours', backtest.config.maxPositionTimeHours);
      setValue('flipOnlyWhenInProfit', backtest.config.flipOnlyWhenInProfit || false);
      setValue('closeEarlyWhenProfitable', backtest.config.closeEarlyWhenProfitable || false);
      setValue('balance', backtest.config.botTradingBalance || 10000);
      setValue('save', false); // Default to not saving for re-runs
      setValue('useSynthApi', backtest.config.useSynthApi || false);
      setValue('useForPositionSizing', backtest.config.useForPositionSizing ?? true);
      setValue('useForSignalFiltering', backtest.config.useForSignalFiltering ?? true);
      setValue('useForDynamicStopLoss', backtest.config.useForDynamicStopLoss ?? true);
      
      // Set tickers for backtest (array)
      if (backtest.config.ticker) {
        setValue('tickers', [backtest.config.ticker]);
      }
      
      // Set dates from backtest
      if (backtest.startDate) {
        const backtestStartDate = new Date(backtest.startDate).toISOString().split('T')[0];
        setStartDate(backtestStartDate);
        setValue('startDate', backtestStartDate);
      }
      if (backtest.endDate) {
        const backtestEndDate = new Date(backtest.endDate).toISOString().split('T')[0];
        setEndDate(backtestEndDate);
        setValue('endDate', backtestEndDate);
      }
      
      // Use backtest's money management as custom
      if (backtest.config.moneyManagement) {
        setShowCustomMoneyManagement(true);
        setCustomMoneyManagement(backtest.config.moneyManagement);
        
        // Convert decimal values to percentages for UI display
        const formattedMoneyManagement = {
          ...backtest.config.moneyManagement,
          stopLoss: backtest.config.moneyManagement.stopLoss * 100,
          takeProfit: backtest.config.moneyManagement.takeProfit * 100,
        };
        setGlobalCustomMoneyManagement(formattedMoneyManagement);
      }
      
      // Handle risk management
      if (backtest.config.riskManagement) {
        setValue('useCustomRiskManagement', true);
        setValue('riskManagement', backtest.config.riskManagement);
      }
    } else if (mode === 'updateBot' && existingBot) {
      // Initialize from existing bot
      const config = existingBot.config;
      setValue('name', config.name);
      setValue('accountName', config.accountName);
      // For bots, store ticker in state
      if (config.ticker) {
        setSelectedTicker(config.ticker);
      }
      setValue('scenarioName', config.scenarioName || '');
      setValue('timeframe', config.timeframe);
      setValue('cooldownPeriod', config.cooldownPeriod);
      setValue('maxLossStreak', config.maxLossStreak);
      setValue('maxPositionTimeHours', config.maxPositionTimeHours);
      setValue('flipOnlyWhenInProfit', config.flipOnlyWhenInProfit);
      setValue('closeEarlyWhenProfitable', config.closeEarlyWhenProfitable || false);
      setValue('balance', config.botTradingBalance);
      setValue('isForWatchingOnly', config.isForWatchingOnly);
      setValue('useSynthApi', config.useSynthApi || false);
      setValue('useForPositionSizing', config.useForPositionSizing ?? true);
      setValue('useForSignalFiltering', config.useForSignalFiltering ?? true);
      setValue('useForDynamicStopLoss', config.useForDynamicStopLoss ?? true);
      
      // Handle money management - if it exists, treat as custom for update mode
      if (config.moneyManagement) {
        setShowCustomMoneyManagement(true);
        setCustomMoneyManagement(config.moneyManagement);
        
        // Convert decimal values to percentages for UI display
        const formattedMoneyManagement = {
          ...config.moneyManagement,
          stopLoss: config.moneyManagement.stopLoss * 100,
          takeProfit: config.moneyManagement.takeProfit * 100,
        };
        setGlobalCustomMoneyManagement(formattedMoneyManagement);
        setSelectedMoneyManagement('custom'); // Set dropdown to show "custom"
      }
      
      // Handle scenario - check if we have scenario data or just a name reference
      if (config.scenario) {
        setShowCustomScenario(true);
        // Use LightScenario directly since CustomScenario now supports it
        setCustomScenario(config.scenario);
        setGlobalCustomScenario(config.scenario); // Also update global store for prefilling
        setSelectedScenario('custom'); // Set dropdown to show "custom"
      } else if (config.scenarioName) {
        setValue('scenarioName', config.scenarioName);
        setSelectedScenario(config.scenarioName);
        setShowCustomScenario(false);
      }
      
      // Handle risk management
      if (config.riskManagement) {
        setValue('useCustomRiskManagement', true);
        setValue('riskManagement', config.riskManagement);
      }
    }
  }, [mode, backtest, existingBot, setValue]);

  // Set defaults when data loads
  useEffect(() => {
    if (scenarios && scenarios.length > 0 && !getValues('scenarioName')) {
      setValue('scenarioName', scenarios[0].name || '');
    } else if (scenarios && scenarios.length === 0) {
      setShowCustomScenario(true);
    }
  }, [scenarios, setValue]);

  useEffect(() => {
    if (accounts && accounts.length > 0 && !getValues('accountName')) {
      setValue('accountName', accounts[0].name);
    }
  }, [accounts, setValue]);

  useEffect(() => {
    if (moneyManagements && moneyManagements.length > 0 && !selectedMoneyManagement) {
      setSelectedMoneyManagement(moneyManagements[0].name);
    } else if (moneyManagements && moneyManagements.length === 0) {
      setShowCustomMoneyManagement(true);
    }
  }, [moneyManagements]);

  // Handlers continue below...

  // Event handlers
  const handleSynthApiToggle = (enabled: boolean) => {
    setValue('useSynthApi', enabled);
    if (!enabled) {
      // Only reset to false when disabling Synth API
      setValue('useForPositionSizing', false);
      setValue('useForSignalFiltering', false);
      setValue('useForDynamicStopLoss', false);
    } else {
      // Set to true when enabling Synth API
      setValue('useForPositionSizing', true);
      setValue('useForSignalFiltering', true);
      setValue('useForDynamicStopLoss', true);
    }
  };

  const handleRiskToleranceChange = (tolerance: RiskToleranceLevel) => {
    const presetConfig = getPresetRiskManagement(tolerance);
    setValue('riskManagement', presetConfig);
  };

  const getPresetRiskManagement = (tolerance: RiskToleranceLevel): RiskManagement => {
    switch (tolerance) {
      case RiskToleranceLevel.Conservative:
        return {
          adverseProbabilityThreshold: 0.15,
          favorableProbabilityThreshold: 0.40,
          riskAversion: 2.0,
          kellyMinimumThreshold: 0.02,
          kellyMaximumCap: 0.15,
          maxLiquidationProbability: 0.08,
          signalValidationTimeHorizonHours: 24,
          positionMonitoringTimeHorizonHours: 6,
          positionWarningThreshold: 0.15,
          positionAutoCloseThreshold: 0.35,
          kellyFractionalMultiplier: 0.5,
          riskTolerance: tolerance,
          useExpectedUtility: true,
          useKellyCriterion: true,
        };
      case RiskToleranceLevel.Aggressive:
        return {
          adverseProbabilityThreshold: 0.30,
          favorableProbabilityThreshold: 0.25,
          riskAversion: 0.5,
          kellyMinimumThreshold: 0.005,
          kellyMaximumCap: 0.40,
          maxLiquidationProbability: 0.15,
          signalValidationTimeHorizonHours: 24,
          positionMonitoringTimeHorizonHours: 6,
          positionWarningThreshold: 0.30,
          positionAutoCloseThreshold: 0.70,
          kellyFractionalMultiplier: 1.0,
          riskTolerance: tolerance,
          useExpectedUtility: true,
          useKellyCriterion: true,
        };
      default: // Moderate
        return getDefaultRiskManagement();
    }
  };

  const handleImportJsonConfig = () => {
    try {
      setImportError('');
      const config = JSON.parse(jsonConfig);
      
      // Load the configuration into the form
      if (config.accountName) setValue('accountName', config.accountName);
      if (config.timeframe) setValue('timeframe', config.timeframe);
      if (config.cooldownPeriod !== undefined) setValue('cooldownPeriod', config.cooldownPeriod);
      if (config.maxLossStreak !== undefined) setValue('maxLossStreak', config.maxLossStreak);
      if (config.maxPositionTimeHours !== undefined) setValue('maxPositionTimeHours', config.maxPositionTimeHours);
      if (config.flipOnlyWhenInProfit !== undefined) setValue('flipOnlyWhenInProfit', config.flipOnlyWhenInProfit);
      if (config.closeEarlyWhenProfitable !== undefined) setValue('closeEarlyWhenProfitable', config.closeEarlyWhenProfitable);
      if (config.botTradingBalance !== undefined) setValue('balance', config.botTradingBalance);
      if (config.useSynthApi !== undefined) setValue('useSynthApi', config.useSynthApi);
      if (config.useForPositionSizing !== undefined) setValue('useForPositionSizing', config.useForPositionSizing);
      if (config.useForSignalFiltering !== undefined) setValue('useForSignalFiltering', config.useForSignalFiltering);
      if (config.useForDynamicStopLoss !== undefined) setValue('useForDynamicStopLoss', config.useForDynamicStopLoss);

      // For bot modes, set the ticker
      if (mode !== 'backtest' && config.ticker) {
        setSelectedTicker(config.ticker);
      }

      // For backtest mode, set tickers array
      if (mode === 'backtest' && config.ticker) {
        setValue('tickers', [config.ticker]);
      }

      // Handle scenario
      if (config.scenario) {
        setShowCustomScenario(true);
        setCustomScenario(config.scenario);
        setGlobalCustomScenario(config.scenario);
        setSelectedScenario('custom');
      } else if (config.scenarioName) {
        setSelectedScenario(config.scenarioName);
        setValue('scenarioName', config.scenarioName);
        setShowCustomScenario(false);
      }

      // Handle money management
      if (config.moneyManagement) {
        setShowCustomMoneyManagement(true);
        setCustomMoneyManagement(config.moneyManagement);
        
        // Convert decimal values to percentages for UI display
        const formattedMoneyManagement = {
          ...config.moneyManagement,
          stopLoss: config.moneyManagement.stopLoss * 100,
          takeProfit: config.moneyManagement.takeProfit * 100,
        };
        setGlobalCustomMoneyManagement(formattedMoneyManagement);
        setSelectedMoneyManagement('custom');
      }

      // Handle risk management
      if (config.riskManagement) {
        setValue('useCustomRiskManagement', true);
        setValue('riskManagement', config.riskManagement);
      }

      // Bot-specific fields
      if (mode !== 'backtest') {
        if (config.name) setValue('name', config.name);
        if (config.isForWatchingOnly !== undefined) setValue('isForWatchingOnly', config.isForWatchingOnly);
        if (config.flipPosition !== undefined) setValue('flipPosition', config.flipPosition);
      }

      new Toast('Configuration imported successfully!', false);
      setShowJsonImport(false);
      setJsonConfig('');
    } catch (error) {
      setImportError('Invalid JSON format. Please check your configuration.');
      console.error('JSON import error:', error);
    }
  };

  const onMoneyManagementChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    if (e.target.value === 'custom') {
      setShowCustomMoneyManagement(true);
      setSelectedMoneyManagement('custom'); // Set selected to 'custom'
      setCustomMoneyManagement(undefined);
      setGlobalCustomMoneyManagement(null); // Clear global store when creating new custom
    } else {
      setShowCustomMoneyManagement(false);
      setSelectedMoneyManagement(e.target.value); // Update selected money management
      setCustomMoneyManagement(undefined);
      setGlobalCustomMoneyManagement(null); // Clear global store when switching away from custom
    }
  };

  const onScenarioChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    if (e.target.value === 'custom') {
      setShowCustomScenario(true);
      setCustomScenario(undefined);
      setGlobalCustomScenario(null); // Clear global store when creating new custom
    } else {
      setShowCustomScenario(false);
      setCustomScenario(undefined);
      setGlobalCustomScenario(null); // Clear global store when switching away from custom
      setSelectedScenario(e.target.value);
      setValue('scenarioName', e.target.value);
    }
  };

  // Main form submission handler
  const onSubmit: SubmitHandler<IUnifiedTradingConfigInput> = async (form) => {
    if (mode === 'backtest') {
      await handleBacktestSubmission(form);
    } else {
      await handleBotSubmission(form);
    }
  };

  // Helper function to convert custom scenario to ScenarioRequest format
  const convertScenarioToRequest = (scenario: LightScenario): ScenarioRequest => {
    return {
      name: scenario.name || 'Custom Scenario',
      loopbackPeriod: scenario.loopbackPeriod || null,
      indicators: scenario.indicators?.map(indicator => ({
        name: indicator.name || '',
        type: indicator.type!,
        signalType: indicator.signalType || SignalType.Signal, // Default to Signal if not set
        minimumHistory: indicator.minimumHistory || 0,
        period: indicator.period,
        fastPeriods: indicator.fastPeriods,
        slowPeriods: indicator.slowPeriods,
        signalPeriods: indicator.signalPeriods,
        multiplier: indicator.multiplier,
        smoothPeriods: indicator.smoothPeriods,
        stochPeriods: indicator.stochPeriods,
        cyclePeriods: indicator.cyclePeriods,
      })).filter(indicator => indicator.type) || [] // Only filter out indicators without type
    };
  };

  // Backtest submission handler
  const handleBacktestSubmission = async (form: IUnifiedTradingConfigInput) => {
    if (!form.scenarioName && !customScenario) {
      new Toast('Please select a scenario or create a custom scenario', false);
      return;
    }

    if (customScenario && (!customScenario.indicators || customScenario.indicators.length === 0)) {
      new Toast('Custom scenario must have at least one indicator', false);
      return;
    }

    if (!form.tickers || form.tickers.length === 0) {
      new Toast('Please select at least one ticker', false);
      return;
    }

    // Process tickers sequentially
    for (const ticker of form.tickers) {
      try {
        await runBacktest(form, ticker, 0);
      } catch (error) {
        console.error(`Error running backtest for ${ticker}:`, error);
        continue;
      }
    }
  };

  // Unified bot submission handler
  const handleBotSubmission = async (form: IUnifiedTradingConfigInput, saveOnly: boolean = false) => {
    const t = new Toast(
      mode === 'createBot' 
        ? (saveOnly ? 'Saving bot configuration...' : 'Creating bot...')
        : 'Updating bot...'
    );
    
    try {
      // Create money management object
      let moneyManagement: MoneyManagement | undefined = undefined;
      
      if (showCustomMoneyManagement || (mode === 'createBot' && backtest)) {
        moneyManagement = customMoneyManagement;
      } else {
        const selectedMM = moneyManagements?.find(mm => mm.name === selectedMoneyManagement);
        if (selectedMM) {
          moneyManagement = selectedMM;
        }
      }

      console.log(form)
      console.log(customMoneyManagement)
      if (!moneyManagement) {
        t.update('error', 'Money management is required');
        return;
      }

      // Create TradingBotConfigRequest
      const tradingBotConfigRequest: TradingBotConfigRequest = {
        accountName: form.accountName,
        ticker: selectedTicker!, // Use selected ticker for bots
        scenario: customScenario ? convertScenarioToRequest(customScenario) : undefined,
        scenarioName: customScenario ? undefined : form.scenarioName,
        timeframe: form.timeframe,
        isForWatchingOnly: form.isForWatchingOnly || false,
        flipPosition: form.flipPosition || false,
        cooldownPeriod: form.cooldownPeriod,
        maxLossStreak: form.maxLossStreak,
        maxPositionTimeHours: form.maxPositionTimeHours,
        flipOnlyWhenInProfit: form.flipOnlyWhenInProfit ?? true,
        name: form.name || 'Unnamed Bot',
        botTradingBalance: form.balance,
        closeEarlyWhenProfitable: form.closeEarlyWhenProfitable ?? false,
        useSynthApi: form.useSynthApi ?? false,
        useForPositionSizing: form.useForPositionSizing ?? true,
        useForSignalFiltering: form.useForSignalFiltering ?? true,
        useForDynamicStopLoss: form.useForDynamicStopLoss ?? true,
        moneyManagementName: showCustomMoneyManagement ? undefined : selectedMoneyManagement,
        moneyManagement: moneyManagement,
      };

      if (mode === 'createBot') {
        const request: StartBotRequest = {
          config: tradingBotConfigRequest,
        };
        
        if (saveOnly) {
          await botClient.bot_Save(request);
          t.update('success', 'Bot configuration saved successfully!');
        } else {
          await botClient.bot_Start(request);
          t.update('success', 'Bot created successfully!');
        }
      } else {
        const request: UpdateBotConfigRequest = {
          identifier: existingBot!.identifier,
          config: tradingBotConfigRequest,
          moneyManagementName: showCustomMoneyManagement ? undefined : selectedMoneyManagement,
        };
        await botClient.bot_UpdateBotConfig(request);
        t.update('success', 'Bot updated successfully!');
      }

      closeModal();
    } catch (error: any) {
      console.error(error);
      t.update('error', `Error: ${error.message || error}`);
    }
  };

  // Run backtest function
  async function runBacktest(form: IUnifiedTradingConfigInput, ticker: string, loopCount: number): Promise<void> {
    const t = new Toast(`${ticker} is running`);
    
    try {
      const tradingBotConfigRequest: TradingBotConfigRequest = {
        accountName: form.accountName,
        ticker: ticker as any,
        scenario: customScenario ? convertScenarioToRequest(customScenario) : undefined,
        scenarioName: customScenario ? undefined : form.scenarioName,
        timeframe: form.timeframe,
        isForWatchingOnly: false,
        cooldownPeriod: form.cooldownPeriod,
        maxLossStreak: form.maxLossStreak,
        maxPositionTimeHours: form.maxPositionTimeHours,
        flipOnlyWhenInProfit: form.flipOnlyWhenInProfit ?? true,
        name: `Backtest-${customScenario ? customScenario.name : form.scenarioName}-${ticker}-${new Date().toISOString()}`,
        botTradingBalance: form.balance,
        closeEarlyWhenProfitable: form.closeEarlyWhenProfitable ?? false,
        useSynthApi: form.useSynthApi ?? false,
        useForPositionSizing: form.useForPositionSizing ?? true,
        useForSignalFiltering: form.useForSignalFiltering ?? true,
        useForDynamicStopLoss: form.useForDynamicStopLoss ?? true,
        moneyManagementName: showCustomMoneyManagement ? undefined : selectedMoneyManagement,
        moneyManagement: customMoneyManagement,
        flipPosition: form.flipPosition || false,
      };

      const request: RunBacktestRequest = {
        config: tradingBotConfigRequest,
        startDate: new Date(form.startDate),
        endDate: new Date(form.endDate),
        save: form.save || false,
      };

      const backtest = await backtestClient.backtest_Run(request);
      
      t.update('success', `${ticker} Backtest Succeeded`);
      addBacktest(backtest as unknown as LightBacktestResponse);
      
      // Call the callback to notify parent component that backtest is completed
      if (onBacktestComplete) {
        onBacktestComplete();
      }


    } catch (err: any) {
      t.update('error', 'Error: ' + err);
      throw err;
    }
  }

  if (!accounts || !scenarios || !moneyManagements) {
    return <Loader />;
  }

  return (
    <Modal
      showModal={showModal}
      onSubmit={handleSubmit(onSubmit)}
      onClose={closeModal}
      titleHeader={
        mode === 'backtest' 
          ? 'Run Backtest' 
          : mode === 'createBot' 
            ? `Create Bot${backtest ? ' from Backtest' : ''}` 
            : 'Update Bot Configuration'
      }
    >
      <div className="space-y-4">
        {/* Bot Name (for bot modes only) */}
        {mode !== 'backtest' && (
          <FormInput label="Bot Name" htmlFor="name">
            <input
              type="text"
              className="input input-bordered w-full"
              {...register('name', { required: mode === 'createBot' || mode === 'updateBot' })}
            />
          </FormInput>
        )}

        {/* JSON Import Section */}
        <div className="divider">
          <button
            type="button"
            className="btn btn-outline btn-sm normal-case"
            onClick={() => setShowJsonImport(!showJsonImport)}
          >
            <svg 
              className="w-4 h-4 mr-2" 
              fill="none" 
              stroke="currentColor" 
              viewBox="0 0 24 24"
            >
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M9 19l3 3m0 0l3-3m-3 3V10" />
            </svg>
            Import Configuration from JSON
            <svg 
              className={`w-4 h-4 ml-2 transition-transform duration-200 ${showJsonImport ? 'rotate-180' : ''}`} 
              fill="none" 
              stroke="currentColor" 
              viewBox="0 0 24 24"
            >
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
            </svg>
          </button>
        </div>

        {showJsonImport && (
          <div className="space-y-4 border border-accent rounded-lg p-4 bg-base-100">
            <div className="space-y-2">
              <label className="label">
                <span className="label-text">Paste Configuration JSON</span>
              </label>
              <textarea
                className="textarea textarea-bordered w-full h-32"
                placeholder='Paste your configuration JSON here...'
                value={jsonConfig}
                onChange={(e) => setJsonConfig(e.target.value)}
              />
              {importError && (
                <div className="alert alert-error">
                  <svg className="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  <span>{importError}</span>
                </div>
              )}
            </div>
            <div className="flex gap-2">
              <button
                type="button"
                className="btn btn-primary btn-sm"
                onClick={handleImportJsonConfig}
                disabled={!jsonConfig.trim()}
              >
                Import Configuration
              </button>
              <button
                type="button"
                className="btn btn-ghost btn-sm"
                onClick={() => {
                  setJsonConfig('');
                  setImportError('');
                  setShowJsonImport(false);
                }}
              >
                Cancel
              </button>
            </div>
            <div className="text-sm text-base-content/70">
              <p>Copy a configuration from the backtest table and paste it here to quickly load all settings.</p>
            </div>
          </div>
        )}

        {/* First Row: Account & Timeframe */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <FormInput label="Account" htmlFor="accountName">
            <select
              className="select select-bordered w-full"
              {...register('accountName', { required: true })}
            >
              <option value="" disabled>
                Select an account
              </option>
              {accounts.map((item) => (
                <option key={item.name} value={item.name}>
                  {item.name}
                </option>
              ))}
            </select>
          </FormInput>

          <FormInput label="Timeframe" htmlFor="timeframe">
            <select
              className="select select-bordered w-full"
              {...register('timeframe', { required: true })}
              onChange={(e) => {
                setValue('timeframe', e.target.value as any);
                if (mode === 'backtest') {
                  refetchTickers();
                }
              }}
            >
              {Object.keys(Timeframe).map((item) => (
                <option key={item} value={item}>
                  {item}
                </option>
              ))}
            </select>
          </FormInput>
        </div>

        {/* Money Management */}
        <FormInput label="Money Management" htmlFor="moneyManagement">
          <select
            className="select select-bordered w-full"
            value={selectedMoneyManagement || (showCustomMoneyManagement ? 'custom' : '')}
            onChange={onMoneyManagementChange}
          >
            {moneyManagements.length === 0 ? (
              <option value="" disabled>No money management available - create a custom one below</option>
            ) : (
              <>
                {moneyManagements.map((item) => (
                  <option key={item.name} value={item.name}>
                    {item.name} - SL: {(item.stopLoss * 100).toFixed(3)} - TP: {(item.takeProfit * 100).toFixed(3)} - x: {item.leverage}
                  </option>
                ))}
              </>
            )}
            <option key="custom" value="custom">
              {moneyManagements.length === 0 ? 'Create Custom Money Management' : 'Custom'}
            </option>
          </select>
        </FormInput>

        {/* Custom Money Management */}
        {showCustomMoneyManagement && (
          <div className="mt-6">
            <CustomMoneyManagement
              onCreateMoneyManagement={setCustomMoneyManagement}
              timeframe={selectedTimeframe || Timeframe.FiveMinutes}
              showCustomMoneyManagement={showCustomMoneyManagement}
            />
          </div>
        )}

        {/* Scenario Selection */}
        <FormInput label="Scenario" htmlFor="scenarioName">
          <select
            className="select select-bordered w-full"
            {...register('scenarioName')}
            value={selectedScenario || (showCustomScenario ? 'custom' : '')}
            onChange={onScenarioChange}
          >
            {scenarios.length === 0 ? (
              <option value="" disabled>No scenarios available - create a custom one below</option>
            ) : (
              <option value="" disabled>Select a scenario</option>
            )}
            {scenarios.map((item) => (
              <option key={item.name || 'unnamed'} value={item.name || ''}>
                {item.name || 'Unnamed Scenario'}
              </option>
            ))}
            <option key="custom" value="custom">
              {scenarios.length === 0 ? 'Create Custom Scenario' : 'Custom'}
            </option>
          </select>
        </FormInput>

        {/* Custom Scenario */}
        {showCustomScenario && (
          <div className="mt-6">
            <CustomScenario
              onCreateScenario={setCustomScenario}
              showCustomScenario={showCustomScenario}
            />
          </div>
        )}

        {/* Ticker Selection - Multiple for backtests, Single for bots */}
        {mode === 'backtest' ? (
          <FormInput label="Tickers" htmlFor="tickers">
            <select
              className="select select-bordered w-full"
              multiple
              {...register('tickers')}
            >
              {tickers?.map((item) => (
                <option key={item.ticker} value={item.ticker}>
                  {item.ticker}
                </option>
              ))}
            </select>
          </FormInput>
        ) : (
          <FormInput label="Ticker" htmlFor="ticker">
            <select
              className="select select-bordered w-full"
              value={selectedTicker || ''}
              onChange={(e) => setSelectedTicker(e.target.value as Ticker)}
              required
            >
              <option value="" disabled>Select a ticker</option>
              {Object.values(Ticker).map((ticker) => (
                <option key={ticker} value={ticker}>
                  {ticker}
                </option>
              ))}
            </select>
          </FormInput>
        )}

        {/* Trading Balance */}
        <FormInput label={mode === 'backtest' ? 'Balance' : 'Trading Balance'} htmlFor="balance">
          <input
            type="number"
            className="input input-bordered w-full"
            {...register('balance', { valueAsNumber: true, required: true })}
            min="1"
            step="0.01"
          />
        </FormInput>

        {/* Watch Only Mode (bot modes only) */}
        {mode !== 'backtest' && (
          <FormInput 
            label={
              <div className="flex items-center gap-2">
                <span className="label-text">Watch Only Mode</span>
                <div className="tooltip tooltip-top" data-tip="Bot will analyze and generate signals but won't execute actual trades. Good for testing strategies">
                  <span className="badge badge-info badge-xs">i</span>
                </div>
              </div>
            } 
            htmlFor="isForWatchingOnly"
          >
            <input
              type="checkbox"
              className="toggle toggle-primary"
              {...register('isForWatchingOnly')}
            />
          </FormInput>
        )}

        {/* Continue with Advanced Parameters section... */}

        {/* Advanced Parameters Dropdown */}
        <div className="divider">
          <button
            type="button"
            className="btn btn-outline btn-sm normal-case"
            onClick={() => setShowAdvancedParams(!showAdvancedParams)}
          >
            <svg 
              className="w-4 h-4 mr-2" 
              fill="none" 
              stroke="currentColor" 
              viewBox="0 0 24 24"
            >
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
            </svg>
            Advanced Parameters
            <svg 
              className={`w-4 h-4 ml-2 transition-transform duration-200 ${showAdvancedParams ? 'rotate-180' : ''}`} 
              fill="none" 
              stroke="currentColor" 
              viewBox="0 0 24 24"
            >
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
            </svg>
          </button>
        </div>

        {showAdvancedParams && (
          <div className="space-y-4 border border-primary rounded-lg p-4 bg-base-100">
            {/* Cooldown Period */}
            <div className="grid grid-cols-1 gap-4">
              <FormInput 
                label={
                  <div className="flex items-center gap-2">
                    Cooldown Period (candles)
                    <div className="tooltip tooltip-top" data-tip="Number of candles to wait before allowing another trade after closing a position. Prevents overtrading and allows market to settle">
                      <span className="badge badge-info badge-xs">i</span>
                    </div>
                  </div>
                } 
                htmlFor="cooldownPeriod"
              >
                <input
                  type="number"
                  className="input input-bordered w-full"
                  min="1"
                  step="1"
                  {...register('cooldownPeriod', { valueAsNumber: true })}
                />
              </FormInput>
            </div>

            {/* Dates for backtests */}
            {mode === 'backtest' && (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <FormInput label="Start Date" htmlFor="startDate">
                  <input
                    type="date"
                    className="input input-bordered w-full"
                    value={startDate}
                    onChange={(e) => {
                      setStartDate(e.target.value);
                      setValue('startDate', e.target.value);
                    }}
                  />
                </FormInput>

                <FormInput label="End Date" htmlFor="endDate">
                  <input
                    type="date"
                    className="input input-bordered w-full"
                    value={endDate}
                    onChange={(e) => {
                      setEndDate(e.target.value);
                      setValue('endDate', e.target.value);
                    }}
                  />
                </FormInput>
              </div>
            )}



            {/* Max Loss Streak & Max Position Time */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <FormInput 
                label={
                  <div className="flex items-center gap-2">
                    Max Loss Streak
                    <div className="tooltip tooltip-top" data-tip="Maximum number of consecutive losing trades before stopping the bot. Set to 0 for no limit">
                      <span className="badge badge-info badge-xs">i</span>
                    </div>
                  </div>
                } 
                htmlFor="maxLossStreak"
              >
                <input
                  type="number"
                  className="input input-bordered w-full"
                  min="0"
                  step="1"
                  {...register('maxLossStreak', { valueAsNumber: true })}
                />
              </FormInput>

              <FormInput 
                label={
                  <div className="flex items-center gap-2">
                    Max Position Time (hours)
                    <div className="tooltip tooltip-top" data-tip="Maximum time to hold a position before force closing. Leave empty to disable time-based position closure">
                      <span className="badge badge-info badge-xs">i</span>
                    </div>
                  </div>
                } 
                htmlFor="maxPositionTimeHours"
              >
                <input
                  type="number"
                  className="input input-bordered w-full"
                  min="0"
                  step="0.5"
                  placeholder="Leave empty to disable"
                  {...register('maxPositionTimeHours', { valueAsNumber: true })}
                />
              </FormInput>
            </div>

            {/* Trading Options */}
            <FormInput 
                label={
                  <div className="flex items-center gap-2">
                    Enable Position Flipping
                    <div className="tooltip tooltip-top" data-tip="Allow the bot to flip between long and short positions based on signals. More aggressive trading strategy">
                      <span className="badge badge-info badge-xs">i</span>
                    </div>
                  </div>
                } 
                htmlFor="flipPosition"
              >
                <input
                  type="checkbox"
                  className="toggle toggle-primary"
                  {...register('flipPosition')}
                />
              </FormInput>


            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <FormInput 
                label={
                  <div className="flex items-center gap-2">
                    Flip Only When In Profit
                    <div className="tooltip tooltip-top" data-tip="If enabled, positions will only flip when current position is profitable. Helps avoid flipping during losing streaks">
                      <span className="badge badge-info badge-xs">i</span>
                    </div>
                  </div>
                } 
                htmlFor="flipOnlyWhenInProfit"
              >
                <input
                  type="checkbox"
                  className="toggle toggle-primary"
                  {...register('flipOnlyWhenInProfit')}
                />
              </FormInput>

              <FormInput 
                label={
                  <div className="flex items-center gap-2">
                    Close Early When Profitable
                    <div className="tooltip tooltip-top" data-tip="If enabled, positions will close early when they become profitable. Conservative approach to lock in gains">
                      <span className="badge badge-info badge-xs">i</span>
                    </div>
                  </div>
                } 
                htmlFor="closeEarlyWhenProfitable"
              >
                <input
                  type="checkbox"
                  className="toggle toggle-primary"
                  {...register('closeEarlyWhenProfitable')}
                />
              </FormInput>
            </div>

             
            {/* Save Option (backtest mode only) */}
            {mode === 'backtest' && (
              <FormInput 
                label={
                  <div className="flex items-center gap-2">
                    Save Backtest Results
                    <div className="tooltip tooltip-top" data-tip="Save the backtest results to your account for future reference and analysis">
                      <span className="badge badge-info badge-xs">i</span>
                    </div>
                  </div>
                } 
                htmlFor="save"
              >
                <input
                  type="checkbox"
                  className="toggle toggle-primary"
                  {...register('save')}
                />
              </FormInput>
            )}

            {/* Synth API Section */}
            <div className="divider">Synth API Configuration</div>
            
            <div className="grid grid-cols-1 gap-4">
              <FormInput 
                label={
                  <div className="flex items-center gap-2">
                    Enable Synth API
                    <div className="tooltip tooltip-top" data-tip="Enable AI-powered probabilistic price forecasts and risk assessment using advanced machine learning models for enhanced trading decisions">
                      <span className="badge badge-info badge-xs">i</span>
                    </div>
                  </div>
                } 
                htmlFor="useSynthApi"
              >
                <input
                  type="checkbox"
                  className="toggle toggle-primary"
                  {...register('useSynthApi')}
                  onChange={(e) => handleSynthApiToggle(e.target.checked)}
                />
              </FormInput>
            </div>

            {/* Show sub-options only when Synth API is enabled */}
            {useSynthApi && (
              <div className="grid grid-cols-1 gap-4">
                <FormInput 
                  label={
                    <div className="flex items-center gap-2">
                      Use for Position Sizing
                      <div className="tooltip tooltip-top" data-tip="Use Synth predictions for position sizing adjustments and risk assessment. Optimizes trade size based on confidence levels">
                        <span className="badge badge-info badge-xs">i</span>
                      </div>
                    </div>
                  } 
                  htmlFor="useForPositionSizing"
                >
                  <input
                    type="checkbox"
                    className="toggle toggle-primary"
                    {...register('useForPositionSizing')}
                  />
                </FormInput>

                <FormInput 
                  label={
                    <div className="flex items-center gap-2">
                      Use for Signal Filtering
                      <div className="tooltip tooltip-top" data-tip="Use Synth predictions to filter trading signals. Only executes trades when AI confidence is high">
                        <span className="badge badge-info badge-xs">i</span>
                      </div>
                    </div>
                  } 
                  htmlFor="useForSignalFiltering"
                >
                  <input
                    type="checkbox"
                    className="toggle toggle-primary"
                    {...register('useForSignalFiltering')}
                  />
                </FormInput>

                <FormInput 
                  label={
                    <div className="flex items-center gap-2">
                      Use for Dynamic Stop Loss
                      <div className="tooltip tooltip-top" data-tip="Use Synth predictions for dynamic stop-loss/take-profit adjustments. Adapts levels based on market conditions">
                        <span className="badge badge-info badge-xs">i</span>
                      </div>
                    </div>
                  } 
                  htmlFor="useForDynamicStopLoss"
                >
                  <input
                    type="checkbox"
                    className="toggle toggle-primary"
                    {...register('useForDynamicStopLoss')}
                  />
                </FormInput>
              </div>
            )}
          </div>
        )}

        {/* Risk Management Section */}
        <div className="divider">
          <button
            type="button"
            className="btn btn-outline btn-sm normal-case"
            onClick={() => setShowRiskManagement(!showRiskManagement)}
          >
            <svg 
              className="w-4 h-4 mr-2" 
              fill="none" 
              stroke="currentColor" 
              viewBox="0 0 24 24"
            >
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
            </svg>
            Risk Management Configuration
            <svg 
              className={`w-4 h-4 ml-2 transition-transform duration-200 ${showRiskManagement ? 'rotate-180' : ''}`} 
              fill="none" 
              stroke="currentColor" 
              viewBox="0 0 24 24"
            >
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
            </svg>
          </button>
        </div>

        {showRiskManagement && (
          <div className="space-y-4 border border-secondary rounded-lg p-4 bg-base-100">
            <FormInput 
              label={
                <div className="flex items-center gap-2">
                  Use Custom Risk Management
                  <div className="tooltip tooltip-top" data-tip="Enable custom risk management parameters for advanced probabilistic analysis and Kelly Criterion calculations">
                    <span className="badge badge-secondary badge-xs">i</span>
                  </div>
                </div>
              } 
              htmlFor="useCustomRiskManagement"
            >
              <input
                type="checkbox"
                className="toggle toggle-secondary"
                {...register('useCustomRiskManagement')}
              />
            </FormInput>

            {useCustomRiskManagement && (
              <div className="space-y-4">
                {/* Risk Tolerance Level */}
                <FormInput label="Risk Tolerance Level" htmlFor="riskTolerance">
                  <select
                    className="select select-bordered w-full"
                    value={watch('riskManagement')?.riskTolerance || RiskToleranceLevel.Moderate}
                    onChange={(e) => handleRiskToleranceChange(e.target.value as RiskToleranceLevel)}
                  >
                    {Object.values(RiskToleranceLevel).map((level) => (
                      <option key={level} value={level}>
                        {level}
                      </option>
                    ))}
                  </select>
                </FormInput>

                {/* Risk Management Parameters Grid */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <FormInput 
                    label={
                      <div className="flex items-center gap-2">
                        Adverse Probability Threshold
                        <div className="tooltip tooltip-top" data-tip="Threshold for adverse probability in signal validation (5%-50%)">
                          <span className="badge badge-secondary badge-xs">i</span>
                        </div>
                      </div>
                    } 
                    htmlFor="adverseProbabilityThreshold"
                  >
                    <input
                      type="number"
                      className="input input-bordered w-full"
                      min="0.05"
                      max="0.50"
                      step="0.01"
                      value={watch('riskManagement')?.adverseProbabilityThreshold || 0.20}
                      onChange={(e) => {
                        const currentRM = getValues('riskManagement') || getDefaultRiskManagement();
                        setValue('riskManagement', {
                          ...currentRM,
                          adverseProbabilityThreshold: parseFloat(e.target.value)
                        });
                      }}
                    />
                  </FormInput>

                  <FormInput 
                    label={
                      <div className="flex items-center gap-2">
                        Favorable Probability Threshold
                        <div className="tooltip tooltip-top" data-tip="Threshold for favorable probability in signal validation (10%-70%)">
                          <span className="badge badge-secondary badge-xs">i</span>
                        </div>
                      </div>
                    } 
                    htmlFor="favorableProbabilityThreshold"
                  >
                    <input
                      type="number"
                      className="input input-bordered w-full"
                      min="0.10"
                      max="0.70"
                      step="0.01"
                      value={watch('riskManagement')?.favorableProbabilityThreshold || 0.30}
                      onChange={(e) => {
                        const currentRM = getValues('riskManagement') || getDefaultRiskManagement();
                        setValue('riskManagement', {
                          ...currentRM,
                          favorableProbabilityThreshold: parseFloat(e.target.value)
                        });
                      }}
                    />
                  </FormInput>

                  <FormInput 
                    label={
                      <div className="flex items-center gap-2">
                        Risk Aversion Parameter
                        <div className="tooltip tooltip-top" data-tip="Risk aversion parameter for Expected Utility calculations (0.1-5.0)">
                          <span className="badge badge-secondary badge-xs">i</span>
                        </div>
                      </div>
                    } 
                    htmlFor="riskAversion"
                  >
                    <input
                      type="number"
                      className="input input-bordered w-full"
                      min="0.1"
                      max="5.0"
                      step="0.1"
                      value={watch('riskManagement')?.riskAversion || 1.0}
                      onChange={(e) => {
                        const currentRM = getValues('riskManagement') || getDefaultRiskManagement();
                        setValue('riskManagement', {
                          ...currentRM,
                          riskAversion: parseFloat(e.target.value)
                        });
                      }}
                    />
                  </FormInput>

                  <FormInput 
                    label={
                      <div className="flex items-center gap-2">
                        Kelly Minimum Threshold
                        <div className="tooltip tooltip-top" data-tip="Minimum Kelly Criterion fraction to consider a trade favorable (0.5%-10%)">
                          <span className="badge badge-secondary badge-xs">i</span>
                        </div>
                      </div>
                    } 
                    htmlFor="kellyMinimumThreshold"
                  >
                    <input
                      type="number"
                      className="input input-bordered w-full"
                      min="0.005"
                      max="0.10"
                      step="0.005"
                      value={watch('riskManagement')?.kellyMinimumThreshold || 0.01}
                      onChange={(e) => {
                        const currentRM = getValues('riskManagement') || getDefaultRiskManagement();
                        setValue('riskManagement', {
                          ...currentRM,
                          kellyMinimumThreshold: parseFloat(e.target.value)
                        });
                      }}
                    />
                  </FormInput>

                  <FormInput 
                    label={
                      <div className="flex items-center gap-2">
                        Kelly Maximum Cap
                        <div className="tooltip tooltip-top" data-tip="Maximum Kelly Criterion fraction cap for practical risk management (5%-50%)">
                          <span className="badge badge-secondary badge-xs">i</span>
                        </div>
                      </div>
                    } 
                    htmlFor="kellyMaximumCap"
                  >
                    <input
                      type="number"
                      className="input input-bordered w-full"
                      min="0.05"
                      max="0.50"
                      step="0.01"
                      value={watch('riskManagement')?.kellyMaximumCap || 0.25}
                      onChange={(e) => {
                        const currentRM = getValues('riskManagement') || getDefaultRiskManagement();
                        setValue('riskManagement', {
                          ...currentRM,
                          kellyMaximumCap: parseFloat(e.target.value)
                        });
                      }}
                    />
                  </FormInput>

                  <FormInput 
                    label={
                      <div className="flex items-center gap-2">
                        Max Liquidation Probability
                        <div className="tooltip tooltip-top" data-tip="Maximum acceptable liquidation probability for position risk assessment (5%-30%)">
                          <span className="badge badge-secondary badge-xs">i</span>
                        </div>
                      </div>
                    } 
                    htmlFor="maxLiquidationProbability"
                  >
                    <input
                      type="number"
                      className="input input-bordered w-full"
                      min="0.05"
                      max="0.30"
                      step="0.01"
                      value={watch('riskManagement')?.maxLiquidationProbability || 0.10}
                      onChange={(e) => {
                        const currentRM = getValues('riskManagement') || getDefaultRiskManagement();
                        setValue('riskManagement', {
                          ...currentRM,
                          maxLiquidationProbability: parseFloat(e.target.value)
                        });
                      }}
                    />
                  </FormInput>
                </div>

                {/* Checkboxes for Kelly and Expected Utility */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <FormInput 
                    label={
                      <div className="flex items-center gap-2">
                        Use Kelly Criterion
                        <div className="tooltip tooltip-top" data-tip="Enable Kelly Criterion for position sizing recommendations">
                          <span className="badge badge-secondary badge-xs">i</span>
                        </div>
                      </div>
                    } 
                    htmlFor="useKellyCriterion"
                  >
                    <input
                      type="checkbox"
                      className="toggle toggle-secondary"
                      checked={watch('riskManagement')?.useKellyCriterion || true}
                      onChange={(e) => {
                        const currentRM = getValues('riskManagement') || getDefaultRiskManagement();
                        setValue('riskManagement', {
                          ...currentRM,
                          useKellyCriterion: e.target.checked
                        });
                      }}
                    />
                  </FormInput>

                  <FormInput 
                    label={
                      <div className="flex items-center gap-2">
                        Use Expected Utility
                        <div className="tooltip tooltip-top" data-tip="Enable Expected Utility Theory for decision making">
                          <span className="badge badge-secondary badge-xs">i</span>
                        </div>
                      </div>
                    } 
                    htmlFor="useExpectedUtility"
                  >
                    <input
                      type="checkbox"
                      className="toggle toggle-secondary"
                      checked={watch('riskManagement')?.useExpectedUtility || true}
                      onChange={(e) => {
                        const currentRM = getValues('riskManagement') || getDefaultRiskManagement();
                        setValue('riskManagement', {
                          ...currentRM,
                          useExpectedUtility: e.target.checked
                        });
                      }}
                    />
                  </FormInput>
                </div>
              </div>
            )}
          </div>
        )}
      </div>

      <div className="modal-action">
        <button 
          type="button" 
          className="btn btn-ghost" 
          onClick={closeModal}
        >
          Cancel
        </button>
        {mode === 'createBot' ? (
          <>
            <button 
              type="button" 
              className="btn btn-secondary" 
              onClick={handleSubmit((form) => handleBotSubmission(form, true))}
            >
              Save
            </button>
            <button type="submit" className="btn btn-primary">
              Create Bot
            </button>
          </>
        ) : (
          <button type="submit" className="btn btn-primary">
            {mode === 'backtest' ? 'Run Backtest' : 'Update Bot'}
          </button>
        )}
      </div>
    </Modal>
  );
};

export default UnifiedTradingModal; 