import StyledWrapper from "@insite/client-framework/Common/StyledWrapper";
import getFileExtension from "@insite/client-framework/Common/Utilities/getFileExtension";
import { makeHandlerChainAwaitable } from "@insite/client-framework/HandlerCreator";
import siteMessage from "@insite/client-framework/SiteMessage";
import ApplicationState from "@insite/client-framework/Store/ApplicationState";
import cleanupUploadData from "@insite/client-framework/Store/Components/VmiUsersImportModal/Handlers/CleanupUploadData";
import processFile from "@insite/client-framework/Store/Components/VmiUsersImportModal/Handlers/ProcessFile";
import setAllowCancel from "@insite/client-framework/Store/Components/VmiUsersImportModal/Handlers/SetAllowCancel";
import setErrorsModalIsOpen from "@insite/client-framework/Store/Components/VmiUsersImportModal/Handlers/SetErrorsModalIsOpen";
import setIsBadFile from "@insite/client-framework/Store/Components/VmiUsersImportModal/Handlers/SetIsBadFile";
import setIsUploading from "@insite/client-framework/Store/Components/VmiUsersImportModal/Handlers/SetIsUploading";
import setUploadCancelled from "@insite/client-framework/Store/Components/VmiUsersImportModal/Handlers/SetUploadCancelled";
import setUploadLimitExceeded from "@insite/client-framework/Store/Components/VmiUsersImportModal/Handlers/SetUploadLimitExceeded";
import setVmiUsersImportModalIsOpen from "@insite/client-framework/Store/Components/VmiUsersImportModal/Handlers/SetVmiUsersImportModalIsOpen";
import uploadVmiUsers from "@insite/client-framework/Store/Components/VmiUsersImportModal/Handlers/UploadVmiUsers";
import validateVmiUsers from "@insite/client-framework/Store/Components/VmiUsersImportModal/Handlers/ValidateVmiUsers";
import translate from "@insite/client-framework/Translate";
import { VmiUserImportCollectionModel } from "@insite/client-framework/Types/ApiModels";
import Button, { ButtonPresentationProps } from "@insite/mobius/Button";
import Checkbox, { CheckboxPresentationProps, CheckboxProps } from "@insite/mobius/Checkbox";
import FileUpload, { FileUploadPresentationProps } from "@insite/mobius/FileUpload";
import GridContainer, { GridContainerProps } from "@insite/mobius/GridContainer";
import GridItem, { GridItemProps } from "@insite/mobius/GridItem";
import Link, { LinkPresentationProps } from "@insite/mobius/Link";
import LoadingSpinner, { LoadingSpinnerProps } from "@insite/mobius/LoadingSpinner";
import Modal, { ModalPresentationProps } from "@insite/mobius/Modal";
import Typography, { TypographyPresentationProps } from "@insite/mobius/Typography";
import getColor from "@insite/mobius/utilities/getColor";
import InjectableCss from "@insite/mobius/utilities/InjectableCss";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { connect, ResolveThunks } from "react-redux";
import { css } from "styled-components";

const mapStateToProps = (state: ApplicationState) => {
    return {
        parsedItems: state.components.vmiUsersImportModal.parsedItems,
        isUploading: state.components.vmiUsersImportModal.isUploading,
        vmiUsersProcessed: state.components.vmiUsersImportModal.vmiUsersProcessed,
        errorEntries: state.components.vmiUsersImportModal.errorEntries,
        isBadFile: state.components.vmiUsersImportModal.isBadFile,
        fullFileError: state.components.vmiUsersImportModal.fullFileError,
        importedItems: state.components.vmiUsersImportModal.importedItems,
        allowCancel: state.components.vmiUsersImportModal.allowCancel,
        uploadCancelled: state.components.vmiUsersImportModal.uploadCancelled,
        uploadLimitExceeded: state.components.vmiUsersImportModal.uploadLimitExceeded,
        isOpen: state.components.vmiUsersImportModal.modalIsOpen,
        continueUpload: state.components.vmiUsersImportModal.continueUpload,
    };
};

const mapDispatchToProps = {
    processFile,
    cleanupUploadData,
    setAllowCancel,
    validateVmiUsers,
    setUploadLimitExceeded,
    setErrorsModalIsOpen,
    setIsBadFile,
    setIsUploading,
    setUploadCancelled,
    setVmiUsersImportModalIsOpen,
    uploadVmiUsers: makeHandlerChainAwaitable<Parameters<typeof uploadVmiUsers>[0], VmiUserImportCollectionModel>(
        uploadVmiUsers,
    ),
};

type Props = ReturnType<typeof mapStateToProps> & ResolveThunks<typeof mapDispatchToProps>;

export interface VmiUsersImportModalStyles {
    modal?: ModalPresentationProps;
    container?: GridContainerProps;

    uploadInputGridItem?: GridItemProps;
    controlsGridItem?: GridItemProps;
    firstRowOptionCheckbox?: CheckboxPresentationProps;
    uploadButton?: ButtonPresentationProps;
    instructionGridItem?: GridItemProps;
    instructionText?: TypographyPresentationProps;

    fileUploader?: FileUploadPresentationProps;
    templateLink?: LinkPresentationProps;

    uploadingModal?: ModalPresentationProps;
    centeringWrapper?: InjectableCss;
    spinner?: LoadingSpinnerProps;
    uploadingModalText?: TypographyPresentationProps;
    cancelUploadButton?: ButtonPresentationProps;

    uploadsuccessModal?: ModalPresentationProps;
    returnToVmiUsersButton?: ButtonPresentationProps;
}

export const vmiUsersImportModalStyles: VmiUsersImportModalStyles = {
    modal: {
        cssOverrides: {
            modalBody: css`
                overflow: visible;
            `,
        },
    },
    container: { gap: 15 },
    uploadInputGridItem: { width: 6 },
    controlsGridItem: {
        width: 12,
        css: css`
            display: block;
            border: 1px solid ${getColor("common.border")};
            padding: 20px;
        `,
    },
    firstRowOptionCheckbox: {
        css: css`
            margin: 15px 0;
            display: block;
        `,
    },
    uploadButton: {
        css: css`
            float: right;
        `,
    },
    instructionGridItem: { width: 6 },
    instructionText: {
        css: css`
            margin-bottom: 12px;
        `,
    },
    fileUploader: {
        buttonProps: {
            variant: "tertiary",
        },
    },
    centeringWrapper: {
        css: css`
            height: 50px;
            display: flex;
            align-items: center;
        `,
    },
    uploadingModal: {
        cssOverrides: {
            modalTitle: css`
                border-bottom: none;
                padding: 0;
            `,
            modalContent: css`
                text-align: center;
            `,
        },
    },
    spinner: {
        css: css`
            margin: 0 auto;
        `,
    },
    uploadingModalText: {
        css: css`
            margin: 15px 0;
        `,
    },
    uploadsuccessModal: {
        headlineTypographyProps: {
            size: 19,
            color: "success.main",
        },
        cssOverrides: {
            modalTitle: css`
                border-bottom: none;
            `,
            modalContent: css`
                padding: 0 30px 25px 30px;
            `,
        },
    },
};

const styles = vmiUsersImportModalStyles;

const VmiUsersImportModal = ({
    isOpen,
    parsedItems,
    isUploading,
    vmiUsersProcessed,
    errorEntries,
    isBadFile,
    fullFileError,
    importedItems,
    allowCancel,
    uploadCancelled,
    uploadLimitExceeded,
    continueUpload,
    processFile,
    cleanupUploadData,
    setAllowCancel,
    validateVmiUsers,
    setUploadLimitExceeded,
    setErrorsModalIsOpen,
    setIsBadFile,
    setIsUploading,
    setUploadCancelled,
    setVmiUsersImportModalIsOpen,
    uploadVmiUsers,
}: Props) => {
    const fileUploadRef = useRef({ value: "" } as HTMLInputElement);

    const [file, setFile] = useState<any>(null);
    const [incorrectFileExtension, setIncorrectFileExtension] = React.useState(false);
    const [firstRowHeading, setFirstRowHeading] = useState(true);
    const [uploadedItemsCount, setUploadedItemsCount] = useState(0);

    const [isUploadingModalOpen, setIsUploadingModalOpen] = useState(false);
    const [isUploadSuccessModalOpen, setIsUploadSuccessModalOpen] = useState(false);

    useEffect(() => {
        if (isOpen || isUploadingModalOpen) {
            batchGetVmiUsers();
        }
    }, [parsedItems]);

    useEffect(() => checkCompletion(), [vmiUsersProcessed]);

    useEffect(() => {
        if (!isOpen) {
            resetState();
            cleanupUploadData();
        }
    }, [isOpen]);

    useEffect(() => {
        if (continueUpload) {
            uploadUsers();
        }
    }, [continueUpload]);

    const checkCompletion = useCallback(() => {
        if (!vmiUsersProcessed || uploadCancelled) {
            return;
        }

        if (importedItems && errorEntries.length === 0 && !fullFileError) {
            uploadUsers();
        } else {
            setIsUploadingModalOpen(false);
            setErrorsModalIsOpen({ errorsModalIsOpen: true });
        }
    }, [vmiUsersProcessed, uploadCancelled, errorEntries]);

    const resetState = () => {
        setFile(null);
        setIncorrectFileExtension(false);
        setUploadLimitExceeded({ uploadLimitExceeded: false });
        setIsBadFile({ isBadFile: false });
    };

    const closeModalHandler = () => {
        setIsUploading({ isUploading: false });
        setVmiUsersImportModalIsOpen({ modalIsOpen: false });
    };

    const firstRowHeadingChangeHandler: CheckboxProps["onChange"] = (_, value) => setFirstRowHeading(value);

    const batchGetVmiUsers = () => {
        cleanupUploadData();
        if (parsedItems.length === 0) {
            setIsBadFile({ isBadFile: true });
            return;
        }

        validateVmiUsers({ firstRowHeading: false, validationOnly: true });
    };

    const uploadUsers = async () => {
        setAllowCancel({ allowCancel: false });
        await uploadVmiUsers({ vmiUsers: importedItems, validationOnly: false });
        onUploadingSuccess();
    };

    const onUploadingSuccess = () => {
        setIsUploadingModalOpen(false);
        setUploadedItemsCount(importedItems.length);
        setIsUploading({ isUploading: false });
        setIsUploadSuccessModalOpen(true);
        cleanupUploadData();
    };

    const cancelUploadingHandler = () => {
        setUploadCancelled({ uploadCancelled: true });
        setIsUploadingModalOpen(false);
        setIsUploading({ isUploading: false });
        cleanupUploadData();
        setFile(null);
        if (fileUploadRef.current?.value) {
            fileUploadRef.current.value = "";
        }
        setFirstRowHeading(false);
    };

    const returnToVmiUsersHandler = () => {
        setIsUploadSuccessModalOpen(false);
    };

    const fileChangeHandler = (event: React.ChangeEvent<any>) => {
        const uploadedFile = event.target.files[0];
        setFile(uploadedFile);
        if (uploadedFile) {
            const fileExtension = getFileExtension(uploadedFile.name);
            const incorrectFileExtension = ["xls", "xlsx", "csv"].indexOf(fileExtension) === -1;
            setIncorrectFileExtension(incorrectFileExtension);
            setIsBadFile({ isBadFile: incorrectFileExtension });
            setUploadLimitExceeded({ uploadLimitExceeded: false });
        }
    };

    const onUploadClick = () => {
        setUploadCancelled({ uploadCancelled: false });

        const reader = new FileReader();
        reader.onload = onReaderLoad(getFileExtension(file.name));
        reader.readAsArrayBuffer(file);
    };

    const onReaderLoad = (fileExtension: string) => {
        return (e: Event) => {
            const data = (e.target as any).result;
            processFile({ data, fileExtension, firstRowHeading });
            if (!isBadFile && !uploadLimitExceeded) {
                setAllowCancel({ allowCancel: true });
                setVmiUsersImportModalIsOpen({ modalIsOpen: false });
                setIsUploadingModalOpen(true);
            }
        };
    };

    return (
        <>
            <Modal
                {...styles.modal}
                handleClose={() => closeModalHandler()}
                headline={translate("Import Users")}
                isOpen={isOpen}
                size={800}
            >
                <GridContainer {...styles.container}>
                    <GridItem {...styles.uploadInputGridItem}>
                        <GridItem {...styles.controlsGridItem}>
                            <FileUpload
                                {...styles.fileUploader}
                                inputRef={fileUploadRef}
                                fileName={file?.name || ""}
                                accept=".xls,.xlsx,.csv"
                                labelPosition="top"
                                buttonText={translate("Browse")}
                                error={
                                    incorrectFileExtension
                                        ? translate("must be .xls, .xlsx or .csv")
                                        : uploadLimitExceeded
                                        ? siteMessage("Vmi_VmiUserImport_RowsLimitExceeded")
                                        : isBadFile
                                        ? siteMessage("Vmi_VmiUserImport_UploadError")
                                        : undefined
                                }
                                onFileChange={fileChangeHandler}
                                uid="vmiUserUploadFileUpload"
                            />
                            <Checkbox
                                {...styles.firstRowOptionCheckbox}
                                checked={firstRowHeading}
                                onChange={firstRowHeadingChangeHandler}
                            >
                                {translate("First row is column headings")}
                            </Checkbox>
                            <Button
                                {...styles.uploadButton}
                                type="button"
                                disabled={!file || isBadFile}
                                onClick={onUploadClick}
                            >
                                {translate("Upload VMI Users")}
                            </Button>
                        </GridItem>
                    </GridItem>
                    <GridItem {...styles.instructionGridItem}>
                        <Typography as="p" {...styles.instructionText}>
                            {siteMessage("Vmi_VmiUserImport_Instructions")}
                            <Link href="/Excel/VMIImport_userProfiles.csv" target="_blank" {...styles.templateLink}>
                                {translate("Download the template")}
                            </Link>
                        </Typography>
                    </GridItem>
                </GridContainer>
            </Modal>
            <Modal {...styles.uploadingModal} isOpen={isUploadingModalOpen} size={290} isCloseable={false}>
                <StyledWrapper {...styles.centeringWrapper}>
                    <LoadingSpinner {...styles.spinner} />
                </StyledWrapper>
                <Typography as="h3" {...styles.uploadingModalText}>
                    {uploadCancelled ? translate("Cancelling") : translate("Uploading Users")}...
                </Typography>
                <Button
                    {...styles.cancelUploadButton}
                    onClick={cancelUploadingHandler}
                    disabled={!isUploading || !allowCancel || uploadCancelled}
                >
                    {translate("Cancel Upload")}
                </Button>
            </Modal>
            <Modal
                {...styles.uploadsuccessModal}
                isOpen={isUploadSuccessModalOpen}
                headline={`${uploadedItemsCount} ${translate("users uploaded")}.`}
                size={290}
                isCloseable={false}
            >
                <Button {...styles.returnToVmiUsersButton} onClick={returnToVmiUsersHandler}>
                    {translate("Return To Vmi Users")}
                </Button>
            </Modal>
        </>
    );
};

export default connect(mapStateToProps, mapDispatchToProps)(VmiUsersImportModal);
