import type { FC } from 'react';
import React from 'react';
import { Button, GridTable } from '@theorchard/suite-components';
import { formatMessage } from '@theorchard/suite-frontend';
import dayjs from 'dayjs';
import { DateCell, TextCell, ThumbnailProductCell } from 'src/tableCells';
import { exportToCsv } from 'src/utils/exportCsv';
import { recordSelectProductClicked } from 'src/utils/segment';
import { TRANSLATION_KEY } from '../../constants';
import type { DeliveryProduct } from 'src/data/queries';
import type { SortBy } from 'src/types';
import type { CsvDataType } from 'src/utils/exportCsv';

export const CLASSNAME = 'ProductsTable';

interface Props {
    totalCount?: number;
    products: DeliveryProduct[];
    loading: boolean;
    selectedProducts: string[];
    onSort: (sortBy: SortBy[]) => void;
    sortBy: SortBy;
    deliveryType: string;
    onSelectedRowsChanged: (rows: string[]) => void;
    pageSize: number;
    page: number;
    handlePageChange: (newPageNumber: number) => void;
    handlePageSizeChange: (newPageSize: number) => void;
}
const ProductsTable: FC<Props> = ({
    totalCount,
    products,
    loading,
    selectedProducts,
    onSort,
    sortBy,
    onSelectedRowsChanged,
    deliveryType,
    page,
    pageSize,
    handlePageChange,
    handlePageSizeChange,
}) => {
    const handleRowSelection = (rows: string[]) => {
        onSelectedRowsChanged(rows);
    };

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const translateHeaders = (data: Record<string, any>) => {
        const formatted: CsvDataType = {};
        Object.keys(data).forEach(key => {
            const newKey = formatMessage(
                `${TRANSLATION_KEY}.table.headers.${key}`
            );
            formatted[newKey] = data[key];
        });
        return formatted;
    };

    const onExportCsv = () => {
        const filename = `Products_${deliveryType}_${dayjs().format(
            'YYYY-MM-DDTHHmmss'
        )}`;
        const csvData = products.map(x => translateHeaders(x));

        exportToCsv(csvData, filename);
    };

    const header = (
        <>
            {products.length > 0 && (
                <div className={`${CLASSNAME}-deliveryButtons`}>
                    <Button
                        className={`${CLASSNAME}-exportData`}
                        variant="link"
                        onClick={() => onExportCsv()}
                    >
                        {$t(`${TRANSLATION_KEY}.exportData`)}
                    </Button>
                </div>
            )}
        </>
    );

    return (
        <GridTable
            className={CLASSNAME}
            data={products}
            headerRight={header}
            loading={loading}
            rowKey={(row: DeliveryProduct) => row.productId}
            selectable
            selectedRowKeys={selectedProducts}
            onSelectedRowsChanged={handleRowSelection}
            emptyStateTitle={$t(`${TRANSLATION_KEY}.table.emptyStateTitle`)}
            onSort={onSort}
            sortBy={sortBy}
            onRowClick={recordSelectProductClicked}
            paginated
            totalCount={totalCount}
            page={page}
            pageSize={pageSize}
            onPageChange={handlePageChange}
            onPageSizeChange={handlePageSizeChange}
            showUpdateIndicator
        >
            <GridTable.Column
                className={`${CLASSNAME}-cell-primaryArtist`}
                name="primaryArtist"
                title={$t(`${TRANSLATION_KEY}.table.headers.primaryArtist`)}
                Cell={TextCell}
                minWidth="150px"
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-productName`}
                name="productName"
                title={$t(`${TRANSLATION_KEY}.table.headers.productName`)}
                Cell={ThumbnailProductCell}
                minWidth="220px"
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-brandName`}
                name="brandName"
                title={$t(`${TRANSLATION_KEY}.table.headers.brandName`)}
                Cell={TextCell}
                fixedOffset={30}
                minWidth="150px"
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-account`}
                name="account"
                title={$t(`${TRANSLATION_KEY}.table.headers.account`)}
                Cell={TextCell}
                minWidth="150px"
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-serviceName`}
                name="serviceName"
                title={$t(`${TRANSLATION_KEY}.table.headers.serviceName`)}
                Cell={TextCell}
                minWidth="150px"
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-imprint`}
                name="imprint"
                title={$t(`${TRANSLATION_KEY}.table.headers.imprint`)}
                Cell={TextCell}
                minWidth="150px"
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-productCode`}
                name="productCode"
                title={$t(`${TRANSLATION_KEY}.table.headers.productCode`)}
                Cell={TextCell}
                minWidth="110px"
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-displayUpc`}
                name="displayUpc"
                title={$t(`${TRANSLATION_KEY}.table.headers.displayUpc`)}
                Cell={TextCell}
                minWidth="150px"
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-salesStartDate`}
                name="salesStartDate"
                title={$t(`${TRANSLATION_KEY}.table.headers.salesStartDate`)}
                sortable
                sortKey="SALE_START_DATE"
                Cell={DateCell}
                minWidth="150px"
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-embargoDate`}
                name="embargoDate"
                title={$t(`${TRANSLATION_KEY}.table.headers.embargoDate`)}
                sortable
                Cell={DateCell}
                minWidth="150px"
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-configuration`}
                name="configuration"
                title={$t(`${TRANSLATION_KEY}.table.headers.configuration`)}
                Cell={TextCell}
                minWidth="170px"
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-deliveryType`}
                name="deliveryType"
                title={$t(`${TRANSLATION_KEY}.table.headers.deliveryType`)}
                Cell={TextCell}
                minWidth="100px"
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-genre`}
                name="genre"
                title={$t(`${TRANSLATION_KEY}.table.headers.genre`)}
                Cell={TextCell}
                minWidth="150px"
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-subGenre`}
                name="subGenre"
                title={$t(`${TRANSLATION_KEY}.table.headers.subGenre`)}
                Cell={TextCell}
                minWidth="150px"
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-price`}
                name="price"
                title={$t(`${TRANSLATION_KEY}.table.headers.price`)}
                Cell={TextCell}
                minWidth="130px"
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-version`}
                name="version"
                title={$t(`${TRANSLATION_KEY}.table.headers.version`)}
                Cell={TextCell}
                minWidth="130px"
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-projectDescription`}
                name="projectDescription"
                title={$t(
                    `${TRANSLATION_KEY}.table.headers.projectDescription`
                )}
                Cell={TextCell}
                minWidth="150px"
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-initialStock`}
                name="initialStock"
                title={$t(`${TRANSLATION_KEY}.table.headers.initialStock`)}
                Cell={TextCell}
                minWidth="100px"
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-deletions`}
                name="deletions"
                title={$t(`${TRANSLATION_KEY}.table.headers.deletions`)}
                Cell={TextCell}
                minWidth="100px"
            />
        </GridTable>
    );
};

export default ProductsTable;
