import { useEffect, useMemo, useState } from 'react';
import { useAuth } from '../components/AuthContext';
import type { BacktestRuntimeFlags } from './flags';
import { isBacktestBuildEnabled, loadBacktestRuntimeFlags } from './flags';

interface UseBacktestFeatureGateOptions {
    previewAsCustomer?: boolean;
}

interface BacktestFeatureGateState {
    enabled: boolean;
    loading: boolean;
    buildEnabled: boolean;
    isAdminView: boolean;
    runtimeFlags: BacktestRuntimeFlags;
}

const DISABLED_FLAGS: BacktestRuntimeFlags = {
    enableBacktest: false,
    customerEnabled: false
};

export const useBacktestFeatureGate = (
    options: UseBacktestFeatureGateOptions = {}
): BacktestFeatureGateState => {
    const { previewAsCustomer = false } = options;
    const { profile } = useAuth();
    const buildEnabled = isBacktestBuildEnabled();
    const isAdminView = profile?.role === 'admin' && !previewAsCustomer;
    const [runtimeFlags, setRuntimeFlags] = useState<BacktestRuntimeFlags>(DISABLED_FLAGS);
    const [loading, setLoading] = useState<boolean>(buildEnabled);

    useEffect(() => {
        let cancelled = false;
        if (!buildEnabled) {
            setRuntimeFlags(DISABLED_FLAGS);
            setLoading(false);
            return () => {
                cancelled = true;
            };
        }

        setLoading(true);
        void loadBacktestRuntimeFlags()
            .then((flags) => {
                if (!cancelled) {
                    setRuntimeFlags(flags);
                }
            })
            .catch(() => {
                if (!cancelled) {
                    setRuntimeFlags(DISABLED_FLAGS);
                }
            })
            .finally(() => {
                if (!cancelled) {
                    setLoading(false);
                }
            });

        return () => {
            cancelled = true;
        };
    }, [buildEnabled]);

    const enabled = useMemo(() => {
        if (!buildEnabled) return false;
        if (!runtimeFlags.enableBacktest) return false;
        if (isAdminView) return true;
        return runtimeFlags.customerEnabled;
    }, [buildEnabled, runtimeFlags, isAdminView]);

    return {
        enabled,
        loading,
        buildEnabled,
        isAdminView,
        runtimeFlags
    };
};
