import { parserOptions } from "@insite/client-framework/Common/BasicSelectors";
import useGoogleMaps from "@insite/client-framework/Common/Hooks/useGoogleMaps";
import useWarehouseFilterSearch from "@insite/client-framework/Common/Hooks/useWarehouseFilterSearch";
import useWarehouseGoogleMarkers from "@insite/client-framework/Common/Hooks/useWarehouseGoogleMarkers";
import StyledWrapper, { getStyledWrapper } from "@insite/client-framework/Common/StyledWrapper";
import { Dictionary } from "@insite/client-framework/Common/Types";
import { getGeoCodeFromLatLng } from "@insite/client-framework/Common/Utilities/GoogleMaps/getGeoCodeFromAddress";
import withDynamicGoogleMaps, { HasDynamicGoogleMaps } from "@insite/client-framework/Common/withDynamicGoogleMaps";
import { makeHandlerChainAwaitable } from "@insite/client-framework/HandlerCreator";
import siteMessage from "@insite/client-framework/SiteMessage";
import ApplicationState from "@insite/client-framework/Store/ApplicationState";
import loadRealTimeCartInventory from "@insite/client-framework/Store/CommonHandlers/LoadRealTimeCartInventory";
import loadWarehouses from "@insite/client-framework/Store/Components/FindLocationModal/Handlers/LoadWarehouses";
import setStorePickupOverlayIsOpen from "@insite/client-framework/Store/Components/StorePickupOverlay/Handlers/SetStorePickupOverlayIsOpen";
import { getSession, getSettingsCollection } from "@insite/client-framework/Store/Context/ContextSelectors";
import updatePickUpWarehouse from "@insite/client-framework/Store/Context/Handlers/UpdatePickUpWarehouse";
import { getCurrentCartState } from "@insite/client-framework/Store/Data/Carts/CartsSelector";
import { getWarehousesDataView } from "@insite/client-framework/Store/Data/Warehouses/WarehousesSelectors";
import translate from "@insite/client-framework/Translate";
import {
    AvailabilityDto,
    AvailabilityMessageType,
    PaginationModel,
    RealTimeCartInventoryModel,
    WarehouseModel,
} from "@insite/client-framework/Types/ApiModels";
import WidgetModule from "@insite/client-framework/Types/WidgetModule";
import WidgetProps from "@insite/client-framework/Types/WidgetProps";
import AddressInfoCondensedDisplay, {
    AddressInfoCondensedDisplayStyles,
} from "@insite/content-library/Components/AddressInfoCondensedDisplay";
import DistanceDisplay, { DistanceUnitOfMeasure } from "@insite/content-library/Components/DistanceDisplay";
import WarehouseGoogleMap, { WarehouseGoogleMapStyles } from "@insite/content-library/Components/WarehouseGoogleMap";
import Button, { ButtonPresentationProps } from "@insite/mobius/Button";
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 Pagination, { PaginationPresentationProps } from "@insite/mobius/Pagination";
import Radio, { RadioComponentProps } from "@insite/mobius/Radio";
import RadioGroup, { RadioGroupProps } from "@insite/mobius/RadioGroup";
import Tab, { TabPresentationProps } from "@insite/mobius/Tab";
import TabGroup, { TabGroupPresentationProps } from "@insite/mobius/TabGroup";
import TextField, { TextFieldPresentationProps } from "@insite/mobius/TextField";
import ToasterContext from "@insite/mobius/Toast/ToasterContext";
import Typography, { TypographyPresentationProps } from "@insite/mobius/Typography";
import breakpointMediaQueries from "@insite/mobius/utilities/breakpointMediaQueries";
import getColor from "@insite/mobius/utilities/getColor";
import InjectableCss from "@insite/mobius/utilities/InjectableCss";
import parse from "html-react-parser";
import React, { useContext, useEffect, useState } from "react";
import { connect, ResolveThunks } from "react-redux";
import styled, { css } from "styled-components";

const mapStateToProps = (state: ApplicationState) => {
    const cartState = getCurrentCartState(state);
    const settingsCollection = getSettingsCollection(state);
    return {
        pickUpWarehouse: getSession(state).pickUpWarehouse,
        warehousesDataView: getWarehousesDataView(state, state.components.findLocationModal.getWarehousesParameter),
        googleMapsApiKey: settingsCollection.websiteSettings.googleMapsApiKey,
        hasProductsInCart: cartState.value && cartState.value.lineCount > 0,
        showInventoryAvailability: settingsCollection.productSettings.showInventoryAvailability,
    };
};

const mapDispatchToProps = {
    loadWarehouses,
    loadRealTimeCartInventory,
    updatePickUpWarehouse: makeHandlerChainAwaitable(updatePickUpWarehouse),
    setStorePickupOverlayIsOpen,
};

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

export interface StorePickupStyles {
    wrapper?: InjectableCss;
    titleText?: TypographyPresentationProps;
    form?: InjectableCss;
    searchGridContainer?: GridContainerProps;
    searchTextFieldGridItem?: GridItemProps;
    searchTextField?: TextFieldPresentationProps;
    searchRadiusGridItem?: GridItemProps;
    searchRadiusText?: TextFieldPresentationProps;
    searchButtonGridItem?: GridItemProps;
    searchButton?: ButtonPresentationProps;
    distanceUnitOfMeasureGridItem?: GridItemProps;
    distanceUnitOfMeasureRadioGroup?: RadioGroupProps;
    distanceUnitOfMeasureImperialRadio?: RadioComponentProps;
    distanceUnitOfMeasureMetricRadio?: RadioComponentProps;
    searchResultsTabGroup?: TabGroupPresentationProps;
    listTab?: TabPresentationProps;
    centeringWrapper?: InjectableCss;
    spinner?: LoadingSpinnerProps;
    siteMessageGridItem?: GridItemProps;
    siteMessageGeocodeErrorText?: TypographyPresentationProps;
    siteMessageResultsErrorText?: TypographyPresentationProps;
    searchResultGridItem?: GridItemProps;
    searchResultGridContainer?: GridContainerProps;
    searchResultForMapGridContainer?: GridContainerProps;
    searchResultWarehouseGridItem?: GridItemProps;
    warehouseNameText?: TypographyPresentationProps;
    searchResultDistanceGridItem?: GridItemProps;
    warehouseDistanceDisplayText?: TypographyPresentationProps;
    searchResultWarehouseAvailabilityGridItem?: GridItemProps;
    availabilityCircle?: InjectableCss;
    warehouseAvailabilityText?: TypographyPresentationProps;
    searchResultAddressInfoGridItem?: GridItemProps;
    warehouseAddressInfoCondensed?: AddressInfoCondensedDisplayStyles;
    searchResultPhoneGridItem?: GridItemProps;
    searchResultPhoneLink?: LinkPresentationProps;
    searchResultSelectGridItem?: GridItemProps;
    searchResultSelectButton?: ButtonPresentationProps;
    searchResultHoursGridItem?: GridItemProps;
    searchResultHoursText?: TypographyPresentationProps;
    paginationGridItem?: GridItemProps;
    pagination?: PaginationPresentationProps;
    mapTab?: TabPresentationProps;
    warehouseGoogleMap?: WarehouseGoogleMapStyles;
}

export const storePickupStyles: StorePickupStyles = {
    titleText: {
        size: 24,
        weight: 600,
        css: css`
            margin-bottom: 1rem;
        `,
    },
    form: {
        css: css`
            width: 100%;
        `,
    },
    searchGridContainer: {
        gap: 0,
    },
    searchTextFieldGridItem: {
        width: 12,
    },
    searchRadiusGridItem: {
        width: 4,
        css: css`
            padding-top: 10px;
        `,
    },
    searchButtonGridItem: {
        width: 12,
    },
    searchButton: {
        css: css`
            margin-top: 20px;
            width: 100%;
        `,
    },
    distanceUnitOfMeasureGridItem: {
        width: 8,
        align: "middle",
    },
    distanceUnitOfMeasureRadioGroup: {
        css: css`
            display: inline-block;
            width: 100%;
            flex-direction: row;
            & > div {
                display: inline-flex;
                margin-left: 5px;
            }
            padding-top: 25px;
        `,
    },
    searchResultsTabGroup: {
        cssOverrides: {
            wrapper: css`
                padding: 10px 0 0 0;
            `,
            tabContent: css`
                padding: 15px 0 0 0;
                border-bottom: none;
            `,
        },
    },
    listTab: {
        css: css`
            padding: 8px 16px;
        `,
    },
    centeringWrapper: {
        css: css`
            width: 100%;
            height: 300px;
            display: flex;
            align-items: center;
        `,
    },
    spinner: {
        css: css`
            margin: auto;
        `,
    },
    siteMessageGridItem: {
        width: 12,
    },
    siteMessageGeocodeErrorText: {
        color: "danger",
        weight: "bold",
    },
    siteMessageResultsErrorText: {
        color: "danger",
        weight: "bold",
    },
    searchResultGridItem: {
        width: 12,
        css: css`
            &:not(:last-child) {
                padding-bottom: 0;
            }
        `,
    },
    searchResultGridContainer: {
        gap: 10,
        css: css`
            padding: 15px;
            margin: 0;
            border: 1px solid ${getColor("common.border")};
        `,
    },
    searchResultForMapGridContainer: {
        gap: 10,
        css: css`
            padding: 5px;
            margin: 0;
        `,
    },
    searchResultWarehouseGridItem: {
        width: 9,
    },
    warehouseNameText: {
        ellipsis: true,
        size: 18,
    },
    searchResultDistanceGridItem: {
        width: 3,
        align: "middle",
        css: css`
            justify-content: right;
        `,
    },
    warehouseDistanceDisplayText: {
        size: 13,
    },
    searchResultWarehouseAvailabilityGridItem: {
        width: 12,
    },
    availabilityCircle: {
        css: css`
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 6px;
            margin-top: 3px;
        `,
    },
    warehouseAvailabilityText: {
        size: 13,
    },
    searchResultAddressInfoGridItem: {
        width: 12,
    },
    warehouseAddressInfoCondensed: {
        addressText: { size: 13 },
        cityStatePostalCodeText: { size: 13 },
        countryText: { size: 13 },
    },
    searchResultPhoneGridItem: {
        width: 12,
    },
    searchResultPhoneLink: {
        typographyProps: { size: 13 },
    },
    searchResultSelectGridItem: {
        width: 12,
    },
    searchResultSelectButton: {
        variant: "secondary",
        css: css`
            width: 100%;
            padding: 0;
        `,
    },
    searchResultHoursGridItem: {
        width: 12,
    },
    searchResultHoursText: {
        size: 13,
    },
    paginationGridItem: {
        width: 12,
        css: css`
            justify-content: center;
        `,
    },
    pagination: {
        cssOverrides: {
            pagination: css`
                ${({ theme }) =>
                    breakpointMediaQueries(
                        theme,
                        [
                            css`
                                margin: 0 0 16px 0;
                            `,
                            null,
                            null,
                            null,
                            null,
                        ],
                        "min",
                    )}
            `,
            perPageSelect: css`
                ${({ theme }) =>
                    breakpointMediaQueries(
                        theme,
                        [
                            css`
                                display: none;
                            `,
                            null,
                            null,
                            null,
                            null,
                        ],
                        "min",
                    )}
            `,
        },
    },
    mapTab: {
        css: css`
            padding: 8px 16px;
        `,
    },
};

const styles = storePickupStyles;

const StyledForm = getStyledWrapper("form");
const AvailabilityCircle = styled.div<{ type: AvailabilityMessageType | null }>`
    ${styles.availabilityCircle?.css}
    background-color: ${props =>
        props.type === AvailabilityMessageType.Available
            ? getColor("success.main")
            : props.type === AvailabilityMessageType.LowStock
            ? getColor("warning.main")
            : props.type === AvailabilityMessageType.OutOfStock
            ? getColor("danger.main")
            : getColor("common.disabled")};
`;

const StorePickup = ({
    pickUpWarehouse,
    googleMapsApiKey,
    warehousesDataView,
    hasProductsInCart,
    showInventoryAvailability,
    loadWarehouses,
    loadRealTimeCartInventory,
    updatePickUpWarehouse,
    setStorePickupOverlayIsOpen,
    useLoadScript,
}: Props) => {
    const toasterContext = useContext(ToasterContext);
    const [distanceUnitOfMeasure, setDistanceUnitOfMeasure] = useState<DistanceUnitOfMeasure>("Imperial");
    const [isLoading, setIsLoading] = useState<boolean>(false);

    const { isLoaded } = useLoadScript({ googleMapsApiKey });
    const {
        googleMap,
        setGoogleMap,
        currentLocation,
        setCurrentLocation,
        isGoogleMapsScriptsLoaded,
        setBounds,
        setMapCenter,
        locationKnown,
        setLocationKnown,
    } = useGoogleMaps({
        isLoaded,
        isShown: true,
    });

    // Manage Selected Warehouse
    const [selectedWarehouse, setSelectedWarehouse] = useState<WarehouseModel | undefined>(undefined);
    const [showSelectedWarehouse, setShowSelectedWarehouse] = useState<boolean>(true);
    const [defaultRadius, setDefaultRadius] = useState<number>(0);
    useEffect(() => {
        setSelectedWarehouse(pickUpWarehouse || undefined);
    }, [pickUpWarehouse]);

    // Manage Local Warehouses
    const [warehouses, setWarehouses] = useState<WarehouseModel[] | undefined>(undefined);
    const [warehousesPagination, setWarehousesPagination] = useState<PaginationModel | undefined>();
    const [warehouseAvailabilities, setWarehouseAvailabilities] = useState<Dictionary<AvailabilityDto> | undefined>();

    // Manage Loading Warehouses on State Changes
    const {
        doSearch,
        warehouseSearchFilter,
        setWarehouseSearchFilter,
        radiusSearchFilter,
        setRadiusSearchFilter,
        setPage,
        setPageSize,
    } = useWarehouseFilterSearch({
        loadWarehouses,
        currentLocation,
        setCurrentLocation,
        setLocationKnown,
        defaultRadius,
        selectedWarehouse,
        setSelectedWarehouse,
        setShowSelectedWarehouse,
        excludeCurrentPickupWarehouse: false,
    });

    useEffect(() => {
        if (!hasProductsInCart || !warehouses || warehouses.length === 0) {
            return;
        }

        loadRealTimeCartInventory({
            warehouseIds: warehouses.map(o => o.id),
            onSuccess: (result: RealTimeCartInventoryModel) => {
                setWarehouseAvailabilities(result.warehouseAvailabilities || ({} as Dictionary<AvailabilityDto>));
            },
        });
    }, [hasProductsInCart, warehouses]);

    // Manage Bounds of Map
    useEffect(() => {
        if (!warehouses) {
            return;
        }

        const bounds = [];
        closeInfoWindows();
        warehouses.forEach(warehouse => {
            bounds.push({ lat: warehouse.latitude, lng: warehouse.longitude });
        });
        if (showSelectedWarehouse && selectedWarehouse) {
            bounds.push({ lat: selectedWarehouse.latitude, lng: selectedWarehouse.longitude });
        }
        setBounds(bounds);
    }, [googleMap, warehouses, selectedWarehouse, showSelectedWarehouse, currentLocation]);

    // Manage Map Markers
    const { mapMarkersElements, currentLocationInfoWindow, warehouseInfoWindow, closeInfoWindows } =
        useWarehouseGoogleMarkers({
            warehouses,
            warehouseSearchFilter,
            warehousesPagination,
            currentLocation,
            selectedWarehouse,
            showSelectedWarehouse,
        });

    useEffect(() => {
        if (!isGoogleMapsScriptsLoaded) {
            return;
        }

        if (!warehousesDataView.value || warehousesDataView.isLoading) {
            setIsLoading(true);
            return;
        }

        const { value: warehouses, pagination, defaultRadius, defaultLatitude, defaultLongitude } = warehousesDataView;
        // Find default location
        getGeoCodeFromLatLng(defaultLatitude, defaultLongitude)
            .then(result => {
                setWarehouseSearchFilter(result[0].formatted_address);
            })
            .finally(() => {
                setWarehousesPagination(pagination || undefined);
                setDefaultRadius(defaultRadius);
                setRadiusSearchFilter(defaultRadius);
                setMapCenter(new google.maps.LatLng(defaultLatitude, defaultLongitude));
                setWarehouses(warehouses || []);
                setIsLoading(false);
            });
    }, [isGoogleMapsScriptsLoaded, warehousesDataView]);

    const handleDistanceUnitOfMeasureChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        const value = event.target.value as DistanceUnitOfMeasure;
        setDistanceUnitOfMeasure(value);
    };

    const warehouseSelectClickHandler = async (warehouse: WarehouseModel) => {
        await updatePickUpWarehouse({ pickUpWarehouse: warehouse });
        setStorePickupOverlayIsOpen({ isOpen: false });
        toasterContext.addToast({
            body: translate("Pick Up Address Updated"),
            messageType: "success",
        });
    };

    const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        event.stopPropagation();
        if (!isLoading) {
            doSearch(warehouseSearchFilter);
        }
    };

    const handleSearchLocationsChanged = (event: React.ChangeEvent<HTMLInputElement>) => {
        setWarehouseSearchFilter(event.target.value);
    };

    const handleSearchRadiusChanged = (event: React.ChangeEvent<HTMLInputElement>) => {
        setRadiusSearchFilter(Number(event.target.value));
    };

    const onChangePage = (page: number) => {
        setPage(page);
    };

    const onChangeResultsPerPage = (event: React.ChangeEvent<HTMLSelectElement>) => {
        setPage(1);
        setPageSize(Number(event.currentTarget.value));
    };

    const renderWarehouseCard = (warehouse: WarehouseModel, index: number, forMap = false) => {
        return (
            <GridContainer
                {...(forMap ? styles.searchResultForMapGridContainer : styles.searchResultGridContainer)}
                data-test-selector="storePickup_warehouse"
                data-test-key={`${warehouse.id}`}
            >
                <GridItem
                    {...styles.searchResultWarehouseGridItem}
                    width={forMap ? 12 : styles.searchResultWarehouseGridItem?.width}
                    data-test-selector={`storePickup_warehouseName_${index}`}
                >
                    <Typography {...styles.warehouseNameText}>{warehouse.description || warehouse.name}</Typography>
                </GridItem>
                {!forMap && (
                    <GridItem {...styles.searchResultDistanceGridItem}>
                        <DistanceDisplay
                            {...styles.warehouseDistanceDisplayText}
                            overrideTitle="{0} {1}"
                            distance={warehouse.distance}
                            unitOfMeasure={distanceUnitOfMeasure}
                            data-test-selector={`storePickup_warehouseDistance_${index}`}
                        />
                    </GridItem>
                )}
                {hasProductsInCart && showInventoryAvailability && (
                    <GridItem {...styles.searchResultWarehouseAvailabilityGridItem}>
                        <AvailabilityCircle
                            {...styles.availabilityCircle}
                            type={warehouseAvailabilities?.[warehouse.id]?.messageType || null}
                        />
                        <Typography
                            {...styles.warehouseAvailabilityText}
                            data-test-selector="storePickup_warehouseAvailabilityText"
                        >
                            {warehouseAvailabilities?.[warehouse.id]?.message || "..."}
                        </Typography>
                    </GridItem>
                )}
                <GridItem {...styles.searchResultAddressInfoGridItem}>
                    <AddressInfoCondensedDisplay {...warehouse} extendedStyles={styles.warehouseAddressInfoCondensed} />
                </GridItem>
                {warehouse.phone && (
                    <GridItem {...styles.searchResultPhoneGridItem}>
                        <Link href={`tel:${warehouse.phone}`} {...styles.searchResultPhoneLink} target="_blank">
                            {warehouse.phone}
                        </Link>
                    </GridItem>
                )}
                {warehouse.hours && (
                    <GridItem {...styles.searchResultHoursGridItem}>
                        <Typography {...styles.searchResultHoursText}>
                            {parse(warehouse.hours, parserOptions)}
                        </Typography>
                    </GridItem>
                )}
                <GridItem {...styles.searchResultSelectGridItem}>
                    <Button
                        {...styles.searchResultSelectButton}
                        type="button"
                        onClick={() => warehouseSelectClickHandler(warehouse)}
                        disabled={warehouse.id === selectedWarehouse?.id}
                        data-test-selector="storePickup_warehouseSelect"
                    >
                        {warehouse.id === selectedWarehouse?.id ? translate("Currently Selected") : translate("Select")}
                    </Button>
                </GridItem>
            </GridContainer>
        );
    };

    const isReady = isGoogleMapsScriptsLoaded === true && !isLoading && !!warehouses;
    const showPagination =
        isReady &&
        warehouses.length > 0 &&
        !!warehousesPagination &&
        warehousesPagination.totalItemCount > warehousesPagination.pageSize;

    return (
        <StyledWrapper {...styles.wrapper} data-test-selector="storePickup">
            <Typography as="h2" {...styles.titleText}>
                {translate("Select a store")}
            </Typography>
            <StyledForm {...styles.form} onSubmit={handleSubmit}>
                <GridContainer {...styles.searchGridContainer}>
                    <GridItem {...styles.searchTextFieldGridItem}>
                        <TextField
                            {...styles.searchTextField}
                            label={translate("Search Locations")}
                            value={warehouseSearchFilter}
                            onChange={handleSearchLocationsChanged}
                            placeholder={translate("Search by location name, city, state, or zip")}
                            data-test-selector="storePickup_locationSearch"
                        />
                    </GridItem>
                    <GridItem {...styles.searchRadiusGridItem}>
                        <TextField
                            {...styles.searchRadiusText}
                            label={translate("Search Radius")}
                            value={radiusSearchFilter}
                            onChange={handleSearchRadiusChanged}
                            type="number"
                            min={0}
                            placeholder={translate("Search Radius")}
                            data-test-selector="storePickup_searchRadius"
                        />
                    </GridItem>
                    <GridItem {...styles.distanceUnitOfMeasureGridItem}>
                        <RadioGroup
                            {...styles.distanceUnitOfMeasureRadioGroup}
                            value={distanceUnitOfMeasure}
                            onChangeHandler={handleDistanceUnitOfMeasureChange}
                        >
                            <Radio
                                {...styles.distanceUnitOfMeasureImperialRadio}
                                value="Imperial"
                                data-test-selector="storePickup_byMiles"
                            >
                                {translate("Miles")}
                            </Radio>
                            <Radio
                                {...styles.distanceUnitOfMeasureMetricRadio}
                                value="Metric"
                                data-test-selector="storePickup_byKilometers"
                            >
                                {translate("Kilometers")}
                            </Radio>
                        </RadioGroup>
                    </GridItem>
                    <GridItem {...styles.searchButtonGridItem}>
                        <Button {...styles.searchButton} type="submit" data-test-selector="storePickup_searchButton">
                            {translate("Search")}
                        </Button>
                    </GridItem>
                </GridContainer>
            </StyledForm>
            <TabGroup {...styles.searchResultsTabGroup}>
                <Tab
                    {...styles.listTab}
                    tabKey="List view"
                    headline={translate("List view")}
                    data-test-selector="storePickup_listView"
                >
                    <GridContainer>
                        {!isReady && (
                            <GridItem {...styles.searchResultGridItem}>
                                <StyledWrapper {...styles.centeringWrapper}>
                                    <LoadingSpinner {...styles.spinner} />
                                </StyledWrapper>
                            </GridItem>
                        )}
                        {isReady && !locationKnown && (
                            <GridItem {...styles.siteMessageGridItem}>
                                <Typography {...styles.siteMessageGeocodeErrorText}>
                                    {siteMessage("PickUpLocation_GeocodeErrorMessage")}
                                </Typography>
                            </GridItem>
                        )}
                        {isReady && locationKnown && warehouses.length === 0 && (
                            <GridItem {...styles.siteMessageGridItem}>
                                <Typography
                                    data-test-selector="storePickup_noresult"
                                    {...styles.siteMessageResultsErrorText}
                                >
                                    {showSelectedWarehouse
                                        ? siteMessage("PickUpLocation_SelectedLocationIsOnlyResult")
                                        : siteMessage("PickUpLocation_NoResultsMessage")}
                                </Typography>
                            </GridItem>
                        )}
                        {isReady &&
                            warehouses.map((warehouse, index) => (
                                <GridItem key={warehouse.id} {...styles.searchResultGridItem}>
                                    {renderWarehouseCard(warehouse, index)}
                                </GridItem>
                            ))}
                        <GridItem {...styles.paginationGridItem}>
                            {showPagination && (
                                <Pagination
                                    {...styles.pagination}
                                    currentPage={warehousesPagination.currentPage}
                                    resultsPerPage={warehousesPagination.pageSize}
                                    resultsCount={warehousesPagination.totalItemCount}
                                    resultsPerPageOptions={warehousesPagination.pageSizeOptions}
                                    prevPage={warehousesPagination.prevPageUri}
                                    nextPage={warehousesPagination.nextPageUri}
                                    onChangePage={onChangePage}
                                    onChangeResultsPerPage={onChangeResultsPerPage}
                                />
                            )}
                        </GridItem>
                    </GridContainer>
                </Tab>
                <Tab
                    {...styles.mapTab}
                    tabKey="Map view"
                    headline={translate("Map view")}
                    data-test-selector="storePickup_mapView"
                >
                    <WarehouseGoogleMap
                        extendedStyles={styles.warehouseGoogleMap}
                        currentLocation={currentLocation}
                        warehouseSearchFilter={warehouseSearchFilter}
                        distanceUnitOfMeasure={distanceUnitOfMeasure}
                        setGoogleMap={setGoogleMap}
                        mapMarkerElements={mapMarkersElements}
                        warehouseInfoWindow={warehouseInfoWindow}
                        currentLocationInfoWindow={currentLocationInfoWindow}
                        overrideRenderWarehouseCard={(warehouse: WarehouseModel) =>
                            renderWarehouseCard(warehouse, 0, true)
                        }
                        handleOpenWarehouseHours={() => {}}
                        updateLastFocusableElement={() => {}}
                    />
                </Tab>
            </TabGroup>
        </StyledWrapper>
    );
};

const widgetModule: WidgetModule = {
    component: connect(mapStateToProps, mapDispatchToProps)(withDynamicGoogleMaps(StorePickup)),
    definition: {
        allowedContexts: ["StorePickupOverlay"],
        group: "Store Pickup",
        displayName: "Store Pickup",
    },
};

export default widgetModule;
