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 ProjectTransferCard, {
    productSidecarItems,
} from '../transfer-detail/project-transfer-card';
import type { TransferJobProduct } from 'src/apollo/queries/transfer-projects';

const product = (
    overrides: Partial<TransferJobProduct['product']>
): TransferJobProduct => ({
    product: {
        productId: 1,
        upc: '111',
        productName: 'P',
        productCode: 'PC-1',
        format: 'Digital - Full Length',
        primaryArtists: [{ artistName: 'Jon Snow', artistType: 'primary' }],
        tracks: [{ isrc: 'ISRC1', trackName: 'My Dragon Queen' }],
        ...overrides,
    },
});

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

describe('productSidecarItems', () => {
    it('uses the product name as the label', () => {
        const [item] = productSidecarItems([
            product({ productName: 'My Album' }),
        ]);
        expect(item.label).toBe('My Album');
    });

    it('labels the product by id when it has no name', () => {
        const [item] = productSidecarItems([
            product({ productId: 7, productName: null }),
        ]);
        expect(item.label).toBe('Product 7');
    });

    it('packs code, upc, artist and format into a searchable subtitle', () => {
        const [item] = productSidecarItems([
            product({
                productCode: 'PC-1',
                upc: '195497595617',
                format: 'Single',
                primaryArtists: [
                    { artistName: 'Migrantes', artistType: 'primary' },
                ],
            }),
        ]);
        expect(item.subtitle).toBe('PC-1 • 195497595617 • Migrantes • Single');
    });

    it('omits missing fields from the subtitle', () => {
        const [item] = productSidecarItems([
            product({
                productCode: 'PC-1',
                upc: null,
                format: null,
                primaryArtists: [],
            }),
        ]);
        expect(item.subtitle).toBe('PC-1');
    });
});

describe('ProjectTransferCard', () => {
    it('renders the project title and product count', () => {
        renderInAppContext(
            <ProjectTransferCard
                projectName="Greatest Hits"
                projectId={1}
                products={[
                    product({ productId: 1 }),
                    product({ productId: 2 }),
                ]}
            />,
            { identity }
        );
        expect(screen.getByText('Greatest Hits')).toBeInTheDocument();
        expect(screen.getByText('2 Products')).toBeInTheDocument();
    });

    it('exposes a products sidecar trigger', () => {
        renderInAppContext(
            <ProjectTransferCard
                projectName="Greatest Hits"
                projectId={1}
                products={[product({})]}
            />,
            { identity }
        );
        expect(
            screen.getByTestId('sidecarTrigger-projectProducts')
        ).toBeEnabled();
    });

    it('disables the products trigger when there are no products', () => {
        renderInAppContext(
            <ProjectTransferCard
                projectName="Greatest Hits"
                projectId={1}
                products={[]}
            />,
            { identity }
        );
        expect(
            screen.getByTestId('sidecarTrigger-projectProducts')
        ).toBeDisabled();
        expect(screen.getByText('0 Products')).toBeInTheDocument();
    });

    it('lists the products in the sidecar when opened', () => {
        renderInAppContext(
            <ProjectTransferCard
                projectName="Greatest Hits"
                projectId={1}
                products={[
                    product({ productId: 1, productName: 'Album One' }),
                    product({ productId: 2, productName: 'Album Two' }),
                ]}
            />,
            { identity }
        );
        fireEvent.click(screen.getByTestId('sidecarTrigger-projectProducts'));
        expect(screen.getByText('Products (2)')).toBeInTheDocument();
        expect(screen.getByText('Album One')).toBeInTheDocument();
        expect(screen.getByText('Album Two')).toBeInTheDocument();
    });

    it('hides the sidecar search when there are fewer than 10 products', () => {
        renderInAppContext(
            <ProjectTransferCard
                projectName="Greatest Hits"
                projectId={1}
                products={Array.from({ length: 9 }, (_, i) =>
                    product({ productId: i + 1 })
                )}
            />,
            { identity }
        );
        fireEvent.click(screen.getByTestId('sidecarTrigger-projectProducts'));
        expect(screen.queryByRole('textbox')).not.toBeInTheDocument();
    });

    it('shows the sidecar search when there are 10 or more products', () => {
        renderInAppContext(
            <ProjectTransferCard
                projectName="Greatest Hits"
                projectId={1}
                products={Array.from({ length: 10 }, (_, i) =>
                    product({ productId: i + 1 })
                )}
            />,
            { identity }
        );
        fireEvent.click(screen.getByTestId('sidecarTrigger-projectProducts'));
        expect(screen.getByRole('textbox')).toBeInTheDocument();
    });

    it('renders the Project Code field when a project code is provided', () => {
        renderInAppContext(
            <ProjectTransferCard
                projectName="Greatest Hits"
                projectId={1}
                projectCode="PRJ-500"
                products={[product({})]}
            />,
            { identity }
        );
        expect(screen.getByText('Project Code')).toBeInTheDocument();
        expect(screen.getByText('PRJ-500')).toBeInTheDocument();
    });

    it('omits the Project Code field when no project code is provided', () => {
        renderInAppContext(
            <ProjectTransferCard
                projectName="Greatest Hits"
                projectId={1}
                products={[product({})]}
            />,
            { identity }
        );
        expect(screen.queryByText('Project Code')).not.toBeInTheDocument();
    });

    it('renders a Destination Contract link when a contract is provided', () => {
        renderInAppContext(
            <ProjectTransferCard
                projectName="My Project"
                projectId={1}
                products={[product({})]}
                contractId="c-99"
                contractName="My Contract"
            />,
            { identity }
        );

        const link = screen.getByRole('link', { name: 'My Contract' });
        expect(link).toHaveAttribute('href', '/contract/c-99');
    });

    it('omits the Destination Contract field when no contract is provided', () => {
        renderInAppContext(
            <ProjectTransferCard
                projectName="My Project"
                projectId={1}
                products={[product({})]}
            />,
            { identity }
        );

        expect(
            screen.queryByText('Destination Contract')
        ).not.toBeInTheDocument();
    });
});
