import { getCookie } from "@insite/client-framework/Common/Cookies";
import parseQueryString from "@insite/client-framework/Common/Utilities/parseQueryString";
import { GetVmiLocationsApiParameter } from "@insite/client-framework/Services/VmiLocationService";
import ApplicationState from "@insite/client-framework/Store/ApplicationState";
import { getLocation } 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 { getPageLinkByPageType } from "@insite/client-framework/Store/Links/LinksSelectors";
import loadBelowMinimumCount from "@insite/client-framework/Store/Pages/VmiDashboard/Handlers/LoadBelowMinimumCount";
import loadFastMovingCount from "@insite/client-framework/Store/Pages/VmiDashboard/Handlers/LoadFastMovingCount";
import loadSlowMovingCount from "@insite/client-framework/Store/Pages/VmiDashboard/Handlers/LoadSlowMovingCount";
import updateVmiLocation from "@insite/client-framework/Store/Pages/VmiDashboard/Handlers/UpdateVmiLocation";
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 GridContainer from "@insite/mobius/GridContainer";
import GridItem, { GridItemProps } from "@insite/mobius/GridItem";
import Select, { SelectPresentationProps, SelectProps } from "@insite/mobius/Select";
import Typography, { TypographyPresentationProps } from "@insite/mobius/Typography";
import { HasHistory, withHistory } from "@insite/mobius/utilities/HistoryContext";
import * as React from "react";
import { connect, ResolveThunks } from "react-redux";
import { css } from "styled-components";

interface OwnProps extends WidgetProps {}

const mapStateToProps = (state: ApplicationState) => {
    const getVmiLocationsParameter = {
        filter: "",
        sort: "Name",
        page: 1,
        pageSize: 9999, // need to get all locations
    } as GetVmiLocationsApiParameter;

    const location = getLocation(state);
    const parsedQuery = parseQueryString<{ locationid?: string }>(location.search?.toLowerCase());
    return {
        vmiLocationsDataView: getVmiLocationsDataView(state, getVmiLocationsParameter),
        vmiLocationId: state.pages.vmiDashboard.vmiLocationId,
        parsedQuery,
        getVmiLocationsParameter,
        vmiDashboardPageUrl: getPageLinkByPageType(state, "VmiDashboardPage")?.url,
    };
};

const mapDispatchToProps = {
    loadVmiLocations,
    updateVmiLocation,
    loadBelowMinimumCount,
    loadFastMovingCount,
    loadSlowMovingCount,
};

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

export interface VmiDashboardHeaderStyles {
    titleGridItem?: GridItemProps;
    titleText?: TypographyPresentationProps;
    locationSwitcherGridItem?: GridItemProps;
    locationSelect?: SelectPresentationProps;
}

export const vmiLocationStyles: VmiDashboardHeaderStyles = {
    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 = vmiLocationStyles;

class VmiDashboardHeader extends React.Component<Props> {
    componentDidMount() {
        if (!this.props.vmiLocationsDataView.value && !this.props.vmiLocationsDataView.isLoading) {
            this.props.loadVmiLocations(this.props.getVmiLocationsParameter);
        }

        const vmiLocationId = this.props.parsedQuery?.locationid?.toLowerCase();
        this.props.updateVmiLocation({ vmiLocationId });
    }

    setLocation = (vmiLocationId: string) => {
        const query = vmiLocationId ? `?vmiLocationId=${vmiLocationId}` : "";
        this.props.history.push(`${this.props.vmiDashboardPageUrl}${query}`);
        this.props.updateVmiLocation({ vmiLocationId: vmiLocationId || undefined });
        this.props.loadBelowMinimumCount();
        this.props.loadFastMovingCount();
        this.props.loadSlowMovingCount();
    };

    render() {
        const vmiLocations = this.props.vmiLocationsDataView.value || [];
        let currentLocation = null;
        if (vmiLocations && vmiLocations.length > 0) {
            const vmiLocationId = this.props.parsedQuery?.locationid?.toLowerCase() || this.props.vmiLocationId;
            currentLocation = vmiLocationId
                ? vmiLocations.find(location => location.id?.toLowerCase() === vmiLocationId)
                : null;
        }

        return (
            <GridContainer>
                <GridItem {...styles.titleGridItem}>
                    <Typography as="h2" {...styles.titleText}>
                        {translate("Dashboard")}
                    </Typography>
                </GridItem>
                <GridItem {...styles.locationSwitcherGridItem}>
                    {vmiLocations && (
                        <Select
                            {...styles.locationSelect}
                            onChange={event => this.setLocation(event.currentTarget.value)}
                            value={currentLocation?.id ?? ""}
                            aria-label={translate("Select Location")}
                        >
                            <option value="">{translate("All Locations")}</option>
                            {vmiLocations.map(c => (
                                <option value={c.id} key={c.id}>
                                    {c.name}
                                </option>
                            ))}
                        </Select>
                    )}
                </GridItem>
            </GridContainer>
        );
    }
}

const widgetModule: WidgetModule = {
    component: connect(mapStateToProps, mapDispatchToProps)(withHistory(VmiDashboardHeader)),
    definition: {
        displayName: "VMI Dashboard Header",
        group: "VMI Dashboard",
        allowedContexts: ["VmiDashboardPage"],
    },
};

export default widgetModule;
