import StyledWrapper from "@insite/client-framework/Common/StyledWrapper";
import siteMessage from "@insite/client-framework/SiteMessage";
import ApplicationState from "@insite/client-framework/Store/ApplicationState";
import cleanupUploadData from "@insite/client-framework/Store/Components/VmiLocationsImportModal/Handlers/CleanupUploadData";
import setContinueUpload from "@insite/client-framework/Store/Components/VmiLocationsImportModal/Handlers/SetContinueUpload";
import setErrorsModalIsOpen from "@insite/client-framework/Store/Components/VmiLocationsImportModal/Handlers/SetErrorsModalIsOpen";
import setIsUploading from "@insite/client-framework/Store/Components/VmiLocationsImportModal/Handlers/SetIsUploading";
import setUploadCancelled from "@insite/client-framework/Store/Components/VmiLocationsImportModal/Handlers/SetUploadCancelled";
import { VmiLocationUploadError } from "@insite/client-framework/Store/Components/VmiLocationsImportModal/Handlers/ValidateVmiLocations";
import translate from "@insite/client-framework/Translate";
import Button, { ButtonPresentationProps } from "@insite/mobius/Button";
import DataTable, { DataTableProps } from "@insite/mobius/DataTable";
import DataTableBody, { DataTableBodyProps } from "@insite/mobius/DataTable/DataTableBody";
import DataTableCell from "@insite/mobius/DataTable/DataTableCell";
import { DataTableCellBaseProps } from "@insite/mobius/DataTable/DataTableCellBase";
import DataTableHead, { DataTableHeadProps } from "@insite/mobius/DataTable/DataTableHead";
import DataTableHeader, { DataTableHeaderProps } from "@insite/mobius/DataTable/DataTableHeader";
import DataTableRow, { DataTableRowProps } from "@insite/mobius/DataTable/DataTableRow";
import Icon, { IconPresentationProps } from "@insite/mobius/Icon";
import Link, { LinkPresentationProps } from "@insite/mobius/Link";
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 from "react";
import { connect, ResolveThunks } from "react-redux";
import { css } from "styled-components";

const mapStateToProps = (state: ApplicationState) => ({
    errorsModalIsOpen: state.components.vmiLocationsImportModal.errorsModalIsOpen,
    fullFileError: state.components.vmiLocationsImportModal.fullFileError,
    errorEntries: state.components.vmiLocationsImportModal.errorEntries,
    importedItems: state.components.vmiLocationsImportModal.importedItems,
});

const mapDispatchToProps = {
    setErrorsModalIsOpen,
    setContinueUpload,
    cleanupUploadData,
    setUploadCancelled,
    setIsUploading,
};

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

export interface VmiLocationsErrorsModalStyles {
    modal?: ModalPresentationProps;
    warningIcon?: IconPresentationProps;
    headerText?: TypographyPresentationProps;

    dataTable?: DataTableProps;
    tableHead?: DataTableHeadProps;
    rowNumberHeader?: DataTableHeaderProps;
    billToHeader?: DataTableHeaderProps;
    shipToHeader?: DataTableHeaderProps;
    nameHeader?: DataTableHeaderProps;
    reasonHeader?: DataTableHeaderProps;
    tableBody?: DataTableBodyProps;
    tableRow?: DataTableRowProps;
    rowNumberCell?: DataTableCellBaseProps;
    billToCell?: DataTableCellBaseProps;
    shipToCell?: DataTableCellBaseProps;
    nameCell?: DataTableCellBaseProps;
    reasonCell?: DataTableCellBaseProps;

    instructionText?: TypographyPresentationProps;
    templateLink?: LinkPresentationProps;
    buttonsWrapper?: InjectableCss;
    cancelUploadButton?: ButtonPresentationProps;
    continueUploadButton?: ButtonPresentationProps;
}

export const vmiLocationsErrorsModalStyles: VmiLocationsErrorsModalStyles = {
    modal: {
        sizeVariant: "medium",
        cssOverrides: {
            modalTitle: css`
                padding: 10px 20px;
                justify-content: flex-start;
                font-weight: bold;
                font-size: 17px;
            `,
            modalContent: css`
                padding: 20px;
            `,
        },
    },
    warningIcon: {
        src: "AlertTriangle",
        color: "danger.main",
        css: css`
            margin-right: 10px;
        `,
    },
    dataTable: {
        cssOverrides: {
            table: css`
                margin-top: 15px;
            `,
        },
    },
    tableBody: {
        css: css`
            color: ${getColor("danger.main")};
        `,
    },
    instructionText: {
        css: css`
            margin-bottom: 12px;
        `,
    },
    buttonsWrapper: {
        css: css`
            margin-top: 30px;
            text-align: right;
        `,
    },
    cancelUploadButton: {
        variant: "secondary",
    },
    continueUploadButton: {
        css: css`
            margin-left: 10px;
        `,
    },
};

const styles = vmiLocationsErrorsModalStyles;

const VmiLocationsErrorsModal = ({
    errorsModalIsOpen,
    fullFileError,
    errorEntries,
    importedItems,
    setErrorsModalIsOpen,
    setContinueUpload,
    cleanupUploadData,
    setUploadCancelled,
    setIsUploading,
}: Props) => {
    const cancelUploadClickHandler = () => {
        setErrorsModalIsOpen({ errorsModalIsOpen: false });
        setUploadCancelled({ uploadCancelled: true });
        setIsUploading({ isUploading: false });
        cleanupUploadData();
    };

    const continueUploadClickHandler = () => {
        setErrorsModalIsOpen({ errorsModalIsOpen: false });
        setContinueUpload({ continueUpload: true });
    };

    return (
        <Modal
            {...styles.modal}
            headline={
                <>
                    <Icon {...styles.warningIcon}></Icon>
                    <Typography {...styles.headerText}>{`${siteMessage("VmiLocationUpload_Failure")}${
                        fullFileError ? "." : ":"
                    }`}</Typography>
                </>
            }
            data-test-selector="vmiLocaltionErrorsModal"
            isOpen={errorsModalIsOpen}
            isCloseable={false}
        >
            {!fullFileError && (
                <DataTable {...styles.dataTable}>
                    <DataTableHead {...styles.tableHead}>
                        <DataTableHeader {...styles.rowNumberHeader}>{translate("Row #")}</DataTableHeader>
                        <DataTableHeader {...styles.billToHeader}>{translate("Customer Number")}</DataTableHeader>
                        <DataTableHeader {...styles.shipToHeader}>{translate("Customer Sequence")}</DataTableHeader>
                        <DataTableHeader {...styles.nameHeader}>{translate("Location Name")}</DataTableHeader>
                        <DataTableHeader {...styles.reasonHeader}>{translate("Reason")}</DataTableHeader>
                    </DataTableHead>
                    <DataTableBody {...styles.tableBody}>
                        {errorEntries.map(({ index, customerNumber, customerSequence, name, error }) => (
                            <DataTableRow key={index} {...styles.tableRow}>
                                <DataTableCell {...styles.rowNumberCell}>{index}</DataTableCell>
                                <DataTableCell {...styles.billToCell}>{customerNumber}</DataTableCell>
                                <DataTableCell {...styles.shipToCell}>{customerSequence}</DataTableCell>
                                <DataTableCell {...styles.nameCell}>{name}</DataTableCell>
                                <DataTableCell {...styles.reasonCell} data-test-selector={`vmi-error-reason`}>
                                    {error === VmiLocationUploadError.NoBillTo &&
                                        siteMessage("Field_Required", translate("Customer Number"))}
                                    {error === VmiLocationUploadError.BillToNotFound &&
                                        siteMessage("Customer_BillToNotFound")}
                                    {error === VmiLocationUploadError.NoShipTo &&
                                        siteMessage("Field_Required", translate("Customer Sequence"))}
                                    {error === VmiLocationUploadError.ShipToNotFound &&
                                        siteMessage("Customer_ShipToNotFound")}
                                    {error === VmiLocationUploadError.NoLocationName &&
                                        siteMessage("Field_Required", translate("Location Name"))}
                                    {error === VmiLocationUploadError.DuplicateLocationName &&
                                        siteMessage("Vmi_VmiLocationDuplicate")}
                                    {error === VmiLocationUploadError.DuplicateLocationNameSameFile &&
                                        siteMessage("Vmi_VmiLocationDuplicate_SameFile")}
                                    {error === VmiLocationUploadError.LocationNameTooLong &&
                                        siteMessage("Field_Too_Long", translate("Location Name"), "255")}
                                </DataTableCell>
                            </DataTableRow>
                        ))}
                    </DataTableBody>
                </DataTable>
            )}
            {fullFileError && (
                <Typography as="p" {...styles.instructionText}>
                    {siteMessage("VmiLocationUpload_Instructions_Line1_Part1")}
                    <Link href="/Excel/VMIImport_LocationsTemplate.csv" target="_blank" {...styles.templateLink}>
                        {translate("Download the template")}
                    </Link>
                    {siteMessage("VmiLocationUpload_Instructions_Line1_Part2")}
                </Typography>
            )}
            <StyledWrapper {...styles.buttonsWrapper}>
                <Button {...styles.cancelUploadButton} onClick={cancelUploadClickHandler}>
                    {translate("Cancel Upload")}
                </Button>
                <Button
                    {...styles.continueUploadButton}
                    onClick={continueUploadClickHandler}
                    disabled={!importedItems || importedItems.length === 0 || fullFileError}
                >
                    {translate("Continue Upload")}
                </Button>
            </StyledWrapper>
        </Modal>
    );
};

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