import type { FC } from 'react';
import React, { useState } from 'react';
import { GridTable } from '@theorchard/suite-components';
import { Illustration } from '@theorchard/suite-icons';
import { OwnershipNrSoundRecordingOrderByField } from 'src/data/globalTypes';
import {
    recordInstancesCollapse,
    recordInstancesExpand,
} from 'src/utils/segment/clickEvents';
import {
    TextCell,
    DateCell,
    SongNameLinkCell,
    PrimaryArtistCell,
} from 'src/utils/tableCells';
import type { SortBy } from './types';
import type { GridTableRowInstance } from '@theorchard/suite-components';
import type { CatalogOwnershipNrSoundRecording } from 'src/data/queries/getOwnershipNrSoundRecordings';

interface Props {
    soundRecordings: CatalogOwnershipNrSoundRecording[];
    totalSoundRecordings?: number;
    loading: boolean;
    onClearFilters: () => void;
    onSort: (sortBy: SortBy[]) => void;
    sortBy: SortBy;
    filtersApplied: boolean;
    page: number;
    pageSize: number;
    handlePageChange: (page: number) => void;
    handlePageSizeChange: (pageSize: number) => void;
}

export const CLASSNAME = 'CatalogTable';

const CatalogTable: FC<Props> = ({
    soundRecordings,
    loading,
    totalSoundRecordings,
    onSort,
    sortBy,
    filtersApplied,
    onClearFilters,
    page,
    pageSize,
    handlePageChange,
    handlePageSizeChange,
}) => {
    const [expandedRows, setExpandedRows] = useState<Record<string, FC>>({});

    const handleRowClick = ({
        key,
        data,
    }: GridTableRowInstance<CatalogOwnershipNrSoundRecording>) => {
        if (expandedRows[key]) {
            setExpandedRows({});
            recordInstancesCollapse();
        } else {
            setExpandedRows({
                [key]: () => (
                    <>
                        {data.tracks.map(t => (
                            <div
                                className={`${CLASSNAME}-cell-instance`}
                                key={t.id}
                            >
                                <div
                                    className={`${CLASSNAME}-cell-instance-name`}
                                >
                                    <div>
                                        {t.title}{' '}
                                        {t.version && `(${t.version})`}
                                    </div>
                                    <div
                                        className={`${CLASSNAME}-cell-instance-name-bottom`}
                                    >
                                        {t.submittedByVendor.name}{' '}
                                        {`(${t.submittedByVendor.owner ?? ''})`}
                                        {t.submittedBySubaccountId !== 0 &&
                                            ` - ${t.submittedBySubaccountId}`}
                                    </div>
                                </div>
                                <div
                                    className={`${CLASSNAME}-cell-instance-data`}
                                >
                                    {t.product ? (
                                        <div>
                                            {t.product?.contentType.toLowerCase() ??
                                                ''}
                                            &nbsp;
                                            {t.recordingType.toLowerCase()}
                                            ,&nbsp;
                                            {t.product?.format.toLowerCase() ??
                                                null}
                                        </div>
                                    ) : (
                                        <div>
                                            {t.recordingType.toLowerCase()}
                                        </div>
                                    )}
                                    <div
                                        className={`${CLASSNAME}-cell-instance-data-bottom`}
                                    >
                                        {t.product && t.product.upc}
                                    </div>
                                </div>
                            </div>
                        ))}
                    </>
                ),
            });
            recordInstancesExpand();
        }
    };

    return (
        <GridTable
            className={CLASSNAME}
            data={soundRecordings}
            loading={loading}
            bordered
            onSort={onSort}
            sortBy={sortBy}
            emptyStateTitle={$t(
                'ownershipRights.catalogPage.noSoundRecordings'
            )}
            emptyStateIcon={() => <Illustration name="noResults" />}
            expandedRows={expandedRows}
            onRowClick={handleRowClick}
            paginated
            totalCount={totalSoundRecordings}
            page={page}
            pageSize={pageSize}
            onPageChange={handlePageChange}
            onPageSizeChange={handlePageSizeChange}
            onClearFilters={onClearFilters}
            showClearFilters={filtersApplied}
            showUpdateIndicator
        >
            <GridTable.Column
                className={`${CLASSNAME}-cell-songName`}
                name="srNameVersion"
                title={$t('ownershipRights.catalogPage.srNameVersion')}
                Cell={SongNameLinkCell}
                sortable
                sortKey={OwnershipNrSoundRecordingOrderByField.NAME_VERSION}
                defaultSortDirection="desc"
                minWidth="300px"
                maxWidth="2fr"
                fixed
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-primaryArtist`}
                name="primaryArtists"
                title={$t('ownershipRights.catalogPage.primaryArtist')}
                Cell={PrimaryArtistCell}
                defaultSortDirection="desc"
                minWidth="250px"
                maxWidth="2fr"
                tooltip={$t('ownershipRights.catalogPage.primaryArtistTooltip')}
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-isrc`}
                name="isrc"
                title={$t('ownershipRights.catalogPage.isrc')}
                Cell={TextCell}
                defaultSortDirection="desc"
                minWidth="180px"
                maxWidth="180px"
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-lastModified`}
                name="lastModifiedAt"
                title={$t('ownershipRights.catalogPage.lastModifiedAt')}
                Cell={DateCell}
                sortable
                sortKey={OwnershipNrSoundRecordingOrderByField.LAST_MODIFIED}
                defaultSortDirection="desc"
                minWidth="110px"
                maxWidth="110px"
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-instances`}
                name="instancesCount"
                title={$t('ownershipRights.catalogPage.instances')}
                Cell={TextCell}
                defaultSortDirection="desc"
                minWidth="100px"
                maxWidth="100px"
            />
        </GridTable>
    );
};

export default CatalogTable;
