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 {
    AccountClient,
    BacktestClient,
    DataClient,
    MoneyManagement,
    MoneyManagementClient,
    RunBacktestRequest,
    Scenario,
    ScenarioClient,
    Ticker,
    Timeframe,
    TradingBotConfigRequest,
} from '../../../generated/ManagingApi'
import type {BacktestModalProps, IBacktestsFormInput,} from '../../../global/type.tsx'
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 BacktestModal: React.FC<BacktestModalProps> = ({
  showModal,
  closeModal,
  setBacktests,
}) => {
  // Get date 15 days ago for start date
  const defaultStartDate = new Date();
  defaultStartDate.setDate(defaultStartDate.getDate() - 15);
  const defaultStartDateString = defaultStartDate.toISOString().split('T')[0];
  
  // Today for end date
  const defaultEndDate = new Date();
  const defaultEndDateString = defaultEndDate.toISOString().split('T')[0];

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

  const { register, handleSubmit, setValue, watch } = useForm<IBacktestsFormInput>({
    defaultValues: {
      startDate: defaultStartDateString,
      endDate: defaultEndDateString,
      cooldownPeriod: 10, // Default cooldown period of 10 minutes
      maxLossStreak: 0, // Default max loss streak of 0 (no limit)
      maxPositionTimeHours: null, // Default to null (disabled)
      flipOnlyWhenInProfit: true, // Default to true
      balance: 10000, // Default balance
      closeEarlyWhenProfitable: false, // Default to false
      // Synth API defaults
      useSynthApi: false,
      useForPositionSizing: true,
      useForSignalFiltering: true,
      useForDynamicStopLoss: true
    }
  });

  // Watch the useSynthApi value to conditionally show/hide sub-options
  const useSynthApi = watch('useSynthApi');

  // Reset sub-options when main Synth API toggle is turned off
  useEffect(() => {
    if (!useSynthApi) {
      setValue('useForPositionSizing', false);
      setValue('useForSignalFiltering', false);
      setValue('useForDynamicStopLoss', false);
    }
  }, [useSynthApi, setValue]);

  // State for advanced parameters dropdown
  const [showAdvancedParams, setShowAdvancedParams] = useState(false);

  const [selectedAccount, setSelectedAccount] = useState<string>('')
  const [selectedTimeframe, setSelectedTimeframe] = useState<Timeframe>(Timeframe.OneHour)

  const [balance, setBalance] = useState<number>(10000)
  
  const [customMoneyManagement, setCustomMoneyManagement] =
    React.useState<MoneyManagement | undefined>(undefined)
  const [selectedMoneyManagement, setSelectedMoneyManagement] =
    useState<string>()
  const [showCustomMoneyManagement, setShowCustomMoneyManagement] =
    useState(false)

  const [customScenario, setCustomScenario] =
    React.useState<Scenario | undefined>(undefined)
  const [selectedScenario, setSelectedScenario] =
    useState<string>()
  const [showCustomScenario, setShowCustomScenario] =
    useState(false)

  const { apiUrl } = useApiUrlStore()

  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 onSubmit: SubmitHandler<IBacktestsFormInput> = async (form) => {
    // Check if we have either a selected scenario or a custom scenario
    if (!form.scenarioName && !customScenario) {
      const t = new Toast('Please select a scenario or create a custom scenario', false);
      return;
    }

    // If using custom scenario, validate it has indicators
    if (customScenario && (!customScenario.indicators || customScenario.indicators.length === 0)) {
      const t = new Toast('Custom scenario must have at least one indicator', false);
      return;
    }

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

    // Process tickers sequentially
    for (const ticker of form.tickers) {
      const scenarioName = form.scenarioName;
      try {
        await runBacktest(form, ticker, scenarioName, customMoneyManagement, 0);
      } catch (error) {
        console.error(`Error running backtest for ${ticker}:`, error);
        // Continue with next ticker even if one fails
        continue;
      }
    }
  }

  async function runBacktest(
    form: IBacktestsFormInput,
    ticker: string,
    scenarioName: string,
    customMoneyManagement: MoneyManagement | undefined,
    loopCount: number
  ): Promise<void> {
    const t = new Toast(ticker + ' is running')
    
    console.log(customMoneyManagement)
    console.log(customScenario)
    
    try {
      // Create the TradingBotConfigRequest (note the Request suffix)
      const tradingBotConfigRequest: TradingBotConfigRequest = {
        accountName: form.accountName,
        ticker: ticker as Ticker,
        scenarioName: customScenario ? undefined : scenarioName,
        scenario: customScenario ? {
          name: customScenario.name || 'Custom Scenario',
          indicators: customScenario.indicators?.map(indicator => ({
            name: indicator.name || 'Unnamed Indicator',
            type: indicator.type!,
            signalType: indicator.signalType!,
            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
          })) || [],
          loopbackPeriod: customScenario.loopbackPeriod
        } : undefined,
        timeframe: form.timeframe,
        isForWatchingOnly: false, // Always false for backtests
        cooldownPeriod: form.cooldownPeriod || 1,
        maxLossStreak: form.maxLossStreak || 0,
        maxPositionTimeHours: form.maxPositionTimeHours || null,
        flipOnlyWhenInProfit: form.flipOnlyWhenInProfit ?? true,
        name: `Backtest-${customScenario ? customScenario.name : 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,
        flipPosition: false
      };

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

      const backtest = await backtestClient.backtest_Run(request);
      
      t.update('success', `${backtest.config.ticker} Backtest Succeeded`)
      setBacktests((arr) => [...arr, backtest])


    } catch (err) {
      t.update('error', 'Error: ' + err)
      throw err; // Re-throw the error to be caught by the caller
    }
  }

  function setSelectedAccountEvent(e: React.ChangeEvent<HTMLInputElement>) {
    setSelectedAccount(e.target.value)
  }

  function setSelectedTimeframeEvent(e: any) {
    setSelectedTimeframe(e.target.value)
  }

  function onMoneyManagementChange(e: any) {
    if (e.target.value === 'custom') {
      setShowCustomMoneyManagement(true)
      setCustomMoneyManagement(undefined) // Reset custom money management when switching to custom mode
    } else {
      setShowCustomMoneyManagement(false)
      setCustomMoneyManagement(undefined)
      setSelectedMoneyManagement(e.target.value)
    }
  }

  function onScenarioChange(e: any) {
    if (e.target.value === 'custom') {
      setShowCustomScenario(true)
      setCustomScenario(undefined) // Reset custom scenario when switching to custom mode
    } else {
      setShowCustomScenario(false)
      setCustomScenario(undefined)
      setSelectedScenario(e.target.value)
    }
  }

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

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

  // Set the first scenario as default when scenarios are loaded
  useEffect(() => {
    if (scenarios && scenarios.length > 0 && scenarios[0].name) {
      setValue('scenarioName', scenarios[0].name);
      setShowCustomScenario(false); // Hide custom scenario when scenarios are available
    } else if (scenarios && scenarios.length === 0) {
      // No scenarios available, automatically show custom scenario creation
      setShowCustomScenario(true);
      setValue('scenarioName', ''); // Clear any selected scenario
    }
  }, [scenarios, setValue]);

  useEffect(() => {
    if (accounts && accounts.length > 0) {
      setSelectedAccount(accounts[0].name)
      setSelectedTimeframe(Timeframe.FiveMinutes)
    }
  }, [accounts])

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

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

  useEffect(() => {
    if (moneyManagements && moneyManagements.length > 0){
      setSelectedMoneyManagement(moneyManagements[0].name)
      setCustomMoneyManagement(undefined)
      setShowCustomMoneyManagement(false) // Hide custom money management when options are available
    } else if (moneyManagements && moneyManagements.length === 0) {
      // No money management options available, automatically show custom money management
      setShowCustomMoneyManagement(true)
      setSelectedMoneyManagement(undefined)
      setCustomMoneyManagement(undefined)
    }
  }, [moneyManagements])

  useEffect(() => {
    if (selectedAccount && selectedTimeframe) {
      refetchTickers()
    }
  }, [selectedAccount, selectedTimeframe])

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

  return (
    <Modal
      showModal={showModal}
      onSubmit={handleSubmit(onSubmit)}
      onClose={closeModal}
      titleHeader="Run Backtest"
    >
      <div className="space-y-4">
        {/* First Row: Account & Timeframe */}
        <div className="grid grid-cols-2 gap-4">
          <FormInput label="Account" htmlFor="accountName">
            <select
              className="select select-bordered w-full"
              {...register('accountName', {
                onChange(e) {
                  setSelectedAccountEvent(e)
                },
              })}
            >
              <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', {
                onChange(event) {
                  setSelectedTimeframeEvent(event)
                },
              })}
              value={selectedTimeframe}
            >
              {Object.keys(Timeframe).map((item) => (
                <option key={item} value={item}>
                  {item}
                </option>
              ))}
            </select>
          </FormInput>
        </div>

        {/* Second Row: Money Management & Bot Type */}
        <div className="grid grid-cols-2 gap-4">
          <FormInput label="Money Management" htmlFor="moneyManagement">
            <select
              className="select select-bordered w-full"
              {...register('moneyManagement', {
                onChange(event) {
                  onMoneyManagementChange(event)
                },
              })}
            >
              {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}
                    </option>
                  ))}
                </>
              )}
              <option key="custom" value="custom">
                {moneyManagements.length === 0 ? 'Create Custom Money Management' : 'Custom'}
              </option>
            </select>
          </FormInput>
        </div>

        {/* Losing streak info */}
        {(() => {
          // Find the selected money management object
          let mm: MoneyManagement | undefined = undefined;
          if (showCustomMoneyManagement && customMoneyManagement) {
            mm = { ...customMoneyManagement, stopLoss: customMoneyManagement.stopLoss / 100 };
          } else if (selectedMoneyManagement) {
            mm = moneyManagements.find((m) => m.name === selectedMoneyManagement);
          }
          // Use form balance if available, otherwise fall back to state balance
          const initialBalance = balance; // This state is kept in sync with form
          const minBalance = 10; // You can make this configurable if needed
          if (mm && mm.leverage && mm.stopLoss && initialBalance > minBalance) {
            const perLoss = mm.leverage * mm.stopLoss;
            if (perLoss > 0 && perLoss < 1) {
              const streak = Math.floor(Math.log(minBalance / initialBalance) / Math.log(1 - perLoss));
              return (
                <div className="text-sm text-info mt-1">
                  Max losing streak before balance drops below {minBalance}: <b>{streak}</b> trades (with leverage x{mm.leverage} and stop loss {Math.round(mm.stopLoss * 10000) / 100}% per trade, starting from {initialBalance})
                </div>
              );
            }
          }
          return null;
        })()}

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

        {/* Third Row: Scenario & Tickers (full width since they need more space) */}
        <div className="grid grid-cols-1 gap-4">
          <FormInput label="Scenario" htmlFor="scenarioName">
            <select
              className="select select-bordered w-full"
              {...register('scenarioName', {
                onChange(event) {
                  onScenarioChange(event)
                },
              })}
            >
              {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>

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

          <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}>
                  <img src={item.imageUrl || ''} alt={item.ticker} className="w-4 h-4 mr-2" />
                  {item.ticker}
                </option>
              ))}
            </select>
          </FormInput>
        </div>

        {/* Fourth Row: Balance */}
        <div className="grid grid-cols-1 gap-4">
          <FormInput label="Balance" htmlFor="balance">
            <input
              type="number"
              className="input input-bordered w-full"
              {...register('balance', { valueAsNumber: true })}
              onChange={(e) => {
                setValue('balance', Number(e.target.value));
                setBalance(Number(e.target.value)); // Keep state in sync for UI calculations
              }}
            />
          </FormInput>
        </div>

        {/* 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 & Dates */}
            <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>

            {/* Start Date & End Date */}
            <div className="grid 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-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>

            {/* Flip Only When In Profit & Close Early When Profitable */}
            <div className="grid 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 */}
            <div className="grid grid-cols-1 gap-4">
              <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>
            </div>

            {/* 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')}
                />
              </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>
        )}
      </div>

      <div className="modal-action">
        <button 
          type="button" 
          className="btn btn-ghost" 
          onClick={closeModal}
        >
          Cancel
        </button>
        <button type="submit" className="btn btn-primary">
          Run Backtest
        </button>
      </div>
    </Modal>
  )
}

export default BacktestModal
