import React, { useState } from 'react';
import { BacktestConfigurator } from './BacktestConfigurator';
import { BacktestResultsDashboard } from './BacktestResultsDashboard';
import { runBacktestApi } from '../api';
import type { BacktestRequestPayload, BacktestResult } from '../types';

interface BacktestRunnerPanelProps {
    profileId?: string;
    strategyConfig: any;
    symbols: string[];
    initialCapitalUsd?: number;
    title?: string;
    onClose?: () => void;
}

export const BacktestRunnerPanel: React.FC<BacktestRunnerPanelProps> = ({
    profileId,
    strategyConfig,
    symbols,
    initialCapitalUsd = 1000,
    title = 'Backtest Runner',
    onClose
}) => {
    const [running, setRunning] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [result, setResult] = useState<BacktestResult | null>(null);

    const handleRun = async (payload: BacktestRequestPayload) => {
        setRunning(true);
        setError(null);
        try {
            const nextResult = await runBacktestApi(payload);
            setResult(nextResult);
        } catch (runError: any) {
            setError(runError.message || 'Backtest run failed');
        } finally {
            setRunning(false);
        }
    };

    return (
        <div className="space-y-4 rounded-2xl border border-emerald-400/20 bg-gradient-to-br from-zinc-950 to-zinc-900 p-4">
            <div className="flex items-center justify-between gap-3">
                <div>
                    <h2 className="text-base font-black uppercase tracking-wide text-white">{title}</h2>
                    <p className="text-xs text-zinc-400">Read-only deterministic replay. No broker calls. No production table writes.</p>
                </div>
                {onClose && (
                    <button
                        onClick={onClose}
                        className="rounded-lg border border-white/10 px-3 py-1 text-[11px] font-bold uppercase tracking-wide text-zinc-300 hover:bg-white/10"
                    >
                        Close
                    </button>
                )}
            </div>

            <BacktestConfigurator
                profileId={profileId}
                strategyConfig={strategyConfig}
                initialSymbols={symbols}
                initialCapitalUsd={initialCapitalUsd}
                running={running}
                onRun={handleRun}
            />

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

            {result && <BacktestResultsDashboard result={result} />}
        </div>
    );
};

