import type { FC } from 'react';
import React, { useEffect, useState } from 'react';
import { Button, Sidecar } from '@theorchard/suite-components';
import { filterData } from '@theorchard/suite-frontend';
import { orderBy } from 'lodash';
import { useGetRecentOwnershipIngestionsFileProgress } from 'src/data/queries/getRecentOwnershipNrIngestions';
import { type NrOwnershipIngestionFile } from 'src/data/queries/getRecentOwnershipNrIngestions/types';
import { EmptyCard } from 'src/pages/catalogPage/components/viewBulkUploads/emptyCard';
import {
    recordClickViewBulkUploads,
    recordCloseBulkUploads,
} from 'src/utils/segment/clickEvents';
import { CLASSNAME, NUMBER_OF_RECORDS } from './constants';
import { UploadCard } from './uploadCard';

const pollingInterval = 2000;

const ViewBulkUploads: FC = () => {
    const [open, setOpen] = useState<boolean>(false);

    const {
        data: recentOwnershipNrIngestionFiles,
        error,
        startPolling,
        stopPolling,
    } = useGetRecentOwnershipIngestionsFileProgress({
        limit: NUMBER_OF_RECORDS,
    });

    const ingestionStatuses = recentOwnershipNrIngestionFiles?.map(
        f => f.ingestionCompleted
    );

    const sortedIngestions = filterData(
        orderBy(recentOwnershipNrIngestionFiles, ['lastModified'], 'desc')
    );
    const activeUploads = sortedIngestions.filter(f => !f.ingestionCompleted);
    const completedFiles = sortedIngestions.filter(i => i.ingestionCompleted);

    useEffect(() => {
        if (error) stopPolling();
    }, [error, stopPolling]);

    useEffect(() => {
        if (
            !!recentOwnershipNrIngestionFiles &&
            ingestionStatuses?.every(s => !!s)
        )
            stopPolling();
        else startPolling(pollingInterval);
    }, [
        startPolling,
        recentOwnershipNrIngestionFiles,
        ingestionStatuses,
        stopPolling,
    ]);

    useEffect(() => {
        if (!open) stopPolling();
    }, [open, stopPolling]);

    const onModalOpen = () => {
        startPolling(pollingInterval);
        recordClickViewBulkUploads();
        setOpen(true);
    };

    return (
        <div className={CLASSNAME}>
            <Button className={`${CLASSNAME}-Link`} onClick={onModalOpen}>
                {$t('neighbouringRights.viewBulkUploads.bulkUploads')}
            </Button>

            <Sidecar
                isOpen={open}
                onRequestClose={() => {
                    setOpen(false);
                    recordCloseBulkUploads();
                }}
                title={
                    <h3
                        className={`${CLASSNAME}-header ReactModal-header-text`}
                    >
                        {$t('neighbouringRights.viewBulkUploads.bulkUploads')}
                    </h3>
                }
                data-testid={`${CLASSNAME}-Body`}
                className={`${CLASSNAME}-modal`}
            >
                <div className={`${CLASSNAME}-modal-wrapper`}>
                    <div className={`${CLASSNAME}-history`}>
                        <div className={`${CLASSNAME}-history-header`}>
                            {$t(
                                'neighbouringRights.viewBulkUploads.activeUploads'
                            )}
                        </div>
                        {!activeUploads.length && <EmptyCard />}
                        {activeUploads?.map(
                            (item: NrOwnershipIngestionFile) => (
                                <UploadCard
                                    item={item}
                                    key={item.id}
                                    uploadType="active"
                                />
                            )
                        )}
                    </div>
                    <div className={`${CLASSNAME}-history`}>
                        <div className={`${CLASSNAME}-history-header`}>
                            {$t(
                                'neighbouringRights.viewBulkUploads.uploadHistory'
                            )}
                        </div>
                        {completedFiles.map(
                            (item: NrOwnershipIngestionFile) => (
                                <UploadCard
                                    item={item}
                                    key={item.id}
                                    uploadType="historic"
                                />
                            )
                        )}
                    </div>
                </div>
            </Sidecar>
        </div>
    );
};

export default ViewBulkUploads;
