import React, { type FC, useCallback, useEffect, useState } from 'react';
import { Button, GridTable, Modal } from '@theorchard/suite-components';
import { useToast } from '@theorchard/suite-frontend';
import { Illustration } from '@theorchard/suite-icons';
import {
    NrDeliveryJobsOrderBy,
    NrDeliveryJobStatus,
} from 'src/data/globalTypes';
import { useFulfillDeliveryJobsMutation } from 'src/data/mutations/fulfillNrDeliveryJobs/fulfillNrDeliveryJobs';
import { type DeliveryJobs } from 'src/data/queries';
import {
    TextCell,
    JobUpdatedAtCell,
    JobUpdatedByCell,
    JobStatusCell,
    TimeDateCell,
} from 'src/tableCells';
import { type RowInstance, type SortBy } from 'src/types';
import {
    recordCancelDeliveryClicked,
    recordCompleteDeliveryClicked,
    recordJobIdClicked,
    recordSelectAllJobsClicked,
} from 'src/utils/segment/clickEvents';
import { TRANSLATION_KEY } from '../constants';

export const CLASSNAME = 'JobsTable';

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

const JobsTable: FC<Props> = ({
    jobs,
    totalJobs,
    loading,
    onSort,
    sortBy,
    onClearFilters,
    filtersApplied,
    page,
    pageSize,
    handlePageChange,
    handlePageSizeChange,
}) => {
    const [selectedRows, setSelectedRows] = useState<string[]>([]);
    const [completeClicked, setCompleteClicked] = useState<boolean>(false);
    const [cancelledClicked, setCancelledClicked] = useState<boolean>(false);
    const [openModal, setOpenModal] = useState<boolean>(false);
    const toggleModal = () => setOpenModal(prevValue => !prevValue);

    const handleModalClose = () => {
        setOpenModal(false);
    };

    const { fulfillDeliveryJob, loading: fulfillJobLoading } =
        useFulfillDeliveryJobsMutation({
            jobIds: [],
            status: NrDeliveryJobStatus.COMPLETE,
        });

    const countSummary = () => (
        <div className={`${CLASSNAME}-itemsSelected`}>
            {selectedRows.length > 0 &&
                $t(`${TRANSLATION_KEY}.jobItems.selected`, {
                    selected: selectedRows.length,
                    totalCount: totalJobs ?? '-',
                })}
        </div>
    );

    const addToast = useToast();

    const handleCompleteClick = useCallback(() => {
        recordCompleteDeliveryClicked();
        fulfillDeliveryJob({
            variables: {
                jobIds: selectedRows,
                status: NrDeliveryJobStatus.COMPLETE,
            },
        }).catch(error => console.error(error));
        addToast(
            $t(`${TRANSLATION_KEY}.jobs.complete`, {
                count: selectedRows.length ?? '-',
            })
        );
        setSelectedRows([]);
        setCompleteClicked(false);
        handleModalClose();
    }, [addToast, selectedRows, fulfillDeliveryJob]);

    const handleCancelledClick = useCallback(() => {
        recordCancelDeliveryClicked();
        fulfillDeliveryJob({
            variables: {
                jobIds: selectedRows,
                status: NrDeliveryJobStatus.CANCELLED,
            },
        }).catch(error => console.error(error));
        addToast(
            $t(`${TRANSLATION_KEY}.jobs.cancelled`, {
                count: selectedRows.length ?? '-',
            }),
            { variant: 'danger' }
        );
        setSelectedRows([]);
        setCancelledClicked(false);
    }, [addToast, selectedRows, fulfillDeliveryJob]);

    useEffect(() => {
        if (completeClicked) handleCompleteClick();
        if (cancelledClicked) handleCancelledClick();
    }, [
        completeClicked,
        cancelledClicked,
        handleCancelledClick,
        handleCompleteClick,
    ]);

    const header = (
        <>
            {countSummary()}
            {selectedRows.length > 0 && (
                <div className={`${CLASSNAME}-deliveryButtons`}>
                    <Button
                        className={`${CLASSNAME}-completeDelivery`}
                        onClick={() => toggleModal()}
                    >
                        {$t(`${TRANSLATION_KEY}.completeDelivery`)}
                    </Button>
                    <Button
                        className={`${CLASSNAME}-cancelDelivery`}
                        onClick={() => setCancelledClicked(true)}
                    >
                        {$t(`${TRANSLATION_KEY}.cancelDelivery`)}
                    </Button>
                    {openModal && (
                        <Modal.Custom
                            isOpen={openModal}
                            onRequestClose={() => handleModalClose()}
                            title={$t(`${TRANSLATION_KEY}.areYouSure`)}
                            customFooter={
                                <Modal.Footer
                                    onConfirm={() => setCompleteClicked(true)}
                                    onCancel={() => handleModalClose()}
                                    confirmTitle={$t(
                                        `${TRANSLATION_KEY}.markAsComplete`
                                    )}
                                />
                            }
                        >
                            {$t(`${TRANSLATION_KEY}.completeJobModalBody`)}
                        </Modal.Custom>
                    )}
                </div>
            )}
        </>
    );

    const handleRowSelection = (rows: string[]) => {
        const readyForDeliveryJobs = jobs
            .map(item =>
                item.status === NrDeliveryJobStatus.SUCCESS ? item.jobId : ''
            )
            .filter(item => item);
        if (rows.length > 0 && rows.length === readyForDeliveryJobs.length)
            recordSelectAllJobsClicked();

        setSelectedRows(
            rows.filter(item => readyForDeliveryJobs.includes(item))
        );
    };

    return (
        <GridTable
            className={CLASSNAME}
            data={jobs}
            loading={fulfillJobLoading || loading}
            onSort={onSort}
            sortBy={sortBy}
            bordered
            emptyStateIcon={() => <Illustration name="noResults" />}
            emptyStateTitle={$t(`${TRANSLATION_KEY}.noJobs`)}
            emptyStateBody={$t(`${TRANSLATION_KEY}.adjustFilters`)}
            rowKey={(row: DeliveryJobs) => row.jobId}
            selectable
            rowSelectEnabled={(row: RowInstance<DeliveryJobs>) =>
                row.data.status === NrDeliveryJobStatus.SUCCESS
            }
            selectedRowKeys={selectedRows}
            onSelectedRowsChanged={handleRowSelection}
            onRowClick={recordJobIdClicked}
            headerRight={header}
            paginated
            totalCount={totalJobs}
            page={page}
            pageSize={pageSize}
            onPageChange={handlePageChange}
            onPageSizeChange={handlePageSizeChange}
            onClearFilters={onClearFilters}
            showClearFilters={filtersApplied}
            showUpdateIndicator
        >
            <GridTable.Column
                className={`${CLASSNAME}-cell-jobId`}
                name="jobId"
                title={$t(`${TRANSLATION_KEY}.jobId`)}
                Cell={TextCell}
                sortable={false}
                fixed
                maxWidth="90px"
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-orderId`}
                name="orderId"
                title={$t(`${TRANSLATION_KEY}.orderId`)}
                Cell={TextCell}
                sortable={false}
                maxWidth="90px"
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-cmo`}
                name="cmo"
                title={$t(`${TRANSLATION_KEY}.serviceName`)}
                Cell={TextCell}
                sortable={false}
                minWidth="130px"
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-name`}
                name="name"
                title={$t(`${TRANSLATION_KEY}.legalName`)}
                Cell={TextCell}
                sortable={false}
                minWidth="160px"
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-status`}
                name="status"
                title={$t(`${TRANSLATION_KEY}.jobStatus`)}
                Cell={JobStatusCell}
                sortable={false}
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-numberOfClaims`}
                name="numberOfClaims"
                title={$t(`${TRANSLATION_KEY}.numberOfClaims`)}
                Cell={TextCell}
                sortable={false}
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-lastUpdated`}
                name="lastUpdated"
                title={$t(`${TRANSLATION_KEY}.fulfilledOn`)}
                Cell={JobUpdatedAtCell}
                sortable
                sortKey={NrDeliveryJobsOrderBy.LAST_UPDATED}
                defaultSortDirection="desc"
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-last-updatedBy`}
                name="lastUpdatedBy"
                title={$t(`${TRANSLATION_KEY}.fulfilledBy`)}
                Cell={JobUpdatedByCell}
                sortable={false}
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-last-orderCreated`}
                name="orderCreatedAt"
                title={$t(`${TRANSLATION_KEY}.orderCreatedAt`)}
                Cell={TimeDateCell}
                sortable
            />
            <GridTable.Column
                className={`${CLASSNAME}-cell-last-orderCreatedBy`}
                name="orderCreatedBy"
                title={$t(`${TRANSLATION_KEY}.orderCreatedBy`)}
                Cell={TextCell}
                sortable={false}
            />
        </GridTable>
    );
};

export default JobsTable;
