import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it, vi } from 'vitest';
import type { BotState } from '../hooks/useWebSocket';
import { PositionsTab } from './PositionsTab';

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

vi.mock('../lib/supabaseClient', () => {
    const query: any = {
        select: vi.fn(() => query),
        order: vi.fn(() => query),
        eq: vi.fn(() => query),
        limit: vi.fn(() => Promise.resolve({ data: [], error: null }))
    };

    return {
        supabase: {
            from: vi.fn(() => query)
        }
    };
});

const now = Date.now();

const createBotState = (): BotState => ({
    symbols: {
        'BTC/USDT': {
            price: 70500,
            change24h: 1.4,
            changeToday: 0.6,
            session: 'NY',
            volatility: 'High',
            signal: 'BUY',
            activePosition: null,
            priceHistory: [],
            rules: {
                TrendBiasRule: { passed: true, reason: 'Aligned' }
            },
            indicators: {
                ema50_4h: 68000,
                ema200_4h: 66000,
                rsi_1h: 60
            }
        },
        'ETH/USDT': {
            price: 3200,
            change24h: 0.9,
            changeToday: 0.2,
            session: 'NY',
            volatility: 'Medium',
            signal: 'HOLD',
            activePosition: null,
            priceHistory: [],
            rules: {},
            indicators: {}
        },
        'SOL/USDT': {
            price: 55,
            change24h: 1.1,
            changeToday: 0.4,
            session: 'NY',
            volatility: 'High',
            signal: 'HOLD',
            activePosition: null,
            priceHistory: [],
            rules: {},
            indicators: {}
        },
        'DOGE/USDT': {
            price: 0.1,
            change24h: 0.4,
            changeToday: 0.1,
            session: 'NY',
            volatility: 'High',
            signal: 'HOLD',
            activePosition: null,
            priceHistory: [],
            rules: {},
            indicators: {}
        },
        'LTC/USDT': {
            price: 81,
            change24h: -0.2,
            changeToday: -0.1,
            session: 'NY',
            volatility: 'Medium',
            signal: 'HOLD',
            activePosition: null,
            priceHistory: [],
            rules: {},
            indicators: {}
        },
        'XRP/USDT': {
            price: 0.5,
            change24h: 0.3,
            changeToday: 0.1,
            session: 'NY',
            volatility: 'Medium',
            signal: 'HOLD',
            activePosition: null,
            priceHistory: [],
            rules: {},
            indicators: {}
        },
        'ADA/USDT': {
            price: 0.4,
            change24h: -0.3,
            changeToday: -0.1,
            session: 'NY',
            volatility: 'Medium',
            signal: 'HOLD',
            activePosition: null,
            priceHistory: [],
            rules: {},
            indicators: {}
        }
    },
    alerts: [],
    positions: [
        {
            id: 'open-pos',
            symbol: 'SOL/USDT',
            side: 'BUY',
            size: 1,
            entryPrice: 50,
            currentPrice: 55,
            stopLoss: 45,
            takeProfit: 60,
            unrealizedPnl: 5,
            unrealizedPnlPercent: 10,
            marketValue: 55,
            profileId: 'p1',
            profileName: 'High Risk Scalper',
            tradeId: 'T3'
        },
        {
            id: 'missing-trade-id',
            symbol: 'DOGE/USDT',
            side: 'BUY',
            size: 10,
            entryPrice: 0.1,
            currentPrice: 0.1,
            stopLoss: 0.08,
            takeProfit: 0.12,
            unrealizedPnl: 0,
            unrealizedPnlPercent: 0,
            marketValue: 1,
            profileId: 'p1',
            profileName: 'High Risk Scalper'
        },
        {
            id: 'symbol-mismatch',
            symbol: 'LTC/USDT',
            side: 'BUY',
            size: 1,
            entryPrice: 80,
            currentPrice: 81,
            stopLoss: 70,
            takeProfit: 90,
            unrealizedPnl: 1,
            unrealizedPnlPercent: 1.25,
            marketValue: 81,
            profileId: 'p1',
            profileName: 'High Risk Scalper',
            tradeId: 'T1'
        }
    ],
    orders: [
        {
            id: 'o1',
            symbol: 'BTC/USDT',
            type: 'Market',
            side: 'BUY',
            qty: 1,
            price: 100,
            status: 'filled',
            timestamp: now - 600000,
            profileId: 'p1',
            trade_id: 'T1',
            action: 'ENTRY',
            source: 'BOT'
        },
        {
            id: 'o2',
            symbol: 'BTC/USDT',
            type: 'Market',
            side: 'SELL',
            qty: 1,
            price: 110,
            status: 'filled',
            timestamp: now - 590000,
            profileId: 'p1',
            trade_id: 'T1',
            action: 'EXIT',
            source: 'BOT'
        },
        {
            id: 'o3',
            symbol: 'ETH/USDT',
            type: 'Market',
            side: 'BUY',
            qty: 2,
            price: 200,
            status: 'filled',
            timestamp: now - 580000,
            profileId: 'p1',
            trade_id: 'T2',
            action: 'ENTRY',
            source: 'BOT'
        },
        {
            id: 'o4',
            symbol: 'ETH/USDT',
            type: 'Market',
            side: 'SELL',
            qty: 1,
            price: 210,
            status: 'filled',
            timestamp: now - 570000,
            profileId: 'p1',
            trade_id: 'T2',
            action: 'EXIT',
            source: 'BOT'
        },
        {
            id: 'o5',
            symbol: 'SOL/USDT',
            type: 'Market',
            side: 'BUY',
            qty: 1,
            price: 50,
            status: 'filled',
            timestamp: now - 560000,
            profileId: 'p1',
            trade_id: 'T3',
            action: 'ENTRY',
            source: 'BOT'
        },
        {
            id: 'o6',
            symbol: 'XRP/USDT',
            type: 'Market',
            side: 'SELL',
            qty: 1,
            price: 0.5,
            status: 'filled',
            timestamp: now - 550000,
            profileId: 'p1',
            trade_id: 'T4',
            action: 'EXIT',
            source: 'BOT'
        },
        {
            id: 'o7',
            symbol: 'ADA/USDT',
            type: 'Market',
            side: 'SELL',
            qty: 1,
            price: 0.4,
            status: 'pending_new',
            timestamp: now - 540000,
            profileId: 'p1',
            trade_id: 'T5',
            action: 'EXIT',
            source: 'BOT'
        }
    ],
    history: [],
    settings: {
        executionMode: 'Paper',
        riskPerTrade: 0.01,
        totalCapital: 15000,
        maxOpenTrades: 6,
        isAlgoEnabled: true,
        enabledRules: ['TrendBiasRule']
    },
    uptime: 7200000
});

describe('PositionsTab', () => {
    it('renders lifecycle summary across OPEN, PARTIAL_EXIT, CLOSED, ORPHAN_EXIT, EXIT_PENDING', () => {
        const html = renderToStaticMarkup(
            React.createElement(PositionsTab, { botState: createBotState() })
        );

        expect(html).toContain('Lifecycle Trace');
        expect(html).toContain('OPEN: 1');
        expect(html).toContain('PARTIAL_EXIT: 1');
        expect(html).toContain('CLOSED: 1');
        expect(html).toContain('ORPHAN_EXIT: 1');
        expect(html).toContain('EXIT_PENDING: 1');
        expect(html).toContain('Entry Used ($)');
    });

    it('shows stale order warning and lifecycle mismatch diagnostics', () => {
        const html = renderToStaticMarkup(
            React.createElement(PositionsTab, { botState: createBotState() })
        );

        expect(html).toContain('Stale Order');
        expect(html).toContain('Lifecycle Mismatch Diagnostics');
        expect(html).toContain('Position has no trade ID');
        expect(html).toContain('position symbol is LTC/USDT');
    });

    it('does not flag BTC/USD vs BTC/USDT alias as symbol mismatch', () => {
        const state = createBotState();
        state.positions = state.positions.map((position) => (
            position.id === 'symbol-mismatch'
                ? {
                    ...position,
                    symbol: 'BTC/USD',
                    tradeId: 'T1'
                }
                : position
        ));

        const html = renderToStaticMarkup(
            React.createElement(PositionsTab, { botState: state })
        );

        expect(html).not.toContain('position symbol is BTC/USD');
    });
});
