import React, { useEffect, useMemo, useState } from 'react';
import { useAuth } from '../components/AuthContext';
import { BacktestRunnerPanel } from '../backtest/components/BacktestRunnerPanel';
import { BacktestComparePanel } from '../backtest/components/BacktestComparePanel';
import { useBacktestFeatureGate } from '../backtest/useBacktestFeatureGate';
import { fetchTradeProfiles } from '../lib/profileApi';

interface BacktestTabProps {
    previewAsCustomer?: boolean;
}

export const BacktestTab: React.FC<BacktestTabProps> = ({ previewAsCustomer = false }) => {
    const { user, profile } = useAuth();
    const [profiles, setProfiles] = useState<any[]>([]);
    const [loadingProfiles, setLoadingProfiles] = useState(true);
    const [selectedProfileId, setSelectedProfileId] = useState<string>('');
    const [mode, setMode] = useState<'single' | 'compare'>('single');
    const {
        enabled: backtestEnabled,
        loading: backtestGateLoading,
        isAdminView,
        runtimeFlags
    } = useBacktestFeatureGate({ previewAsCustomer });

    useEffect(() => {
        const fetchProfiles = async () => {
            if (!user) {
                setProfiles([]);
                setLoadingProfiles(false);
                return;
            }
            setLoadingProfiles(true);
            try {
                const data = await fetchTradeProfiles();
                const nextProfiles = data || [];
                setProfiles(nextProfiles);
                if (!nextProfiles.find((item: any) => item.id === selectedProfileId)) {
                    setSelectedProfileId(nextProfiles[0]?.id || '');
                }
            } catch (error) {
                console.error('[BacktestTab] Failed to fetch profiles:', error);
                setProfiles([]);
            }
            setLoadingProfiles(false);
        };

        void fetchProfiles();
        const handleProfilesUpdated = () => {
            void fetchProfiles();
        };
        window.addEventListener('profiles-updated', handleProfilesUpdated);
        return () => window.removeEventListener('profiles-updated', handleProfilesUpdated);
    }, [user]);

    const selectedProfile = useMemo(
        () => profiles.find((item) => item.id === selectedProfileId) || null,
        [profiles, selectedProfileId]
    );
    const compareProfiles = useMemo(() => (
        profiles.map((item) => ({
            id: String(item.id),
            name: String(item.name || 'Unnamed Strategy'),
            symbols: String(item.symbols || ''),
            strategy_config: item.strategy_config,
            allocated_capital: Number(item.allocated_capital || 0)
        }))
    ), [profiles]);

    const isAdminAccount = profile?.role === 'admin';
    const showAccessPanel = isAdminView || !backtestEnabled;

    return (
        <div style={{ maxWidth: '1200px', margin: '0 auto', padding: '0 20px 60px 20px' }}>
            <div style={{ marginBottom: '24px' }}>
                <h2 style={{ color: 'white', fontWeight: 900, letterSpacing: '-0.02em', marginBottom: '6px' }}>
                    Backtesting
                </h2>
                <p style={{ color: '#8b8b95', fontSize: '13px', margin: 0 }}>
                    Deterministic historical simulation. No real or paper orders are placed.
                </p>
            </div>

            {showAccessPanel && (
                <div
                    style={{
                        marginBottom: '16px',
                        padding: '14px 16px',
                        borderRadius: '14px',
                        background: 'rgba(17,24,39,0.45)',
                        border: '1px solid rgba(148,163,184,0.22)'
                    }}
                >
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px', marginBottom: '10px' }}>
                        <span style={{ fontSize: '11px', color: '#d1d5db', fontWeight: 700 }}>
                            Role: {isAdminAccount ? 'admin' : 'customer'}
                        </span>
                        <span style={{ fontSize: '11px', color: '#d1d5db', fontWeight: 700 }}>
                            Preview Mode: {previewAsCustomer ? 'customer view' : 'off'}
                        </span>
                        <span style={{ fontSize: '11px', color: runtimeFlags.enableBacktest ? '#34d399' : '#f87171', fontWeight: 700 }}>
                            ENABLE_BACKTEST: {String(runtimeFlags.enableBacktest)}
                        </span>
                        <span style={{ fontSize: '11px', color: runtimeFlags.customerEnabled ? '#34d399' : '#f87171', fontWeight: 700 }}>
                            BACKTEST_CUSTOMER_ENABLED: {String(runtimeFlags.customerEnabled)}
                        </span>
                    </div>
                    {!backtestGateLoading && !backtestEnabled && (
                        <p style={{ margin: 0, fontSize: '12px', color: '#fca5a5' }}>
                            Backtest access is currently disabled for this view. Admin can enable it in Config {'>'} Backtest Access Control.
                        </p>
                    )}
                    {!backtestGateLoading && backtestEnabled && (
                        <p style={{ margin: 0, fontSize: '12px', color: '#9ca3af' }}>
                            Backtest access is enabled for this view.
                        </p>
                    )}
                </div>
            )}

            {backtestGateLoading ? (
                <div
                    style={{
                        padding: '18px',
                        borderRadius: '14px',
                        background: 'rgba(24,24,27,0.55)',
                        border: '1px solid rgba(113,113,122,0.25)',
                        color: '#a1a1aa',
                        fontSize: '12px'
                    }}
                >
                    Resolving backtest access...
                </div>
            ) : !backtestEnabled ? (
                <div
                    style={{
                        padding: '18px',
                        borderRadius: '14px',
                        background: 'rgba(127,29,29,0.22)',
                        border: '1px solid rgba(248,113,113,0.3)',
                        color: '#fecaca',
                        fontSize: '12px'
                    }}
                >
                    Backtest is disabled for this account view.
                </div>
            ) : loadingProfiles ? (
                <div
                    style={{
                        padding: '18px',
                        borderRadius: '14px',
                        background: 'rgba(24,24,27,0.55)',
                        border: '1px solid rgba(113,113,122,0.25)',
                        color: '#a1a1aa',
                        fontSize: '12px'
                    }}
                >
                    Loading strategy profiles...
                </div>
            ) : profiles.length === 0 ? (
                <div
                    style={{
                        padding: '18px',
                        borderRadius: '14px',
                        background: 'rgba(24,24,27,0.55)',
                        border: '1px solid rgba(113,113,122,0.25)',
                        color: '#a1a1aa',
                        fontSize: '12px'
                    }}
                >
                    Create a strategy profile first, then run backtests from this tab.
                </div>
            ) : (
                <div style={{ display: 'grid', gap: '12px' }}>
                    <div
                        style={{
                            display: 'inline-flex',
                            gap: '6px',
                            background: 'rgba(24,24,27,0.85)',
                            border: '1px solid rgba(148,163,184,0.25)',
                            borderRadius: '999px',
                            padding: '4px',
                            width: 'fit-content'
                        }}
                    >
                        <button
                            type="button"
                            onClick={() => setMode('single')}
                            style={{
                                border: 'none',
                                borderRadius: '999px',
                                padding: '8px 12px',
                                fontSize: '11px',
                                fontWeight: 800,
                                cursor: 'pointer',
                                background: mode === 'single' ? '#22d3ee' : 'transparent',
                                color: mode === 'single' ? '#06141b' : '#cbd5e1'
                            }}
                        >
                            Single Run
                        </button>
                        <button
                            type="button"
                            onClick={() => setMode('compare')}
                            style={{
                                border: 'none',
                                borderRadius: '999px',
                                padding: '8px 12px',
                                fontSize: '11px',
                                fontWeight: 800,
                                cursor: 'pointer',
                                background: mode === 'compare' ? '#818cf8' : 'transparent',
                                color: mode === 'compare' ? '#0f1022' : '#cbd5e1'
                            }}
                        >
                            Compare Strategies
                        </button>
                    </div>

                    {mode === 'single' ? (
                        <>
                            <label style={{ display: 'grid', gap: '6px' }}>
                                <span style={{ fontSize: '11px', color: '#9ca3af', fontWeight: 800, textTransform: 'uppercase' }}>
                                    Strategy Profile
                                </span>
                                <select
                                    value={selectedProfileId}
                                    onChange={(event) => setSelectedProfileId(event.target.value)}
                                    style={{
                                        padding: '10px 12px',
                                        borderRadius: '10px',
                                        border: '1px solid rgba(148,163,184,0.25)',
                                        background: 'rgba(24,24,27,0.85)',
                                        color: '#fff',
                                        fontSize: '12px'
                                    }}
                                >
                                    {profiles.map((item) => (
                                        <option key={item.id} value={item.id}>
                                            {item.name} ({item.symbols})
                                        </option>
                                    ))}
                                </select>
                            </label>

                            {selectedProfile && (
                                <BacktestRunnerPanel
                                    profileId={selectedProfile.id}
                                    strategyConfig={selectedProfile.strategy_config}
                                    symbols={String(selectedProfile.symbols || '')
                                        .split(',')
                                        .map((symbol) => symbol.trim())
                                        .filter(Boolean)}
                                    initialCapitalUsd={Number(selectedProfile.allocated_capital || 1000)}
                                    title={`Backtest: ${selectedProfile.name}`}
                                />
                            )}
                        </>
                    ) : (
                        <BacktestComparePanel profiles={compareProfiles} />
                    )}
                </div>
            )}
        </div>
    );
};
