import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it, vi } from 'vitest';
import type { BotState } from '../hooks/useWebSocket';
import { AlertFeed } from './AlertFeed';
import { TopVolatile, AISetups } from './MarketOpportunities';
import { MarketTicker } from './MarketTicker';
import { Login } from './Login';
import { ResetPassword } from './ResetPassword';
import { GlobalConfigManager } from './GlobalConfigManager';
import { EntryForm } from './EntryForm';
import { SymbolCard } from './SymbolCard';

vi.mock('../components/AuthContext', () => ({
    useAuth: () => ({
        user: { id: 'user-1' },
        profile: { role: 'admin' }
    })
}));

vi.mock('../lib/tradingAuth', () => ({
    useTradingAuth: () => ({
        login: vi.fn(async () => true),
        register: vi.fn(async () => true),
        error: null,
    })
}));

vi.mock('../lib/supabaseClient', () => {
    const query: any = {
        select: vi.fn(() => query),
        order: vi.fn(() => query),
        eq: vi.fn(() => query),
        single: vi.fn(() => Promise.resolve({ data: null, error: null })),
        insert: vi.fn(() => Promise.resolve({ error: null })),
        update: vi.fn(() => query),
        upsert: vi.fn(() => Promise.resolve({ error: null })),
        delete: vi.fn(() => query)
    };

    return {
        supabase: {
            from: vi.fn(() => query),
            auth: {
                getSession: vi.fn(async () => ({ data: { session: null } })),
                signInWithPassword: vi.fn(async () => ({ error: null })),
                signUp: vi.fn(async () => ({ error: null })),
                resetPasswordForEmail: vi.fn(async () => ({ error: null })),
                updateUser: vi.fn(async () => ({ error: null }))
            }
        }
    };
});

vi.mock('./PriceChart', () => ({
    PriceChart: () => React.createElement('div', null, 'PriceChartMock')
}));

const botState: BotState = {
    symbols: {
        'BTC/USDT': {
            price: 70000,
            change24h: 1.1,
            changeToday: 0.3,
            session: 'NY',
            volatility: 'High',
            signal: 'BUY',
            signalTime: Date.now() - 120000,
            tradingMode: 'Paper',
            activePosition: null,
            priceHistory: [],
            rules: {
                TrendBiasRule: { passed: true, reason: 'ok' },
                AIAnalysisRule: { passed: true, reason: 'ok', metadata: { confidence: 82, reasoning: 'Positive flow' } }
            },
            profileSignals: {
                p1: {
                    profileName: 'High Risk Scalper',
                    signal: 'BUY',
                    passed: true,
                    reason: 'rules passed'
                }
            },
            indicators: {
                rsi_15m: 54.2,
                rsi_1h: 58.9,
                ema20_15m: 69900,
                ema20_1h: 69800
            }
        },
        'ETH/USDT': {
            price: 3200,
            change24h: -2.1,
            changeToday: -1.2,
            session: 'London',
            volatility: 'Medium',
            signal: 'SELL',
            activePosition: null,
            priceHistory: [],
            rules: {
                TrendBiasRule: { passed: false, reason: 'downtrend' }
            },
            indicators: {
                ema50_4h: 3300,
                ema200_4h: 3400,
                rsi_1h: 42
            }
        }
    },
    alerts: [],
    positions: [],
    orders: [],
    history: [],
    settings: {
        executionMode: 'Paper',
        riskPerTrade: 0.01,
        totalCapital: 12000,
        maxOpenTrades: 5,
        isAlgoEnabled: true,
        enabledRules: ['TrendBiasRule']
    },
    uptime: 100000
};

describe('component smoke coverage', () => {
    it('renders alert feed with relative timing and message', () => {
        const html = renderToStaticMarkup(
            React.createElement(AlertFeed, {
                alerts: [
                    {
                        timestamp: Date.now() - 60000,
                        type: 'signal',
                        symbol: 'BTC/USDT',
                        message: 'Breakout detected'
                    }
                ]
            })
        );

        expect(html).toContain('Recent Activity');
        expect(html).toContain('BTC/USDT');
        expect(html).toContain('Breakout detected');
    });

    it('renders market opportunity and ticker components', () => {
        const volatileHtml = renderToStaticMarkup(React.createElement(TopVolatile, { botState }));
        expect(volatileHtml).toContain('Top Volatile');
        expect(volatileHtml).toContain('BTC/USDT');

        const aiHtml = renderToStaticMarkup(React.createElement(AISetups, { botState }));
        expect(aiHtml).toContain('Best AI Setups');
        expect(aiHtml).toContain('82% Conf');

        const tickerHtml = renderToStaticMarkup(React.createElement(MarketTicker, { botState }));
        expect(tickerHtml).toContain('Market Ticker');
        expect(tickerHtml).toContain('2 Assets Active');
    });

    it('renders auth and config shells', () => {
        const loginHtml = renderToStaticMarkup(React.createElement(Login));
        expect(loginHtml).toContain('Trading Dashboard');
        expect(loginHtml).toContain('Sign in to access bot controls');

        const resetHtml = renderToStaticMarkup(React.createElement(ResetPassword));
        expect(resetHtml).toContain('Reset Password');
        expect(resetHtml).toContain('Update Password');

        const configHtml = renderToStaticMarkup(React.createElement(GlobalConfigManager));
        expect(configHtml).toContain('Loading system configuration');
    });

    it('renders entry form and symbol card details', () => {
        const entryHtml = renderToStaticMarkup(
            React.createElement(EntryForm, {
                onSuccess: vi.fn(),
                initialData: {
                    stock_instance_id: 'entry-1',
                    symbol: 'BTC/USDT',
                    quantity: '0.1',
                    buy_price: '69000',
                    sell_price: '70000'
                }
            })
        );

        expect(entryHtml).toContain('BTC/USD');
        expect(entryHtml).toContain('Update');

        const symbolHtml = renderToStaticMarkup(
            React.createElement(SymbolCard, {
                symbol: 'BTC/USDT',
                data: {
                    ...botState.symbols['BTC/USDT'],
                    activePosition: {
                        side: 'BUY',
                        entryPrice: 69000,
                        size: 0.1,
                        stopLoss: 68000,
                        takeProfit: 71000,
                        unrealizedPnl: 10,
                        unrealizedPnlPercent: 1.45,
                        marketValue: 7000
                    }
                }
            })
        );

        expect(symbolHtml).toContain('Profile Signals');
        expect(symbolHtml).toContain('ACTIVE BUY');
        expect(symbolHtml).toContain('PriceChartMock');
        expect(symbolHtml).toContain('Confidence: 82%');
    });
});
