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';
import { PageHeader } from '../components/ui/page-header';
import { Card, CardContent } from '../components/ui/card';
import { Button } from '../components/ui/button';
import { Select } from '../components/ui/select';

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' }}>
            <PageHeader
                title="Backtesting"
                description="Deterministic historical simulation. No real or paper orders are placed."
            />

            {showAccessPanel && (
                <Card style={{ marginBottom: 16 }}>
                    <CardContent style={{ padding: '14px 16px' }}>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px', marginBottom: '10px' }}>
                        <span className="stat-chip">
                            Role: {isAdminAccount ? 'admin' : 'customer'}
                        </span>
                        <span className="stat-chip">
                            Preview Mode: {previewAsCustomer ? 'customer view' : 'off'}
                        </span>
                        <span className="stat-chip" data-tone={runtimeFlags.enableBacktest ? 'success' : 'danger'}>
                            ENABLE_BACKTEST: {String(runtimeFlags.enableBacktest)}
                        </span>
                        <span className="stat-chip" data-tone={runtimeFlags.customerEnabled ? 'success' : 'danger'}>
                            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>
                    )}
                    </CardContent>
                </Card>
            )}

            {backtestGateLoading ? (
                <Card><CardContent style={{ padding: 18, color: 'var(--muted-foreground)', fontSize: 12 }}>Resolving backtest access...</CardContent></Card>
            ) : !backtestEnabled ? (
                <Card><CardContent style={{ padding: 18, color: '#DC2626', fontSize: 12 }}>Backtest is disabled for this account view.</CardContent></Card>
            ) : loadingProfiles ? (
                <Card><CardContent style={{ padding: 18, color: 'var(--muted-foreground)', fontSize: 12 }}>Loading strategy profiles...</CardContent></Card>
            ) : profiles.length === 0 ? (
                <Card><CardContent style={{ padding: 18, color: 'var(--muted-foreground)', fontSize: 12 }}>Create a strategy profile first, then run backtests from this tab.</CardContent></Card>
            ) : (
                <div style={{ display: 'grid', gap: '12px' }}>
                    <div className="pill-group">
                        <Button type="button" variant={mode === 'single' ? 'default' : 'ghost'} size="sm" onClick={() => setMode('single')}>
                            Single Run
                        </Button>
                        <Button type="button" variant={mode === 'compare' ? 'default' : 'ghost'} size="sm" onClick={() => setMode('compare')}>
                            Compare Strategies
                        </Button>
                    </div>

                    {mode === 'single' ? (
                        <>
                            <label style={{ display: 'grid', gap: '6px' }}>
                                <span style={{ fontSize: '11px', color: 'var(--muted-foreground)', fontWeight: 800, textTransform: 'uppercase' }}>
                                    Strategy Profile
                                </span>
                                <Select
                                    value={selectedProfileId}
                                    onChange={(event) => setSelectedProfileId(event.target.value)}
                                >
                                    {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>
    );
};
