import { InvoicesDataViewContext } from "@insite/client-framework/Store/Data/Invoices/InvoicesSelectors";
import updateSearchFields from "@insite/client-framework/Store/Pages/InvoiceHistory/Handlers/UpdateSearchFields";
import WidgetModule from "@insite/client-framework/Types/WidgetModule";
import WidgetProps from "@insite/client-framework/Types/WidgetProps";
import Pagination, { PaginationPresentationProps } from "@insite/mobius/Pagination";
import React, { useContext, useEffect, useState } from "react";
import { connect, ResolveThunks } from "react-redux";

const mapDispatchToProps = {
    updateSearchFields,
};

type Props = WidgetProps & ResolveThunks<typeof mapDispatchToProps>;

export interface InvoiceHistoryPaginationStyles {
    pagination?: PaginationPresentationProps;
}

export const paginationStyles: InvoiceHistoryPaginationStyles = {};

const styles = paginationStyles;

const InvoiceHistoryPagination = ({ updateSearchFields }: Props) => {
    const invoicesDataView = useContext(InvoicesDataViewContext);
    const pagination = invoicesDataView.value && invoicesDataView.pagination ? invoicesDataView.pagination : undefined;

    const [shouldScrollToTop, setShouldScrollToTop] = useState(false);
    useEffect(() => {
        if (shouldScrollToTop) {
            window.scrollTo(0, 0);
            setShouldScrollToTop(false);
        }
    }, [pagination?.page]);

    if (!pagination) {
        return null;
    }

    const { totalItemCount, page, pageSize, pageSizeOptions, prevPageUri, nextPageUri } = pagination;
    if (totalItemCount === 0) {
        return null;
    }

    const changePage = (newPageIndex: number) => {
        updateSearchFields({
            page: newPageIndex,
        });
        setShouldScrollToTop(true);
    };

    const changeResultsPerPage = (event: React.ChangeEvent<HTMLSelectElement>) => {
        const newPageSize = parseInt(event.currentTarget.value, 10);
        updateSearchFields({
            page: 1,
            pageSize: newPageSize,
        });
    };

    return (
        <Pagination
            {...styles.pagination}
            resultsCount={totalItemCount}
            currentPage={page}
            resultsPerPage={pageSize}
            resultsPerPageOptions={pageSizeOptions}
            onChangePage={changePage}
            onChangeResultsPerPage={changeResultsPerPage}
            pageSizeCookie="InvoiceHistory-PageSize"
            prevPage={prevPageUri}
            nextPage={nextPageUri}
        />
    );
};

const widgetModule: WidgetModule = {
    component: connect(null, mapDispatchToProps)(InvoiceHistoryPagination),
    definition: {
        group: "Invoice History",
        displayName: "Pagination",
        allowedContexts: ["InvoiceHistoryPage"],
    },
};

export default widgetModule;
