import React from 'react';
import { fireEvent, screen } from '@testing-library/react';
import { createIdentity, renderInAppContext } from '@theorchard/suite-testing';
import { ABACUS_PROFILE } from 'src/constants';
import TransferDetail from '../transfer-detail/transfer-detail';

let mockTransferId = 'job-1001';
let mockJobStatus = 'QUEUED';

jest.mock('react-router-dom', () => ({
    ...jest.requireActual('react-router-dom'),
    useParams: () => ({ transferId: mockTransferId }),
    useHistory: () => ({ goBack: jest.fn(), push: jest.fn() }),
}));

jest.mock('src/apollo/queries/transfer-projects', () => {
    const baseJob = {
        projectTransferJobId: 'job-1001',
        status: 'QUEUED',
        createdAt: '2024-01-15T10:30:00Z',
        transferCompletedOn: null,
        failureReason: null,
        projectCode: null,
        revenueCutoffDate: '2026-01-01',
        createdBy: { id: 'alice@example.com' },
        originLabel: { vendorId: 101 },
        destinationLabel: { vendorId: 202 },
        project: { projectId: 1, projectName: 'Greatest Hits' },
        products: [
            {
                status: 'QUEUED',
                transferCompletedOn: null,
                failureReason: null,
                product: {
                    productId: 9001,
                    upc: '196589123456',
                    productName: 'My Album',
                    productCode: 'PC-12436',
                    format: 'Digital - Full Length',
                    primaryArtists: [
                        { artistName: 'Jon Snow', artistType: 'primary' },
                    ],
                    tracks: [{ isrc: 'ISRC123', trackName: 'My Dragon Queen' }],
                },
            },
        ],
    };
    const completedJob = {
        ...baseJob,
        projectTransferJobId: 'job-completed',
        status: 'COMPLETED',
        transferCompletedOn: '2026-06-03T00:00:00Z',
    };
    return {
        ...jest.requireActual('src/apollo/queries/transfer-projects'),
        useProjectTransferJob: (jobId: string | undefined) => ({
            job:
                jobId === 'job-1001'
                    ? { ...baseJob, status: mockJobStatus }
                    : jobId === 'job-completed'
                      ? completedJob
                      : null,
            loading: false,
            error: undefined,
        }),
    };
});

jest.mock('src/apollo/queries/transfer-terms', () => ({
    useProjectTransferTerms: () => ({ terms: [], loading: false }),
}));

jest.mock('src/apollo/queries/account', () => ({
    ...jest.requireActual('src/apollo/queries/account'),
    useAccountsByVendorIds: () => ({
        accounts: [
            {
                accountId: 'acc-101',
                accountName: 'Origin Label Co',
                vendor: { vendorId: 101, companyBrand: null },
            },
            {
                accountId: 'acc-202',
                accountName: 'Destination Label Co',
                vendor: { vendorId: 202, companyBrand: null },
            },
        ],
        loading: false,
    }),
}));

const identity = createIdentity({ profileType: ABACUS_PROFILE });

describe('TransferDetail', () => {
    it('renders the Transfer tag and the job id as the title', () => {
        renderInAppContext(<TransferDetail />, { identity });
        expect(screen.getByText('Transfer')).toBeInTheDocument();
        expect(screen.getByText('job-1001')).toBeInTheDocument();
    });

    it('renders the statement period and created-by in the header', () => {
        renderInAppContext(<TransferDetail />, { identity });
        expect(screen.getByText('Statement Period:')).toBeInTheDocument();
        expect(screen.getByText('February 2026')).toBeInTheDocument();
        expect(screen.getByText('Created:')).toBeInTheDocument();
        expect(screen.getByText('By:')).toBeInTheDocument();
    });

    it('renders a Delete button in the header', () => {
        renderInAppContext(<TransferDetail />, { identity });
        expect(screen.getByTestId('transferDeleteButton')).toBeInTheDocument();
    });

    it('renders the breadcrumbs', () => {
        renderInAppContext(<TransferDetail />, { identity });
        expect(screen.getByText('Transfer Projects')).toBeInTheDocument();
    });

    it('renders from and to vendor metadata', () => {
        renderInAppContext(<TransferDetail />, { identity });
        expect(screen.getByText('Origin Label Co')).toBeInTheDocument();
        expect(screen.getByText('Destination Label Co')).toBeInTheDocument();
    });

    it('renders the Project to Transfer card with a products sidecar', () => {
        renderInAppContext(<TransferDetail />, { identity });
        expect(screen.getByText('Project to Transfer')).toBeInTheDocument();
        expect(screen.getByText('1 Product')).toBeInTheDocument();
        expect(
            screen.getByTestId('sidecarTrigger-projectProducts')
        ).toBeInTheDocument();
    });
});

describe('TransferDetail - not found', () => {
    beforeEach(() => {
        mockTransferId = '9999';
    });
    afterEach(() => {
        mockTransferId = 'job-1001';
    });

    it('shows not found message for unknown transfer', () => {
        renderInAppContext(<TransferDetail />, { identity });
        expect(screen.getByText('Transfer not found')).toBeInTheDocument();
    });
});

describe('TransferDetail - delete guard while the modal is open', () => {
    afterEach(() => {
        mockJobStatus = 'QUEUED';
    });

    it('keeps Confirm enabled while the job is still deletable', () => {
        renderInAppContext(<TransferDetail />, { identity });
        fireEvent.click(screen.getByTestId('transferDeleteButton'));
        expect(
            screen.getByText(
                'Once you delete this transfer it cannot be undone.'
            )
        ).toBeInTheDocument();
        const confirmButton = screen
            .getAllByRole('button', { name: 'Delete' })
            .at(-1) as HTMLElement;
        expect(confirmButton).toBeEnabled();
    });

    it('disables Confirm and shows the reason when the job starts processing', () => {
        renderInAppContext(<TransferDetail />, { identity });
        const deleteButton = screen.getByTestId('transferDeleteButton');
        // The poll result lands between the render that produced the button
        // and the click: the modal opens against an already-PROCESSING job.
        mockJobStatus = 'PROCESSING';
        fireEvent.click(deleteButton);
        expect(
            screen.getByText(
                'Once you delete this transfer it cannot be undone.'
            )
        ).toBeInTheDocument();
        const confirmButton = screen
            .getAllByRole('button', { name: 'Delete' })
            .at(-1) as HTMLElement;
        expect(confirmButton).toBeDisabled();
        expect(
            screen.queryAllByText(
                'Transfer is in progress and cannot be deleted'
            ).length
        ).toBeGreaterThan(0);
    });
});

describe('TransferDetail - completed', () => {
    beforeEach(() => {
        mockTransferId = 'job-completed';
    });
    afterEach(() => {
        mockTransferId = 'job-1001';
    });

    it('shows the transfer date as status subtext, not an info alert', () => {
        renderInAppContext(<TransferDetail />, { identity });
        expect(screen.getByText('Transferred')).toBeInTheDocument();
        expect(screen.getByText('2026-06-03')).toBeInTheDocument();
        // The old info-panel alert is gone.
        expect(
            screen.queryByText(/Transfer completed on/)
        ).not.toBeInTheDocument();
    });
});
