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

import useApiUrlStore from '../../app/store/apiStore'
import {
  BacktestClient,
  GeneticCrossoverMethod,
  GeneticMutationMethod,
  type GeneticRequest,
  GeneticSelectionMethod,
  IndicatorType,
  type LightBacktestResponse,
  type PaginatedBacktestsResponse,
  type RunGeneticRequest,
  Ticker,
  Timeframe,
} from '../../generated/ManagingApi'
import {Toast} from '../../components/mollecules'
import Table from '../../components/mollecules/Table/Table'
import BacktestTable from '../../components/organism/Backtest/backtestTable'
import Modal from '../../components/mollecules/Modal/Modal'
import Fitness3DPlot from '../../components/organism/Charts/Fitness3DPlot'
import TPvsSLvsPnL3DPlot from '../../components/organism/Charts/TPvsSLvsPnL3DPlot'
import IndicatorsComparison from '../../components/organism/Charts/IndicatorsComparison'
import ScoreVsGeneration from '../../components/organism/Charts/ScoreVsGeneration'
import useTheme from '../../hooks/useTheme'

// Available Indicator Types
const ALL_INDICATORS = [
    IndicatorType.RsiDivergence,
    IndicatorType.RsiDivergenceConfirm,
    IndicatorType.MacdCross,
    IndicatorType.EmaCross,
    IndicatorType.ThreeWhiteSoldiers,
    IndicatorType.SuperTrend,
    IndicatorType.ChandelierExit,
    IndicatorType.EmaTrend,
    IndicatorType.StochRsiTrend,
    IndicatorType.Stc,
    IndicatorType.StDev,
    IndicatorType.LaggingStc,
    IndicatorType.SuperTrendCrossEma,
    IndicatorType.DualEmaCross,
]

// Form Interface
interface GeneticBundleFormData {
    ticker: Ticker
    timeframe: Timeframe
    startDate: string
    endDate: string
    balance: number
    populationSize: number
    generations: number
    mutationRate: number
    selectionMethod: GeneticSelectionMethod
    crossoverMethod: GeneticCrossoverMethod
    mutationMethod: GeneticMutationMethod
    elitismPercentage: number
    maxTakeProfit: number
    eligibleIndicators: IndicatorType[]
}

const BacktestGeneticBundle: React.FC = () => {
    const {apiUrl} = useApiUrlStore()
    const backtestClient = new BacktestClient({}, apiUrl)
    const theme = useTheme().themeProperty()

    // State
    const [isSubmitting, setIsSubmitting] = useState(false)
    const [selectedIndicators, setSelectedIndicators] = useState<IndicatorType[]>(ALL_INDICATORS)
    const [geneticRequests, setGeneticRequests] = useState<GeneticRequest[]>([])
    const [selectedRequest, setSelectedRequest] = useState<GeneticRequest | null>(null)
    const [isViewModalOpen, setIsViewModalOpen] = useState(false)
    const [backtests, setBacktests] = useState<LightBacktestResponse[]>([])
    const [isLoadingBacktests, setIsLoadingBacktests] = useState(false)
    const [isFormCollapsed, setIsFormCollapsed] = useState(false)

    // Pagination state
    const [currentPage, setCurrentPage] = useState(1)
    const [pageSize, setPageSize] = useState(50)
    const [totalBacktests, setTotalBacktests] = useState(0)
    const [totalPages, setTotalPages] = useState(0)

    // Sorting state
    const [currentSort, setCurrentSort] = useState<{ sortBy: string; sortOrder: 'asc' | 'desc' }>({
        sortBy: 'score',
        sortOrder: 'desc'
    })

    // Form setup
    const {register, handleSubmit, watch, setValue, formState: {errors}} = useForm<GeneticBundleFormData>({
        defaultValues: {
            ticker: Ticker.BTC,
            timeframe: Timeframe.OneHour,
            startDate: getDefaultDateRange().startDate,
            endDate: getDefaultDateRange().endDate,
            balance: 10000,
            populationSize: 10,
            generations: 5,
            mutationRate: 0.3,
            selectionMethod: GeneticSelectionMethod.Tournament,
            crossoverMethod: GeneticCrossoverMethod.Uniform,
            mutationMethod: GeneticMutationMethod.Uniform,
            elitismPercentage: 10,
            maxTakeProfit: 2.0,
            eligibleIndicators: ALL_INDICATORS,
        }
    })

    const formValues = watch()

    // Get default date range (last 30 days)
    function getDefaultDateRange() {
        const endDate = new Date()
        const startDate = new Date()
        startDate.setDate(startDate.getDate() - 30)

        return {
            startDate: startDate.toISOString().split('T')[0],
            endDate: endDate.toISOString().split('T')[0],
        }
    }

    // Fetch existing genetic requests
    const {data: existingRequests, refetch: refetchRequests} = useQuery({
        queryKey: ['geneticRequests'],
        queryFn: async () => {
            try {
                const requests = await backtestClient.backtest_GetGeneticRequests()
                setGeneticRequests(requests)
                return requests
            } catch (error) {
                console.error('Error fetching genetic requests:', error)
                return []
            }
        },
    })

    // Handle form submission
    const onSubmit = async (data: GeneticBundleFormData) => {
        if (selectedIndicators.length === 0) {
            new Toast('Please select at least one indicator', false)
            return
        }

        setIsSubmitting(true)
        const t = new Toast('Creating genetic request...')

        try {
            const request: RunGeneticRequest = {
                ticker: data.ticker,
                timeframe: data.timeframe,
                startDate: new Date(data.startDate),
                endDate: new Date(data.endDate),
                balance: data.balance,
                populationSize: data.populationSize,
                generations: data.generations,
                mutationRate: data.mutationRate,
                selectionMethod: data.selectionMethod,
                crossoverMethod: data.crossoverMethod,
                mutationMethod: data.mutationMethod,
                elitismPercentage: data.elitismPercentage,
                maxTakeProfit: data.maxTakeProfit,
                eligibleIndicators: selectedIndicators,
            }

            const geneticRequest = await backtestClient.backtest_RunGenetic(request)

            t.update('success', `Genetic request created successfully! ID: ${geneticRequest.requestId}`)

            // Refresh the list of genetic requests
            await refetchRequests()

            // Reset form
            setValue('ticker', Ticker.BTC)
            setValue('timeframe', Timeframe.OneHour)
            setValue('startDate', getDefaultDateRange().startDate)
            setValue('endDate', getDefaultDateRange().endDate)
            setValue('balance', 10000)
            setValue('populationSize', 10)
            setValue('generations', 5)
            setValue('mutationRate', 0.3)
            setValue('selectionMethod', GeneticSelectionMethod.Tournament)
            setValue('crossoverMethod', GeneticCrossoverMethod.Uniform)
            setValue('mutationMethod', GeneticMutationMethod.Uniform)
            setValue('elitismPercentage', 10)
            setValue('maxTakeProfit', 2.0)
            setSelectedIndicators(ALL_INDICATORS)

        } catch (error) {
            console.error('Error creating genetic request:', error)
            t.update('error', 'Failed to create genetic request. Please try again.')
        } finally {
            setIsSubmitting(false)
        }
    }

    // Handle indicator selection
    const handleIndicatorToggle = (indicator: IndicatorType) => {
        setSelectedIndicators(prev => {
            if (prev.includes(indicator)) {
                return prev.filter(i => i !== indicator)
            } else {
                return [...prev, indicator]
            }
        })
    }

    // Get status badge color
    const getStatusBadgeColor = (status: string) => {
        switch (status) {
            case 'Pending':
                return 'badge-warning'
            case 'Running':
                return 'badge-info'
            case 'Completed':
                return 'badge-success'
            case 'Failed':
                return 'badge-error'
            case 'Cancelled':
                return 'badge-neutral'
            default:
                return 'badge-neutral'
        }
    }

    // Handle view details
    const handleViewDetails = async (request: GeneticRequest) => {
        setSelectedRequest(request)
        setIsViewModalOpen(true)
        setIsLoadingBacktests(true)

        // Reset pagination and sorting state
        setCurrentPage(1)
        setTotalBacktests(0)
        setTotalPages(0)
        setCurrentSort({sortBy: 'score', sortOrder: 'desc'})

        try {
            const response: PaginatedBacktestsResponse = await backtestClient.backtest_GetBacktestsByRequestIdPaginated(
                request.requestId,
                1,
                pageSize,
                currentSort.sortBy,
                currentSort.sortOrder
            )
            setBacktests(response.backtests || [])
            setTotalBacktests(response.totalCount || 0)
            setTotalPages(response.totalPages || 0)
        } catch (error) {
            console.error('Error fetching backtests:', error)
            new Toast('Failed to load backtest details', false)
        } finally {
            setIsLoadingBacktests(false)
        }
    }

    // Close view modal
    const closeViewModal = () => {
        setIsViewModalOpen(false)
        setSelectedRequest(null)
        setBacktests([])
        setCurrentPage(1)
        setTotalBacktests(0)
        setTotalPages(0)
    }

    // Handle page change
    const handlePageChange = async (newPage: number) => {
        if (!selectedRequest || newPage < 1 || newPage > totalPages) return

        setIsLoadingBacktests(true)
        setCurrentPage(newPage)

        try {
            const response: PaginatedBacktestsResponse = await backtestClient.backtest_GetBacktestsByRequestIdPaginated(
                selectedRequest.requestId,
                newPage,
                pageSize,
                currentSort.sortBy,
                currentSort.sortOrder
            )
            setBacktests(response.backtests || [])
        } catch (error) {
            console.error('Error fetching backtests:', error)
            new Toast('Failed to load backtest details', false)
        } finally {
            setIsLoadingBacktests(false)
        }
    }

    // Handle sort change
    const handleSortChange = async (sortBy: string, sortOrder: 'asc' | 'desc') => {
        if (!selectedRequest) return

        setIsLoadingBacktests(true)
        setCurrentSort({sortBy, sortOrder})
        setCurrentPage(1) // Reset to first page when sorting

        try {
            const response: PaginatedBacktestsResponse = await backtestClient.backtest_GetBacktestsByRequestIdPaginated(
                selectedRequest.requestId,
                1,
                pageSize,
                sortBy,
                sortOrder
            )
            setBacktests(response.backtests || [])
            setTotalBacktests(response.totalCount || 0)
            setTotalPages(response.totalPages || 0)
        } catch (error) {
            console.error('Error fetching backtests:', error)
            new Toast('Failed to load backtest details', false)
        } finally {
            setIsLoadingBacktests(false)
        }
    }

    // Table columns for genetic requests
    const geneticRequestsColumns = useMemo(() => [
        {
            Header: 'Ticker',
            accessor: 'ticker',
        },
        {
            Header: 'Timeframe',
            accessor: 'timeframe',
        },
        {
            Header: 'Progress & Status',
            accessor: 'currentGeneration',
            Cell: ({value, row}: { value: number, row: any }) => {
                const generations = row.original.generations
                const currentGen = value || 0
                const percentage = generations > 0 ? Math.round((currentGen / generations) * 100) : 0
                const status = row.original.status

                // Calculate color based on percentage (red to green)
                const getProgressColor = (percent: number) => {
                    if (percent <= 25) return 'progress-error'
                    if (percent <= 50) return 'progress-warning'
                    if (percent <= 75) return 'progress-info'
                    return 'progress-success'
                }

                return (
                    <div className="flex flex-col gap-2">
                        <div className="flex items-center justify-between">
                            <span className={`badge badge-sm ${getStatusBadgeColor(status)}`}>
                                {status}
                            </span>
                            <div className="text-xs">
                                {currentGen} / {generations}
                            </div>
                        </div>
                        <progress
                            className={`progress w-56 ${getProgressColor(percentage)}`}
                            value={percentage}
                            max="100"
                        />
                    </div>
                )
            },
        },
        {
            Header: 'Selection',
            accessor: 'selectionMethod',
            Cell: ({value}: { value: string }) => (
                <span className="text-xs">{value}</span>
            ),
        },
        {
            Header: 'Crossover',
            accessor: 'crossoverMethod',
            Cell: ({value}: { value: string }) => (
                <span className="text-xs">{value}</span>
            ),
        },
        {
            Header: 'Mutation',
            accessor: 'mutationMethod',
            Cell: ({value}: { value: string }) => (
                <span className="text-xs">{value}</span>
            ),
        },

        {
            Header: 'Actions',
            accessor: 'actions',
            Cell: ({row}: { row: any }) => (
                <div className="flex gap-2">
                    <button
                        onClick={() => handleViewDetails(row.original)}
                        className="btn btn-sm btn-outline"
                    >
                        View
                    </button>
                    <button
                        onClick={async () => {
                            try {
                                await backtestClient.backtest_DeleteGeneticRequest(row.original.requestId)
                                new Toast('Request deleted successfully', false)
                                await refetchRequests()
                            } catch (error) {
                                new Toast('Failed to delete request', false)
                            }
                        }}
                        className="btn btn-sm btn-error"
                    >
                        Delete
                    </button>
                </div>
            ),
        },
    ], [refetchRequests])


    return (
        <div className="space-y-6">
            <div className="card bg-base-100 shadow-xl">
                <div className="card-body">
                    <div className="flex justify-between items-center mb-4">
                        <div>
                            <h2 className="card-title">Genetic Algorithm Bundle</h2>
                            <p className="text-sm text-gray-600">
                                Create a genetic algorithm request that will be processed in the background.
                                The algorithm will optimize trading parameters and indicator combinations.
                            </p>
                        </div>
                        <button
                            type="button"
                            onClick={() => setIsFormCollapsed(!isFormCollapsed)}
                            className="btn btn-sm btn-outline"
                        >
                            {isFormCollapsed ? 'Show Form' : 'Hide Form'}
                        </button>
                    </div>

                    <form onSubmit={handleSubmit(onSubmit)} className={`space-y-4 ${isFormCollapsed ? 'hidden' : ''}`}>
                        {isFormCollapsed && (
                            <div className="space-y-4">
                                <div className="bg-base-200 p-4 rounded-lg">
                                    <h4 className="font-semibold mb-2">Current Settings</h4>
                                    <div className="grid grid-cols-2 md:grid-cols-4 gap-2 text-sm">
                                        <div><strong>Ticker:</strong> {formValues.ticker}</div>
                                        <div><strong>Timeframe:</strong> {formValues.timeframe}</div>
                                        <div><strong>Population:</strong> {formValues.populationSize}</div>
                                        <div><strong>Generations:</strong> {formValues.generations}</div>
                                        <div><strong>Selection:</strong> {formValues.selectionMethod}</div>
                                        <div><strong>Crossover:</strong> {formValues.crossoverMethod}</div>
                                        <div><strong>Mutation:</strong> {formValues.mutationMethod}</div>
                                        <div><strong>Indicators:</strong> {selectedIndicators.length}</div>
                                    </div>
                                </div>
                                <div className="flex justify-center">
                                    <button
                                        type="button"
                                        onClick={handleSubmit(onSubmit)}
                                        disabled={isSubmitting}
                                        className="btn btn-primary"
                                    >
                                        {isSubmitting ? 'Creating...' : 'Create Request with Current Settings'}
                                    </button>
                                </div>
                            </div>
                        )}
                        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div className="form-control">
                                <label className="label">
                                    <span className="label-text">Ticker</span>
                                </label>
                                <select
                                    className="select select-bordered w-full"
                                    {...register('ticker')}
                                >
                                    {Object.values(Ticker).map(ticker => (
                                        <option key={ticker} value={ticker}>{ticker}</option>
                                    ))}
                                </select>
                            </div>

                            <div className="form-control">
                                <label className="label">
                                    <span className="label-text">Timeframe</span>
                                </label>
                                <select
                                    className="select select-bordered w-full"
                                    {...register('timeframe')}
                                >
                                    {Object.values(Timeframe).map(tf => (
                                        <option key={tf} value={tf}>{tf}</option>
                                    ))}
                                </select>
                            </div>

                            <div className="form-control">
                                <label className="label">
                                    <span className="label-text">Start Date</span>
                                </label>
                                <input
                                    type="date"
                                    className="input input-bordered w-full"
                                    {...register('startDate')}
                                />
                            </div>

                            <div className="form-control">
                                <label className="label">
                                    <span className="label-text">End Date</span>
                                </label>
                                <input
                                    type="date"
                                    className="input input-bordered w-full"
                                    {...register('endDate')}
                                />
                            </div>

                            <div className="form-control">
                                <label className="label">
                                    <span className="label-text">Balance</span>
                                </label>
                                <input
                                    type="number"
                                    className="input input-bordered w-full"
                                    {...register('balance', {valueAsNumber: true})}
                                />
                            </div>

                            <div className="form-control">
                                <label className="label">
                                    <span className="label-text">Population Size</span>
                                </label>
                                <input
                                    type="number"
                                    min="5"
                                    max="1000"
                                    className="input input-bordered w-full"
                                    {...register('populationSize', {valueAsNumber: true})}
                                />
                            </div>

                            <div className="form-control">
                                <label className="label">
                                    <span className="label-text">Generations</span>
                                </label>
                                <input
                                    type="number"
                                    min="1"
                                    max="1000"
                                    className="input input-bordered w-full"
                                    {...register('generations', {valueAsNumber: true})}
                                />
                            </div>

                            <div className="form-control">
                                <label className="label">
                                    <span className="label-text">Mutation Rate</span>
                                </label>
                                <input
                                    type="number"
                                    step="0.1"
                                    min="0"
                                    max="1"
                                    className="input input-bordered w-full"
                                    {...register('mutationRate', {valueAsNumber: true})}
                                />
                            </div>

                            <div className="form-control">
                                <label className="label">
                                    <span className="label-text">Selection Method</span>
                                </label>
                                <select
                                    className="select select-bordered w-full"
                                    {...register('selectionMethod')}
                                >
                                    <option value={GeneticSelectionMethod.Elite}>Elite Selection</option>
                                    <option value={GeneticSelectionMethod.Roulette}>Roulette Wheel</option>
                                    <option value={GeneticSelectionMethod.StochasticUniversalSampling}>Stochastic
                                        Universal Sampling
                                    </option>
                                    <option value={GeneticSelectionMethod.Tournament}>Tournament Selection</option>
                                    <option value={GeneticSelectionMethod.Truncation}>Truncation Selection</option>
                                </select>
                            </div>

                            <div className="form-control">
                                <label className="label">
                                    <span className="label-text">Crossover Method</span>
                                </label>
                                <select
                                    className="select select-bordered w-full"
                                    {...register('crossoverMethod')}
                                >
                                    <option value={GeneticCrossoverMethod.AlternatingPosition}>Alternating Position
                                        (AP)
                                    </option>
                                    <option value={GeneticCrossoverMethod.CutAndSplice}>Cut and Splice</option>
                                    <option value={GeneticCrossoverMethod.Cycle}>Cycle (CX)</option>
                                    <option value={GeneticCrossoverMethod.OnePoint}>One-Point (C1)</option>
                                    <option value={GeneticCrossoverMethod.OrderBased}>Order-based (OX2)</option>
                                    <option value={GeneticCrossoverMethod.Ordered}>Ordered (OX1)</option>
                                    <option value={GeneticCrossoverMethod.PartiallyMapped}>Partially Mapped (PMX)
                                    </option>
                                    <option value={GeneticCrossoverMethod.PositionBased}>Position-based (POS)</option>
                                    <option value={GeneticCrossoverMethod.ThreeParent}>Three Parent</option>
                                    <option value={GeneticCrossoverMethod.TwoPoint}>Two-Point (C2)</option>
                                    <option value={GeneticCrossoverMethod.Uniform}>Uniform</option>
                                    <option value={GeneticCrossoverMethod.VotingRecombination}>Voting Recombination
                                        (VR)
                                    </option>
                                </select>
                            </div>

                            <div className="form-control">
                                <label className="label">
                                    <span className="label-text">Mutation Method</span>
                                </label>
                                <select
                                    className="select select-bordered w-full"
                                    {...register('mutationMethod')}
                                >
                                    <option value={GeneticMutationMethod.Displacement}>Displacement</option>
                                    <option value={GeneticMutationMethod.FlipBit}>Flip Bit</option>
                                    <option value={GeneticMutationMethod.Insertion}>Insertion</option>
                                    <option value={GeneticMutationMethod.PartialShuffle}>Partial Shuffle (PSM)</option>
                                    <option value={GeneticMutationMethod.ReverseSequence}>Reverse Sequence (RSM)
                                    </option>
                                    <option value={GeneticMutationMethod.Twors}>Twors</option>
                                    <option value={GeneticMutationMethod.Uniform}>Uniform</option>
                                </select>
                            </div>

                            <div className="form-control">
                                <label className="label">
                                    <span className="label-text">Elitism Percentage</span>
                                </label>
                                <input
                                    type="number"
                                    min="1"
                                    max="50"
                                    step="1"
                                    className="input input-bordered w-full"
                                    {...register('elitismPercentage', {valueAsNumber: true})}
                                />
                            </div>

                            <div className="form-control">
                                <label className="label">
                                    <span className="label-text">Max Take Profit (%)</span>
                                </label>
                                <input
                                    type="number"
                                    min="0.9"
                                    max="8"
                                    step="0.1"
                                    className="input input-bordered w-full"
                                    {...register('maxTakeProfit', {valueAsNumber: true})}
                                />
                            </div>
                        </div>

                        <div className="form-control">
                            <label className="label">
                                <span className="label-text">Eligible Indicators</span>
                            </label>
                            <div
                                className="grid grid-cols-2 md:grid-cols-3 gap-2 max-h-40 overflow-y-auto border rounded-lg p-4">
                                {ALL_INDICATORS.map(indicator => (
                                    <label key={indicator} className="flex items-center gap-2 cursor-pointer">
                                        <input
                                            type="checkbox"
                                            checked={selectedIndicators.includes(indicator)}
                                            onChange={() => handleIndicatorToggle(indicator)}
                                            className="checkbox checkbox-sm"
                                        />
                                        <span className="text-sm">{indicator}</span>
                                    </label>
                                ))}
                            </div>
                            <div className="text-xs text-gray-500 mt-1">
                                {selectedIndicators.length} of {ALL_INDICATORS.length} indicators selected
                            </div>
                        </div>

                        <div className="flex gap-4">
                            <button
                                type="submit"
                                disabled={isSubmitting || selectedIndicators.length === 0}
                                className="btn btn-primary"
                            >
                                {isSubmitting ? 'Creating...' : 'Create Genetic Request'}
                            </button>

                            <button
                                type="button"
                                onClick={() => setSelectedIndicators(ALL_INDICATORS)}
                                className="btn btn-secondary"
                            >
                                Select All Indicators
                            </button>

                            <button
                                type="button"
                                onClick={() => setSelectedIndicators([])}
                                className="btn btn-secondary"
                            >
                                Clear All
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            {/* Existing Genetic Requests */}
            {geneticRequests.length > 0 && (
                <div className="card bg-base-100 shadow-xl">
                    <div className="card-body">
                        <h3 className="card-title">Existing Genetic Requests</h3>
                        <Table
                            columns={geneticRequestsColumns}
                            data={geneticRequests}
                            showPagination={true}
                        />
                    </div>
                </div>
            )}

            {/* View Details Modal */}
            <Modal
                showModal={isViewModalOpen}
                onClose={closeViewModal}
                titleHeader={`Genetic Request Details - ${selectedRequest?.requestId?.slice(0, 8)}...`}
                size="7xl"
            >
                {selectedRequest && (
                    <>
                        <div className="grid grid-cols-2 gap-4 mb-6">
                            <div>
                                <strong>Ticker:</strong> {selectedRequest.ticker}
                            </div>
                            <div>
                                <strong>Timeframe:</strong> {selectedRequest.timeframe}
                            </div>
                            <div>
                                <strong>Selection Method:</strong> {selectedRequest.selectionMethod}
                            </div>
                            <div>
                                <strong>Crossover Method:</strong> {selectedRequest.crossoverMethod}
                            </div>
                            <div>
                                <strong>Mutation Method:</strong> {selectedRequest.mutationMethod}
                            </div>
                            <div>
                                <strong>Status:</strong>
                                <span className={`badge ${getStatusBadgeColor(selectedRequest.status)} ml-2`}>
                  {selectedRequest.status}
                </span>
                            </div>
                            <div>
                                <strong>Created:</strong> {new Date(selectedRequest.createdAt).toLocaleString()}
                            </div>
                            {selectedRequest.completedAt && (
                                <div>
                                    <strong>Completed:</strong> {new Date(selectedRequest.completedAt).toLocaleString()}
                                </div>
                            )}
                            <div>
                                <strong>Progress:</strong> {selectedRequest.currentGeneration || 0} / {selectedRequest.generations}
                                {selectedRequest.currentGeneration && selectedRequest.generations > 0 && (
                                    <div className="mt-1">
                                        <progress
                                            className="progress progress-primary w-full h-2"
                                            value={Math.round(((selectedRequest.currentGeneration || 0) / selectedRequest.generations) * 100)}
                                            max="100"
                                        />
                                    </div>
                                )}
                            </div>
                            {selectedRequest.bestFitnessSoFar && (
                                <div>
                                    <strong>Best Fitness:</strong> {selectedRequest.bestFitnessSoFar.toFixed(4)}
                                </div>
                            )}
                        </div>

                        <div className="mb-6">
                            <div className="flex justify-between items-center mb-4">
                                <h4 className="font-semibold">Backtest Results ({totalBacktests} total)</h4>
                                {totalPages > 1 && (
                                    <div className="flex items-center gap-2">
                                        <span className="text-sm text-gray-600">
                                            Page {currentPage} of {totalPages}
                                        </span>
                                        <div className="join">
                                            <button
                                                className="join-item btn btn-sm"
                                                onClick={() => handlePageChange(currentPage - 1)}
                                                disabled={currentPage <= 1 || isLoadingBacktests}
                                            >
                                                «
                                            </button>
                                            <button
                                                className="join-item btn btn-sm"
                                                onClick={() => handlePageChange(currentPage + 1)}
                                                disabled={currentPage >= totalPages || isLoadingBacktests}
                                            >
                                                »
                                            </button>
                                        </div>
                                    </div>
                                )}
                            </div>
                            {isLoadingBacktests ? (
                                <div className="flex justify-center">
                                    <span className="loading loading-spinner loading-md"></span>
                                </div>
                            ) : backtests.length > 0 ? (
                                <>
                                    {/* Score vs Generation Chart */}
                                    <div className="mb-6">
                                        <div className="card bg-base-100 shadow-xl">
                                            <div className="card-body">
                                                <h3 className="card-title">Score vs Generation</h3>
                                                <ScoreVsGeneration backtests={backtests as any} theme={theme}/>
                                            </div>
                                        </div>
                                    </div>

                                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
                                        {/* Fitness vs Score vs Win Rate */}
                                        <div className="card bg-base-100 shadow-xl">
                                            <div className="card-body">
                                                <h3 className="card-title">Fitness vs Score vs Win Rate</h3>
                                                <Fitness3DPlot backtests={backtests as any} theme={theme}/>
                                            </div>
                                        </div>

                                        {/* TP% vs SL% vs PnL */}
                                        <div className="card bg-base-100 shadow-xl">
                                            <div className="card-body">
                                                <h3 className="card-title">Take Profit vs Stop Loss vs PnL</h3>
                                                <TPvsSLvsPnL3DPlot backtests={backtests as any} theme={theme}/>
                                            </div>
                                        </div>
                                    </div>

                                    {/* Strategy Comparison Radar Chart */}
                                    <div className="mb-6">
                                        <IndicatorsComparison backtests={backtests as any}/>
                                    </div>

                                    <BacktestTable
                                        list={backtests as any}
                                        isFetching={false}
                                        displaySummary={false}
                                        onSortChange={handleSortChange}
                                        currentSort={currentSort}
                                    />
                                </>
                            ) : (
                                <div className="text-center text-gray-500 py-8">
                                    No backtest results found for this request.
                                </div>
                            )}
                        </div>
                    </>
                )}
            </Modal>
        </div>
    )
}

export default BacktestGeneticBundle 