// @vitest-environment jsdom
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { HistoryTab } from './HistoryTab';
import { tableNameTransactions } from '../lib/const';

const { authState, fetchTradeProfilesMock } = vi.hoisted(() => ({
    authState: {
        user: { id: 'u1' },
        profile: { role: 'user' },
        refreshProfile: vi.fn()
    },
    fetchTradeProfilesMock: vi.fn()
}));

vi.mock('../components/AuthContext', () => ({
    useAuth: () => authState
}));

const mockSupabaseChain = (data: any, error: any = null) => {
    const chain: any = {
        select: vi.fn(), eq: vi.fn(), order: vi.fn(), not: vi.fn(), limit: vi.fn(), then: vi.fn()
    };
    chain.select.mockReturnValue(chain);
    chain.eq.mockReturnValue(chain);
    chain.order.mockReturnValue(chain);
    chain.not.mockReturnValue(chain);
    chain.limit.mockReturnValue(chain);
    chain.then.mockImplementation((cb: any) => Promise.resolve({ data, error }).then(cb));
    return chain;
};

vi.mock('../lib/supabaseClient', () => ({
    supabase: { from: vi.fn() }
}));

vi.mock('../lib/profileApi', () => ({
    fetchTradeProfiles: fetchTradeProfilesMock
}));

import { supabase } from '../lib/supabaseClient';

describe('HistoryTab Master Suite', () => {
    const historyData = [
        { id: 'h1', symbol: 'BTC', entry_price: 50000, exit_price: 51000, pnl: 1000, pnl_percent: 2, created_at: '2024-01-01T10:00:00Z', side: 'BUY', source: 'BOT', profile_id: 'p1', size: 1, reason: 'Trend' }
    ];

    beforeEach(() => {
        vi.clearAllMocks();
        fetchTradeProfilesMock.mockResolvedValue([{ id: 'p1', name: 'Alpha' }]);
        (supabase.from as any).mockImplementation((table: string) => {
            if (table === tableNameTransactions) return mockSupabaseChain(historyData);
            return mockSupabaseChain([]);
        });
    });

    it('processes metrics and handles sort toggles', async () => {
        const user = userEvent.setup();
        render(<HistoryTab />);

        await waitFor(() => expect(screen.getByText(/Total Trades/i)).toBeInTheDocument());
        await waitFor(() => expect(screen.getByText('BTC')).toBeInTheDocument());

        const sortBtn = await screen.findByRole('button', { name: /Newest/i });
        await user.click(sortBtn);
        await waitFor(() => expect(screen.queryByText(/Oldest/i)).toBeInTheDocument());

        await user.click(screen.getByText(/Oldest/i));
        await waitFor(() => expect(screen.queryByText(/Newest/i)).toBeInTheDocument());
    });

    it('covers date filtering and pagination', async () => {
        const user = userEvent.setup();
        const manyRecords = Array.from({ length: 25 }, (_, i) => ({
            id: `h${i}`,
            symbol: 'BTC',
            entry_price: 50000,
            exit_price: 51000,
            pnl: 1000,
            pnl_percent: 2,
            created_at: `2024-01-01T12:${String(i % 60).padStart(2, '0')}:00`,

            side: 'BUY',
            source: 'BOT',
            profile_id: 'p1',
            size: 1,
            reason: 'Trend'
        }));

        (supabase.from as any).mockImplementation((table: string) => {
            if (table === tableNameTransactions) return mockSupabaseChain(manyRecords);
            return mockSupabaseChain([]);
        });

        const { container } = render(<HistoryTab />);
        await screen.findByText(/Page 1 \/ 2/i, {}, { timeout: 5000 });


        const dateInputs = container.querySelectorAll('input[type="date"]');
        if (dateInputs.length >= 2) {
            fireEvent.change(dateInputs[0], { target: { value: '2024-01-01' } });
            fireEvent.change(dateInputs[1], { target: { value: '2024-01-02' } });
        }

        const nextBtn = await screen.findByRole('button', { name: /Next/i });
        await user.click(nextBtn);
        await screen.findByText(/Page 2 \/ 2/i);

        const prevBtn = await screen.findByRole('button', { name: /Prev/i });
        await user.click(prevBtn);
        await screen.findByText(/Page 1 \/ 2/i);


        await user.click(screen.getByText(/Clear/i));
    });

    it('covers empty fallback and source mapping', async () => {
        (supabase.from as any).mockImplementation((table: string) => {
            if (table === tableNameTransactions) return mockSupabaseChain([
                { ...historyData[0], source: 'MANUAL', profile_id: null }
            ]);
            return mockSupabaseChain([]);
        });
        render(<HistoryTab />);
        await waitFor(() => expect(screen.queryByText(/MANUAL/i)).toBeInTheDocument());
    });
});
