import { getCookie } from "@insite/client-framework/Common/Cookies";
import Zone from "@insite/client-framework/Components/Zone";
import ApplicationState from "@insite/client-framework/Store/ApplicationState";
import { getCurrentPage } from "@insite/client-framework/Store/Data/Pages/PageSelectors";
import loadVmiLocations from "@insite/client-framework/Store/Data/VmiLocations/Handlers/LoadVmiLocations";
import { getVmiLocationsDataView } from "@insite/client-framework/Store/Data/VmiLocations/VmiLocationsSelectors";
import toggleFiltersOpen from "@insite/client-framework/Store/Pages/OrderHistory/Handlers/ToggleFiltersOpen";
import updateSearchFields from "@insite/client-framework/Store/Pages/OrderHistory/Handlers/UpdateSearchFields";
import translate from "@insite/client-framework/Translate";
import WidgetModule from "@insite/client-framework/Types/WidgetModule";
import WidgetProps from "@insite/client-framework/Types/WidgetProps";
import { NavigationModeCookieName } from "@insite/content-library/Components/NavigationModeMenu";
import Button, { ButtonIcon, ButtonIconPresentationProps, ButtonPresentationProps } from "@insite/mobius/Button";
import { ClickablePresentationProps } from "@insite/mobius/Clickable";
import GridContainer, { GridContainerProps } from "@insite/mobius/GridContainer";
import GridItem, { GridItemProps } from "@insite/mobius/GridItem";
import { IconPresentationProps } from "@insite/mobius/Icon";
import Filter from "@insite/mobius/Icons/Filter";
import Select, { SelectPresentationProps } from "@insite/mobius/Select";
import Typography, { TypographyPresentationProps } from "@insite/mobius/Typography";
import React, { useEffect } from "react";
import { connect, ResolveThunks } from "react-redux";
import { css } from "styled-components";

interface OwnProps extends WidgetProps {}

const mapStateToProps = (state: ApplicationState) => {
    const currentMode = getCookie(NavigationModeCookieName) || "Storefront";
    return {
        vmiLocationsDataView: getVmiLocationsDataView(state, state.pages.orderHistory.getVmiLocationsParameter),
        getOrdersParameter: state.pages.orderHistory.getOrdersParameter,
        getVmiLocationsParameter: state.pages.orderHistory.getVmiLocationsParameter,
        currentMode,
        currentPage: getCurrentPage(state),
    };
};

const mapDispatchToProps = {
    toggleFiltersOpen,
    updateSearchFields,
    loadVmiLocations,
};

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

export interface OrderHistoryHeaderStyles {
    container?: GridContainerProps;
    invoiceCountGridItem?: GridItemProps;
    emptyGridItem?: GridItemProps;
    toggleFilterGridItem?: GridItemProps;
    /** @deprecated Use toggleFilterButtonIcon instead. */
    toggleFilterIcon?: IconPresentationProps;
    /** @deprecated Use toggleFilterButton instead. */
    toggleFilterClickable?: ClickablePresentationProps;
    toggleFilterButton?: ButtonPresentationProps;
    toggleFilterButtonIcon?: ButtonIconPresentationProps;
    gridContainer?: GridContainerProps;
    titleGridItem?: GridItemProps;
    titleText?: TypographyPresentationProps;
    locationSwitcherGridItem?: GridItemProps;
    locationSelect?: SelectPresentationProps;
}

export const headerStyles: OrderHistoryHeaderStyles = {
    container: {
        gap: 8,
        css: css`
            padding-bottom: 20px;
        `,
    },
    invoiceCountGridItem: {
        width: 11,
        style: { fontWeight: 600 },
    },
    toggleFilterGridItem: {
        width: 1,
        style: { justifyContent: "flex-end" },
    },
    toggleFilterButton: {
        color: "common.background",
        shape: "pill",
        buttonType: "solid",
        shadow: false,
        css: css`
            width: 40px;
            padding: 0;
        `,
    },
    toggleFilterButtonIcon: {
        src: Filter,
        size: 24,
    },
    titleGridItem: {
        width: [10, 10, 8, 9, 9],
    },
    titleText: {
        variant: "h2",
    },
    locationSwitcherGridItem: {
        css: css`
            justify-content: flex-end;
        `,
        width: [2, 2, 4, 3, 3],
    },
    locationSelect: {
        cssOverrides: {
            formInputWrapper: css`
                width: 200px;
                align-self: end;
            `,
            inputSelect: css`
                text-transform: uppercase;
            `,
        },
    },
};
const styles = headerStyles;

const OrderHistoryHeader = ({
    toggleFiltersOpen,
    id,
    vmiLocationsDataView,
    loadVmiLocations,
    getVmiLocationsParameter,
    getOrdersParameter,
    updateSearchFields,
    currentMode,
    currentPage,
}: Props) => {
    useEffect(() => {
        if (
            currentMode === "Vmi" &&
            (!vmiLocationsDataView || (!vmiLocationsDataView.value && !vmiLocationsDataView.isLoading))
        ) {
            loadVmiLocations(getVmiLocationsParameter);
        }
    }, [getVmiLocationsParameter]);

    const handleChange = (event: React.FormEvent<HTMLSelectElement>) => {
        updateSearchFields({ vmiLocationId: event.currentTarget.value });
    };
    return (
        <>
            {vmiLocationsDataView &&
                vmiLocationsDataView.value &&
                currentMode === "Vmi" &&
                currentPage.type === "VmiOrderHistoryPage" && (
                    <GridContainer {...styles.gridContainer}>
                        <GridItem {...styles.titleGridItem}>
                            <Typography as="h2" {...styles.titleText}>
                                {translate("Orders")}
                            </Typography>
                        </GridItem>
                        <GridItem {...styles.locationSwitcherGridItem}>
                            <Select
                                {...styles.locationSelect}
                                onChange={handleChange}
                                value={getOrdersParameter.vmiLocationId || ""}
                                aria-label={translate("Select Location")}
                            >
                                <option value="">{translate("All Locations")}</option>
                                {vmiLocationsDataView.value.map(c => (
                                    <option value={c.id} key={c.id}>
                                        {c.name}
                                    </option>
                                ))}
                            </Select>
                        </GridItem>
                    </GridContainer>
                )}
            <GridContainer {...styles.container}>
                <GridItem {...styles.invoiceCountGridItem}>
                    <Zone contentId={id} zoneName="Content" />
                </GridItem>
                <GridItem {...styles.toggleFilterGridItem}>
                    <Button
                        {...styles.toggleFilterButton}
                        onClick={() => toggleFiltersOpen()}
                        aria-label={translate("Toggle Filter")}
                        data-test-selector="orderHistory_showHideFilters"
                    >
                        <ButtonIcon {...styles.toggleFilterButtonIcon} />
                    </Button>
                </GridItem>
            </GridContainer>
        </>
    );
};

const widgetModule: WidgetModule = {
    component: connect(mapStateToProps, mapDispatchToProps)(OrderHistoryHeader),
    definition: {
        group: "Order History",
        displayName: "Header",
        allowedContexts: ["OrderHistoryPage", "VmiOrderHistoryPage"],
    },
};

export default widgetModule;
