import React, { useMemo, useState } from 'react';
import type {
    BacktestIntraCandlePolicy,
    BacktestRequestPayload,
    BacktestTimeframe,
    BacktestTriggerTimeframe
} from '../types';
import { parseSymbolsInput, toDateInputValue } from '../utils';
import { Button, Input, Select } from '../../components/ui/Primitives';

type SourceType = 'csv' | 'json' | 'replay' | 'kraken';

interface BacktestConfiguratorProps {
    profileId?: string;
    strategyConfig: any;
    initialSymbols: string[];
    initialCapitalUsd?: number;
    onRun: (payload: BacktestRequestPayload) => Promise<void> | void;
    running?: boolean;
}

export const BacktestConfigurator: React.FC<BacktestConfiguratorProps> = ({
    profileId,
    strategyConfig,
    initialSymbols,
    initialCapitalUsd = 1000,
    onRun,
    running = false
}) => {
    const now = Date.now();
    const defaultFrom = toDateInputValue(now - (30 * 24 * 60 * 60 * 1000));
const defaultTo = toDateInputValue(now);

    const [symbolsInput, setSymbolsInput] = useState((initialSymbols || []).join(', '));
    const [timeframe, setTimeframe] = useState<BacktestTimeframe>('15m');
    const [fromDate, setFromDate] = useState(defaultFrom);
    const [toDate, setToDate] = useState(defaultTo);
    const [sourceType, setSourceType] = useState<SourceType>('csv');
    const [sourcePayload, setSourcePayload] = useState<any>(null);
    const [sourceName, setSourceName] = useState('');
    const [initialCapital, setInitialCapital] = useState(initialCapitalUsd);
    const [slippageBps, setSlippageBps] = useState(5);
    const [feeBps, setFeeBps] = useState(10);
    const [partialFillPct, setPartialFillPct] = useState(1);
    const [fillOnNextBar, setFillOnNextBar] = useState(true);
    const [intraCandlePolicy, setIntraCandlePolicy] = useState<BacktestIntraCandlePolicy>('ohlc_path');
    const [triggerTimeframe, setTriggerTimeframe] = useState<BacktestTriggerTimeframe>('1m');
    const [forceCloseAtWindowEnd, setForceCloseAtWindowEnd] = useState(false);
    const [krakenLookbackCandles, setKrakenLookbackCandles] = useState(2000);
    const [error, setError] = useState<string | null>(null);

    const parsedSymbols = useMemo(() => parseSymbolsInput(symbolsInput), [symbolsInput]);

    const readFile = async (file: File): Promise<void> => {
        const text = await file.text();
        setSourceName(file.name);
        if (sourceType === 'csv') {
            setSourcePayload(text);
            return;
        }
        try {
            const parsed = JSON.parse(text);
            setSourcePayload(parsed);
        } catch {
            throw new Error('Failed to parse JSON file.');
        }
    };

    const handleRun = async () => {
        setError(null);
        if (!parsedSymbols.length) {
            setError('Please provide at least one symbol.');
            return;
        }
        if (!fromDate || !toDate) {
            setError('Please provide both from/to dates.');
            return;
        }
        if (new Date(`${toDate}T23:59:59.999Z`).getTime() < new Date(`${fromDate}T00:00:00.000Z`).getTime()) {
            setError('To date must be greater than or equal to From date.');
            return;
        }
        if (sourceType !== 'kraken' && !sourcePayload) {
            setError('Please upload historical data (CSV/JSON/Replay JSON) before running.');
            return;
        }
        if (!strategyConfig) {
            setError('Strategy configuration is required.');
            return;
        }

        const payload: BacktestRequestPayload = {
            mode: 'backtest',
            profileId,
            strategyConfig,
            symbols: parsedSymbols,
            timeframe,
            dateRange: {
                from: new Date(`${fromDate}T00:00:00.000Z`).toISOString(),
                to: new Date(`${toDate}T23:59:59.999Z`).toISOString()
            },
            dataSource: {
                type: sourceType,
                payload: sourceType === 'kraken'
                    ? {
                        exchange: 'kraken',
                        lookbackCandles: Number(krakenLookbackCandles || 2000)
                    }
                    : (sourceType === 'csv' ? String(sourcePayload || '') : sourcePayload)
            },
            execution: {
                initialCapitalUsd: Number(initialCapital || 0),
                orderType: 'market',
                slippageBps: Number(slippageBps),
                feeBps: Number(feeBps),
                partialFillPct: Number(partialFillPct),
                fillOnNextBar,
                intraCandlePolicy,
                triggerTimeframe,
                enforceWarmup: true,
                allowNegativeCash: false,
                forceCloseAtWindowEnd
            }
        };

        await onRun(payload);
    };

    return (
        <div className="space-y-4 p-4 rounded-2xl border border-white/10 bg-zinc-950/70">
            <div className="flex items-center justify-between">
                <h3 className="text-sm font-bold uppercase tracking-wider text-white">Backtest Configuration</h3>
                <span className="text-[10px] text-zinc-500 uppercase">No JSON editing required</span>
            </div>
            <p className="text-[11px] text-zinc-500">Replay window is inclusive and evaluated in UTC.</p>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                <label className="space-y-1">
                    <span className="text-[10px] uppercase tracking-wider text-zinc-400">Symbols</span>
                    <Input
                        value={symbolsInput}
                        onChange={(event) => setSymbolsInput(event.target.value)}
                        placeholder="BTC/USDT, ETH/USDT"
                        controlSize="sm"
                    />
                </label>
                <label className="space-y-1">
                    <span className="text-[10px] uppercase tracking-wider text-zinc-400">Timeframe</span>
                    <Select
                        value={timeframe}
                        onChange={(event) => setTimeframe(event.target.value as BacktestTimeframe)}
                        controlSize="sm"
                        options={[
                            { value: '1m', label: '1m' },
                            { value: '15m', label: '15m' },
                            { value: '1h', label: '1h' },
                            { value: '4h', label: '4h' },
                        ]}
                    />
                </label>
                <label className="space-y-1">
                    <span className="text-[10px] uppercase tracking-wider text-zinc-400">From</span>
                    <Input
                        type="date"
                        value={fromDate}
                        onChange={(event) => setFromDate(event.target.value)}
                        controlSize="sm"
                    />
                </label>
                <label className="space-y-1">
                    <span className="text-[10px] uppercase tracking-wider text-zinc-400">To</span>
                    <Input
                        type="date"
                        value={toDate}
                        onChange={(event) => setToDate(event.target.value)}
                        controlSize="sm"
                    />
                </label>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-4 gap-3">
                <label className="space-y-1">
                    <span className="text-[10px] uppercase tracking-wider text-zinc-400">Initial Capital (USD)</span>
                    <Input
                        type="number"
                        min={1}
                        value={initialCapital}
                        onChange={(event) => setInitialCapital(Number(event.target.value))}
                        controlSize="sm"
                    />
                </label>
                <label className="space-y-1">
                    <span className="text-[10px] uppercase tracking-wider text-zinc-400">Slippage (bps)</span>
                    <Input
                        type="number"
                        min={0}
                        value={slippageBps}
                        onChange={(event) => setSlippageBps(Number(event.target.value))}
                        controlSize="sm"
                    />
                </label>
                <label className="space-y-1">
                    <span className="text-[10px] uppercase tracking-wider text-zinc-400">Fee (bps)</span>
                    <Input
                        type="number"
                        min={0}
                        value={feeBps}
                        onChange={(event) => setFeeBps(Number(event.target.value))}
                        controlSize="sm"
                    />
                </label>
                <label className="space-y-1">
                    <span className="text-[10px] uppercase tracking-wider text-zinc-400">Partial Fill %</span>
                    <Input
                        type="number"
                        min={1}
                        max={100}
                        value={Math.round(partialFillPct * 100)}
                        onChange={(event) => setPartialFillPct(Math.max(0.01, Math.min(1, Number(event.target.value) / 100)))}
                        controlSize="sm"
                    />
                </label>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3">
                <label className="space-y-1">
                    <span className="text-[10px] uppercase tracking-wider text-zinc-400">Signal Fill Timing</span>
                    <Select
                        value={fillOnNextBar ? 'next_open' : 'same_close'}
                        onChange={(event) => setFillOnNextBar(event.target.value === 'next_open')}
                        controlSize="sm"
                        options={[
                            { value: 'next_open', label: 'Next bar open' },
                            { value: 'same_close', label: 'Same bar close' },
                        ]}
                    />
                </label>
                <label className="space-y-1">
                    <span className="text-[10px] uppercase tracking-wider text-zinc-400">Intra-candle Conflict</span>
                    <Select
                        value={intraCandlePolicy}
                        onChange={(event) => setIntraCandlePolicy(event.target.value as BacktestIntraCandlePolicy)}
                        controlSize="sm"
                        options={[
                            { value: 'ohlc_path', label: 'OHLC path' },
                            { value: 'stop_loss_first', label: 'Stop-loss first' },
                            { value: 'take_profit_first', label: 'Take-profit first' },
                        ]}
                    />
                </label>
                <label className="space-y-1">
                    <span className="text-[10px] uppercase tracking-wider text-zinc-400">Trigger Resolution</span>
                    <Select
                        value={triggerTimeframe}
                        onChange={(event) => setTriggerTimeframe(event.target.value as BacktestTriggerTimeframe)}
                        controlSize="sm"
                        options={[
                            { value: '1m', label: '1m trigger candles' },
                            { value: 'off', label: 'Base timeframe only' },
                        ]}
                    />
                </label>
                <label className="space-y-1">
                    <span className="text-[10px] uppercase tracking-wider text-zinc-400">End-of-Window Position Handling</span>
                    <Select
                        value={forceCloseAtWindowEnd ? 'force_close' : 'open_at_end'}
                        onChange={(event) => setForceCloseAtWindowEnd(event.target.value === 'force_close')}
                        controlSize="sm"
                        options={[
                            { value: 'open_at_end', label: 'Mark as OPEN_AT_END (Default)' },
                            { value: 'force_close', label: 'Force close at last candle' },
                        ]}
                    />
                </label>
                <div className="rounded-lg border border-white/10 bg-zinc-900/70 px-3 py-2">
                    <p className="text-[10px] uppercase tracking-wider text-zinc-500">Replay Semantics</p>
                    <p className="text-[11px] text-zinc-300 mt-1">
                        No trades occur before <span className="font-semibold">{fromDate}</span>. Warm-up candles are still loaded before the replay window.
                    </p>
                </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-3 items-end">
                <label className="space-y-1">
                    <span className="text-[10px] uppercase tracking-wider text-zinc-400">Historical Data Type</span>
                    <Select
                        value={sourceType}
                        onChange={(event) => {
                            setSourceType(event.target.value as SourceType);
                            if (event.target.value === 'kraken') {
                                setSourcePayload({ exchange: 'kraken' });
                                setSourceName('Kraken historical API');
                            } else {
                                setSourcePayload(null);
                                setSourceName('');
                            }
                        }}
                        controlSize="sm"
                        options={[
                            { value: 'csv', label: 'CSV' },
                            { value: 'json', label: 'JSON' },
                            { value: 'replay', label: 'Replay JSON' },
                            { value: 'kraken', label: 'Kraken Historical API' },
                        ]}
                    />
                </label>
                {sourceType === 'kraken' ? (
                    <label className="space-y-1">
                        <span className="text-[10px] uppercase tracking-wider text-zinc-400">Kraken Warm-up Lookback Candles</span>
                        <Input
                            type="number"
                            min={100}
                            value={krakenLookbackCandles}
                            onChange={(event) => setKrakenLookbackCandles(Math.max(100, Number(event.target.value || 0)))}
                            controlSize="sm"
                        />
                    </label>
                ) : (
                    <label className="space-y-1">
                        <span className="text-[10px] uppercase tracking-wider text-zinc-400">Upload Historical File</span>
                        <Input
                            type="file"
                            accept={sourceType === 'csv' ? '.csv,text/csv' : '.json,application/json'}
                            onChange={async (event) => {
                                try {
                                    const file = event.target.files?.[0];
                                    if (!file) return;
                                    await readFile(file);
                                } catch (uploadError: any) {
                                    setError(uploadError.message || 'Failed to read file');
                                }
                            }}
                            controlSize="sm"
                        />
                    </label>
                )}
            </div>

            <div className="text-[11px] text-zinc-500">
                Uploaded source: <span className="text-zinc-300">{sourceName || 'none'}</span>
            </div>

            {error && (
                <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-xs text-red-300">
                    {error}
                </div>
            )}

            <Button
                type="button"
                onClick={() => { void handleRun(); }}
                disabled={running}
                className="w-full"
                size="lg"
            >
                {running ? 'Running Backtest...' : 'Run Backtest'}
            </Button>
        </div>
    );
};
