import React, { useState } from 'react';
import {
    ShieldCheck,
    Scale,
    Zap,
    DollarSign,
    Clock,
    ChevronRight,
    ChevronLeft,
    CheckCircle2,
    AlertTriangle,
    Info,
    Wallet,
    Target,
    Lock
} from 'lucide-react';
import { RISK_STYLE_TEMPLATES } from '../lib/RiskStyleTemplates';
import type { RiskStyleTemplate } from '../lib/RiskStyleTemplates';
import { getUserTier, TIER_POLICIES, isFeatureAllowed } from '../lib/TierPolicy';
import { useAuth } from './AuthContext';
import { BacktestRunnerPanel } from '../backtest/components/BacktestRunnerPanel';
import { useBacktestFeatureGate } from '../backtest/useBacktestFeatureGate';
import { createTradeProfile, updateTradeProfile } from '../lib/profileApi';
import { Button } from './ui/button';
import { Card } from './ui/card';
import { Input } from './ui/input';

interface WizardState {
    step: number;
    riskStyle: RiskStyleTemplate | null;
    assets: string[];
    capital: number;
    profitTarget: number;
    hours: '24/7' | 'London + New York' | 'Asia only';
}

const ASSETS = [
    { id: 'BTC/USDT', label: 'Bitcoin (BTC)' },
    { id: 'ETH/USDT', label: 'Ethereum (ETH)' },
    { id: 'SOL/USDT', label: 'Solana (SOL)' },
];

const SESSION_MAP = {
    '24/7': 'LDN,NY,TOK,SYD',
    'London + New York': 'LDN,NY',
    'Asia only': 'TOK,SYD'
};

const sectionTitleClass = 'mb-2 text-2xl font-bold text-[var(--foreground)]';
const sectionDescriptionClass = 'text-sm text-[var(--muted-foreground)]';
const labelClass = 'text-xs font-bold uppercase tracking-widest text-[var(--muted-foreground)]';
const optionBaseClass = 'w-full rounded-2xl border-2 p-5 text-left transition-all';
const optionSelectedClass = 'border-[var(--accent)] bg-[var(--accent-soft)]';
const optionIdleClass = 'border-[var(--border)] bg-[var(--card)] hover:border-[var(--border-strong)]';

const buildStrategyConfig = (state: WizardState) => ({
    rules: [
        { ruleId: 'RiskManagementRule', enabled: true, ruleType: 'mandatory', params: {} },
        { ruleId: 'SessionRule', enabled: state.hours !== '24/7', ruleType: 'mandatory', params: { sessions: SESSION_MAP[state.hours] } },
        ...((state.riskStyle?.mandatoryRules || [])
            .filter((ruleId) => !['RiskManagementRule', 'SessionRule'].includes(ruleId))
            .map((ruleId) => ({ ruleId, enabled: true, ruleType: 'mandatory', params: {} }))),
        ...((state.riskStyle?.votingRules || []).map((ruleId) => ({ ruleId, enabled: true, ruleType: 'voting', params: {} })))
    ],
    riskLimits: {
        maxDailyLossUsd: Math.floor(state.capital * 0.05),
        dailyProfitTargetUsd: state.profitTarget,
        maxOpenTrades: 3,
        maxConsecutiveLosses: 3
    },
    execution: {
        orderType: 'market',
        cooldownMinutes: 60,
        minRulePassRatio: state.riskStyle?.minRulePassRatio || 1,
        entryMode: 'both'
    }
});

export const StrategyWizard: React.FC<{
    onComplete: () => void;
    editingProfile?: any;
    profile?: any;
    previewAsCustomer?: boolean;
}> = ({ onComplete, editingProfile, profile: userProfile, previewAsCustomer = false }) => {
    const { user } = useAuth();
    const tier = getUserTier(userProfile);
    const policy = TIER_POLICIES[tier];

    // Initialize state from existing profile if editing
    const getInitialState = (): WizardState => {
        if (editingProfile) {
            const config = editingProfile.strategy_config;
            const passRatio = config?.execution?.minRulePassRatio || 1.0;
            const style = RISK_STYLE_TEMPLATES.find(t => t.minRulePassRatio === passRatio) || RISK_STYLE_TEMPLATES[1];

            let hours: WizardState['hours'] = '24/7';
            const sessions = config?.rules?.find((r: any) => r.ruleId === 'SessionRule')?.params?.sessions;
            if (sessions === 'LDN,NY') hours = 'London + New York';
            if (sessions === 'TOK,SYD') hours = 'Asia only';

            return {
                step: 1,
                riskStyle: style,
                assets: String(editingProfile.symbols).split(','),
                capital: editingProfile.allocated_capital,
                profitTarget: config?.riskLimits?.dailyProfitTargetUsd || 100,
                hours
            };
        }
        return {
            step: 1,
            riskStyle: null,
            assets: ['BTC/USDT'],
            capital: 1000,
            profitTarget: 100,
            hours: '24/7'
        };
    };

    const [state, setState] = useState<WizardState>(getInitialState());
    const [loading, setLoading] = useState(false);
    const [showBacktest, setShowBacktest] = useState(false);
    const { enabled: backtestEnabled, loading: backtestGateLoading } = useBacktestFeatureGate({ previewAsCustomer });

    const next = () => setState(s => ({ ...s, step: s.step + 1 }));
    const back = () => setState(s => ({ ...s, step: s.step - 1 }));

    const handleSave = async () => {
        if (!user || !state.riskStyle) return;
        setLoading(true);

        const strategy_config = buildStrategyConfig(state);

        const payload = {
            name: editingProfile?.name || `${state.riskStyle.label.split(' ')[1]} Bot (${state.assets.join(',')})`,
            user_id: user.id,
            allocated_capital: state.capital,
            risk_per_trade_percent: state.riskStyle.riskPerTrade,
            symbols: state.assets.join(','),
            is_active: editingProfile ? editingProfile.is_active : false, // Preserve status if editing
            strategy_config
        };

        let result;
        if (editingProfile) {
            result = await updateTradeProfile(editingProfile.id, payload).then(() => ({ error: null as any })).catch((error) => ({ error }));
        } else {
            result = await createTradeProfile(payload).then(() => ({ error: null as any })).catch((error) => ({ error }));
        }

        setLoading(false);

        if (result.error) {
            alert('Error saving strategy: ' + result.error.message);
        } else {
            onComplete();
        }
    };

    return (
        <div className="mx-auto max-w-3xl px-4 py-8">
            {/* Progress Bar */}
            <div className="relative mb-12 flex justify-between">
                <div className="absolute left-0 top-1/2 z-0 h-0.5 w-full -translate-y-1/2 bg-[var(--border)]" />
                {[1, 2, 3, 4, 5].map(i => (
                    <div
                        key={i}
                        className={`relative z-10 flex h-10 w-10 items-center justify-center rounded-full text-sm font-bold transition-all duration-300 ${state.step >= i ? 'scale-110 bg-[var(--primary)] text-[var(--primary-foreground)]' : 'border border-[var(--border)] bg-[var(--card)] text-[var(--muted-foreground)]'
                            }`}
                    >
                        {state.step > i ? <CheckCircle2 size={18} /> : i}
                    </div>
                ))}
            </div>

            {/* Step 1: Risk Style */}
            {state.step === 1 && (
                <div className="space-y-6 animate-in fade-in slide-in-from-bottom-4 duration-500">
                    <div className="mb-8 text-center">
                        <h2 className={sectionTitleClass}>How should this bot behave?</h2>
                        <p className={sectionDescriptionClass}>Select a pre-configured risk style. High-frequency options seek more opportunities but require more flexibility.</p>
                    </div>
                    <div className="grid grid-cols-1 gap-4">
                        {RISK_STYLE_TEMPLATES.map(style => {
                            const isLocked = !isFeatureAllowed(tier, 'risk_style', style.id);
                            return (
                                <div key={style.id} className="relative">
                                    <button
                                        disabled={isLocked}
                                        onClick={() => setState({ ...state, riskStyle: style })}
                                        className={`${optionBaseClass} ${isLocked ? 'cursor-not-allowed opacity-40 grayscale' : 'hover:scale-[1.01] active:scale-[0.99]'
                                            } ${state.riskStyle?.id === style.id
                                                ? optionSelectedClass
                                                : optionIdleClass
                                            }`}
                                    >
                                        <div className="flex items-start gap-4">
                                            <div className={`w-12 h-12 rounded-xl flex items-center justify-center ${style.id === 'safe' ? 'bg-blue-500/10 text-blue-400' :
                                                style.id === 'balanced' ? 'bg-[var(--accent-soft)] text-[var(--accent)]' : 'bg-orange-500/10 text-orange-400'
                                                }`}>
                                                {style.id === 'safe' ? <ShieldCheck size={24} /> : style.id === 'balanced' ? <Scale size={24} /> : <Zap size={24} />}
                                            </div>
                                            <div className="flex-1">
                                                <div className="flex justify-between items-center mb-1">
                                                    <span className="flex items-center gap-2 text-lg font-bold text-[var(--foreground)]">
                                                        {style.label}
                                                        {isLocked && <Lock size={14} className="text-[var(--muted-foreground)]" />}
                                                    </span>
                                                    <span className="text-[10px] uppercase tracking-widest font-black opacity-40">{style.tradeFrequency}</span>
                                                </div>
                                                <p className="text-sm leading-relaxed text-[var(--muted-foreground)]">{style.description}</p>
                                            </div>
                                        </div>
                                    </button>
                                    {isLocked && (
                                        <div className="absolute top-4 right-4 text-[9px] font-black uppercase text-amber-500/80 tracking-tighter bg-amber-500/10 px-2 py-0.5 rounded border border-amber-500/20">
                                            Pro/Elite Only
                                        </div>
                                    )}
                                </div>
                            );
                        })}
                    </div>
                    <div className="flex justify-end pt-4">
                        <Button
                            disabled={!state.riskStyle}
                            onClick={next}
                            className="px-8"
                        >
                            Continue <ChevronRight size={18} />
                        </Button>
                    </div>
                </div>
            )}

            {/* Step 2: Assets & Capital */}
            {state.step === 2 && (
                <div className="space-y-8 animate-in fade-in slide-in-from-right-4 duration-500">
                    <div className="text-center">
                        <h2 className={sectionTitleClass}>Assets & Capital</h2>
                        <p className={sectionDescriptionClass}>Define what to trade and how much capital to use.</p>
                    </div>

                    <div className="space-y-6">
                        <div className="space-y-3">
                            <label className={labelClass}>Select Trading Assets</label>
                            <div className="flex flex-wrap gap-3">
                                {ASSETS.map(asset => (
                                    <button
                                        key={asset.id}
                                        onClick={() => {
                                            const newAssets = state.assets.includes(asset.id)
                                                ? state.assets.filter(a => a !== asset.id)
                                                : [...state.assets, asset.id];
                                            if (newAssets.length > 0) setState({ ...state, assets: newAssets });
                                        }}
                                        className={`rounded-xl border-2 px-5 py-3 text-sm font-bold transition-all ${state.assets.includes(asset.id)
                                            ? 'border-[var(--accent)] bg-[var(--accent-soft)] text-[var(--foreground)]'
                                            : 'border-[var(--border)] bg-[var(--card)] text-[var(--muted-foreground)] hover:border-[var(--border-strong)]'
                                            }`}
                                    >
                                        {asset.label}
                                    </button>
                                ))}
                            </div>
                        </div>

                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div className="space-y-3">
                                <label className={labelClass}>Capital Allocation</label>
                                <div className="relative">
                                    <div className="pointer-events-none absolute inset-y-0 left-4 flex items-center text-[var(--muted-foreground)]">
                                        <DollarSign size={16} />
                                    </div>
                                    <Input
                                        type="number"
                                        value={state.capital}
                                        onChange={e => setState({ ...state, capital: Number(e.target.value) })}
                                        className="h-14 pl-10 font-bold"
                                    />
                                </div>
                                <p className="text-[10px] text-[var(--muted-foreground)]">Total USD balance this bot is allowed to manage.</p>
                            </div>

                            <div className="space-y-3">
                                <label className="flex items-center justify-between text-xs font-bold uppercase tracking-widest text-[var(--muted-foreground)]">
                                    Daily Profit Target
                                    {!isFeatureAllowed(tier, 'profit_target', policy.maxDailyProfitTargetUsd + 1) && (
                                        <span className="text-[9px] text-amber-500 flex items-center gap-1"><Lock size={10} /> Limited to ${policy.maxDailyProfitTargetUsd}</span>
                                    )}
                                </label>
                                <div className="relative">
                                    <div className="pointer-events-none absolute inset-y-0 left-4 flex items-center text-[var(--muted-foreground)]">
                                        <Target size={16} />
                                    </div>
                                    <Input
                                        type="number"
                                        disabled={tier === 'free'}
                                        value={state.profitTarget}
                                        onChange={e => {
                                            const val = Number(e.target.value);
                                            if (isFeatureAllowed(tier, 'profit_target', val)) {
                                                setState({ ...state, profitTarget: val });
                                            }
                                        }}
                                        className={`h-14 pl-10 font-bold ${tier === 'free' ? 'cursor-not-allowed opacity-50' : ''}`}
                                    />
                                </div>
                                <div className="flex gap-2 items-start mt-1">
                                    <Info size={12} className="mt-0.5 shrink-0 text-[var(--accent)]" />
                                    <p className="text-[10px] italic text-[var(--muted-foreground)]">Once this profit is reached, the bot automatically pauses for the day to lock in gains.</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div className="flex justify-between pt-4">
                        <Button onClick={back} variant="ghost" className="px-6">
                            <ChevronLeft size={18} /> Back
                        </Button>
                        <Button onClick={next} className="px-8">
                            Continue <ChevronRight size={18} />
                        </Button>
                    </div>
                </div>
            )}

            {/* Step 3: Trading Hours */}
            {state.step === 3 && (
                <div className="space-y-8 animate-in fade-in slide-in-from-right-4 duration-500">
                    <div className="text-center">
                        <h2 className={sectionTitleClass}>Trading Hours</h2>
                        <p className={sectionDescriptionClass}>When should the bot look for signals?</p>
                    </div>

                    <div className="grid grid-cols-1 gap-4">
                        {(['24/7', 'London + New York', 'Asia only'] as const).map(option => (
                            <button
                                key={option}
                                onClick={() => setState({ ...state, hours: option })}
                                className={`rounded-2xl border-2 p-6 text-left transition-all ${state.hours === option
                                    ? optionSelectedClass
                                    : optionIdleClass
                                    }`}
                            >
                                <div className="flex items-center gap-4">
                                    <div className={`flex h-10 w-10 items-center justify-center rounded-lg ${state.hours === option ? 'bg-[var(--accent-soft)] text-[var(--accent)]' : 'bg-[var(--muted)] text-[var(--muted-foreground)]'}`}>
                                        <Clock size={20} />
                                    </div>
                                    <div>
                                        <span className="block text-lg font-bold text-[var(--foreground)]">{option}</span>
                                        <span className="text-xs text-[var(--muted-foreground)]">
                                            {option === '24/7' ? 'Universal coverage, trades any time signals appear.' :
                                                option === 'London + New York' ? 'Focuses on the most liquid market overlap (07:00 - 21:00 UTC).' :
                                                    'Optimized for Tokoyo and Sydney sessions.'}
                                        </span>
                                    </div>
                                </div>
                            </button>
                        ))}
                    </div>

                    <div className="flex justify-between pt-4">
                        <Button onClick={back} variant="ghost" className="px-6">
                            <ChevronLeft size={18} /> Back
                        </Button>
                        <Button onClick={next} className="px-8">
                            Continue <ChevronRight size={18} />
                        </Button>
                    </div>
                </div>
            )}

            {/* Step 4: Safety Confirmation */}
            {state.step === 4 && (
                <div className="space-y-8 animate-in fade-in slide-in-from-right-4 duration-500">
                    <div className="text-center">
                        <h2 className={sectionTitleClass}>Safety Confirmation</h2>
                        <p className={sectionDescriptionClass}>Review the built-in safeguards protecting your capital.</p>
                    </div>

                    <Card className="overflow-hidden rounded-2xl">
                        <div className="p-6 space-y-4">
                            <div className="flex items-center justify-between border-b border-[var(--border)] py-3">
                                <span className="text-sm font-medium text-[var(--muted-foreground)]">Auto-Protective Stop Loss</span>
                                <span className="text-sm font-bold text-[var(--accent)]">Enabled (Mandatory)</span>
                            </div>
                            <div className="flex items-center justify-between border-b border-[var(--border)] py-3">
                                <span className="text-sm font-medium text-[var(--muted-foreground)]">Position Sizing Limit</span>
                                <span className="font-mono text-sm font-bold text-[var(--foreground)]">Max {state.riskStyle?.riskPerTrade}% per trade</span>
                            </div>
                            <div className="flex items-center justify-between border-b border-[var(--border)] py-3">
                                <span className="text-sm font-medium text-[var(--muted-foreground)]">Daily Recovery Halt</span>
                                <span className="text-rose-400 text-sm font-bold font-mono">-${Math.floor(state.capital * 0.05)} (5%)</span>
                            </div>
                            <div className="flex items-center justify-between py-3">
                                <span className="text-sm font-medium text-[var(--muted-foreground)]">Market Volatility Guard</span>
                                <span className="text-blue-400 text-sm font-bold">Smart ATR Check</span>
                            </div>
                        </div>
                        <div className="bg-amber-500/10 border-t border-amber-500/20 p-5 flex gap-4">
                            <AlertTriangle className="text-amber-500 shrink-0" size={20} />
                            <p className="text-xs text-amber-500/90 leading-relaxed font-medium">
                                Risk management and safety rules are coded into the engine core. These cannot be disabled or bypassed, ensuring your bot always operates within safety boundaries.
                            </p>
                        </div>
                    </Card>

                    <div className="flex justify-between pt-4">
                        <Button onClick={back} variant="ghost" className="px-6">
                            <ChevronLeft size={18} /> Back
                        </Button>
                        <Button onClick={next} className="px-8">
                            I Understand <ChevronRight size={18} />
                        </Button>
                    </div>
                </div>
            )}

            {/* Step 5: Review & Create */}
            {state.step === 5 && (
                <div className="space-y-8 animate-in fade-in zoom-in-95 duration-500">
                    <div className="text-center">
                        <h2 className="mb-2 text-3xl font-bold text-[var(--foreground)]">Ready to Deploy</h2>
                        <p className={sectionDescriptionClass}>Verify your bot strategy one last time.</p>
                    </div>

                    <Card className="relative space-y-6 overflow-hidden rounded-3xl border-[var(--border-strong)] p-8">
                        <div className="flex items-center gap-6">
                            <div className="flex h-20 w-20 items-center justify-center rounded-2xl bg-[var(--primary)] text-[var(--primary-foreground)]">
                                {state.riskStyle?.id === 'safe' ? <ShieldCheck size={40} /> : state.riskStyle?.id === 'balanced' ? <Scale size={40} /> : <Zap size={40} />}
                            </div>
                            <div>
                                <h3 className="text-2xl font-bold text-[var(--foreground)]">{state.riskStyle?.label} Bot</h3>
                                <div className="flex gap-2 mt-1">
                                    {state.assets.map(a => (
                                        <span key={a} className="rounded border border-[var(--border)] bg-[var(--muted)] px-2 py-0.5 text-[10px] font-black text-[var(--muted-foreground)]">{a.split('/')[0]}</span>
                                    ))}
                                </div>
                            </div>
                        </div>

                        <div className="grid grid-cols-2 gap-8 pt-4">
                            <div className="space-y-1">
                                <span className="text-[10px] font-black uppercase tracking-widest text-[var(--muted-foreground)]">Target Capital</span>
                                <div className="flex items-baseline gap-1 text-xl font-bold text-[var(--foreground)]">
                                    <span className="text-sm opacity-50 opacity-40">$</span>{state.capital}
                                </div>
                            </div>
                            <div className="space-y-1">
                                <span className="text-[10px] font-black uppercase tracking-widest text-[var(--muted-foreground)]">Profit Threshold</span>
                                <div className="flex items-baseline gap-1 text-xl font-bold text-[var(--accent)]">
                                    <span className="text-sm opacity-40">$</span>{state.profitTarget}<span className="text-[10px] opacity-60 ml-1">/day</span>
                                </div>
                            </div>
                            <div className="space-y-1">
                                <span className="text-[10px] font-black uppercase tracking-widest text-[var(--muted-foreground)]">Risk Level</span>
                                <div className="text-xl font-bold text-[var(--foreground)]">{(state.riskStyle?.riskPerTrade || 0)}% <span className="text-xs font-normal opacity-50">per trade</span></div>
                            </div>
                            <div className="space-y-1">
                                <span className="text-[10px] font-black uppercase tracking-widest text-[var(--muted-foreground)]">Active Schedule</span>
                                <div className="text-xl font-bold text-[var(--foreground)]">{state.hours}</div>
                            </div>
                        </div>

                        <div className="flex items-center gap-4 border-t border-[var(--border)] pt-6">
                            <div className="flex h-12 w-12 items-center justify-center rounded-full border border-[var(--border)] text-[var(--muted-foreground)]">
                                <Wallet size={20} />
                            </div>
                            <div className="flex-1">
                                <p className="text-sm text-[var(--muted-foreground)]">Bots are created in <span className="font-bold text-[var(--foreground)]">PAUSED</span> mode by default. You must manually enable trading from your dashboard.</p>
                            </div>
                        </div>
                    </Card>

                    <div className="flex justify-between pt-4">
                        <Button onClick={back} variant="ghost" className="px-6">
                            <ChevronLeft size={18} /> Back
                        </Button>
                        <div className="flex items-center gap-3">
                            {!backtestGateLoading && backtestEnabled && (
                                <Button
                                    type="button"
                                    onClick={() => setShowBacktest((prev) => !prev)}
                                    variant="outline"
                                    className="px-5 text-xs uppercase tracking-wider"
                                >
                                    {showBacktest ? 'Hide Backtest' : 'Run Backtest'}
                                </Button>
                            )}
                            <Button
                                disabled={loading}
                                onClick={handleSave}
                                size="lg"
                                className="group rounded-2xl px-12 text-lg font-black"
                            >
                                {loading ? 'Processing...' : (
                                    <>
                                        DEPLOY STRATEGY
                                        <ChevronRight size={20} className="group-hover:translate-x-1 transition-transform" />
                                    </>
                                )}
                            </Button>
                        </div>
                    </div>

                    {!backtestGateLoading && backtestEnabled && showBacktest && (
                        <div className="pt-6">
                            <BacktestRunnerPanel
                                strategyConfig={buildStrategyConfig(state)}
                                symbols={state.assets}
                                initialCapitalUsd={state.capital}
                                title="Pre-Deploy Backtest"
                                onClose={() => setShowBacktest(false)}
                            />
                        </div>
                    )}
                </div>
            )}
        </div>
    );
};
