import type { FC } from 'react';
import React, { useState } from 'react';
import {
    GridTable,
    GridTableRowInstance,
    Status,
} from '@theorchard/suite-components';
import { GlyphIcon } from '@theorchard/suite-icons';
import { OA_VENDOR_URL, ROUTE_BULK_CREATE_DIGITAL_AUDIO } from 'src/constants';
import InfiniteScroll from 'src/components/infiniteScroll';
import type { GetBulkSessionIngestionsQuery } from 'src/data/queries/getBulkSessionIngestions/__generated__/GetBulkSessionIngestions';
import IngestionDetails from '../ingestionDetails';

type IngestionItem =
    GetBulkSessionIngestionsQuery['getBulkSessionIngestions']['items'][number];

export const CLASS_NAME = 'BulkSessionIngestionList';

const LabelCell: FC<{ data: IngestionItem }> = ({ data: row }) => {
    const label = row.bulkSession.label;

    if (label.__typename !== 'Vendor') {
        return null;
    }

    const serviceTierName = label.serviceTier?.displayName;
    const labelText = serviceTierName
        ? `${label.name} (${serviceTierName})`
        : label.name;
    const vendorId = (label as { vendorId?: number }).vendorId;

    if (!vendorId) {
        return <>{labelText}</>;
    }

    const vendorParams = new URLSearchParams({
        vendor_id: String(vendorId),
    });

    return (
        <a
            href={`${OA_VENDOR_URL}?${vendorParams.toString()}`}
            target="_blank"
            rel="noreferrer"
        >
            {labelText}
        </a>
    );
};

const BulkSessionIngestionList: FC<{
    items: IngestionItem[];
    totalCount: number;
    loading: boolean;
    fetchMore?: (limit: number, offset: number) => void;
}> = ({ items, totalCount, loading, fetchMore }) => {
    const [expandedIngestion, setExpandedIngestion] = useState<
        Record<string, FC>
    >({});

    const content = (
        <GridTable
            data={items}
            loading={loading}
            totalCount={totalCount}
            expandedRows={expandedIngestion}
            onRowClick={({ key }: GridTableRowInstance<IngestionItem>) => {
                if (expandedIngestion[key]) setExpandedIngestion({});
                else {
                    setExpandedIngestion({
                        [key]: () => (
                            <IngestionDetails bulkSessionIngestionId={key} />
                        ),
                    });
                }
            }}
            rowKey={(row: IngestionItem) => row.id}
            rowActions={{
                metadataDownload: {
                    icon: <GlyphIcon name="formatXlsx" size={24} />,
                    onClick: (row: IngestionItem) => {
                        const { downloadLink } = row.bulkSession;

                        if (!downloadLink) {
                            return;
                        }

                        const link = document.createElement('a');
                        link.href = downloadLink;
                        link.setAttribute('download', '');
                        link.style.display = 'none';
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                    },
                    tooltip: 'Download Metadata',
                },
            }}
        >
            <GridTable.Column<IngestionItem>
                title="Status"
                name="ingestionStatus"
                maxWidth="40px"
                Cell={({ data: row }) => {
                    const variant: 'success' | 'loading' | 'error' | undefined =
                        (
                            {
                                success: 'success',
                                in_progress: 'loading',
                                failure: 'error',
                            } as const
                        )[row.ingestionStatus];
                    return (
                        variant && (
                            <Status
                                variant={variant}
                                filled={true}
                                text={row.ingestionStatus
                                    .replace(/_/g, ' ')
                                    .replace(/\b\w/g, c => c.toUpperCase())}
                            />
                        )
                    );
                }}
            />
            <GridTable.Column<IngestionItem>
                title="Bulk Session"
                name="bulkSessionId"
                maxWidth="250px"
                Cell={({ data: row }) => (
                    <a
                        href={`${ROUTE_BULK_CREATE_DIGITAL_AUDIO}?id=${row.bulkSession.id}`}
                    >
                        {row.bulkSession.slug}
                    </a>
                )}
            />
            <GridTable.Column<IngestionItem>
                title="Label"
                name="createdAt"
                maxWidth="150px"
                Cell={LabelCell}
            />
        </GridTable>
    );

    if (!fetchMore) {
        return <div className={CLASS_NAME}>{content}</div>;
    }

    return (
        <div className={CLASS_NAME}>
            <InfiniteScroll
                fetchMore={(limit, offset) => fetchMore?.(limit, offset)}
                loading={loading}
                count={items.length}
                totalResults={totalCount}
                totalLimit={10000}
                loadLimit={50}
            >
                {content}
            </InfiniteScroll>
        </div>
    );
};

export default BulkSessionIngestionList;
