/**
 * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import { AlertLevels, TestableComponentInterface } from "@wso2is/core/models";
import { addAlert } from "@wso2is/core/store";
import { GenericIcon, Heading, LinkButton, ListLayout, PageHeader, Text } from "@wso2is/react-components";
import React, { FunctionComponent, MouseEvent, ReactElement, ReactNode, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { useDispatch } from "react-redux";
import { DropdownProps, Grid, Modal, PaginationProps } from "semantic-ui-react";
import { getApplicationList } from "../../../../features/applications/api";
import { ApplicationList } from "../../../../features/applications/components";
import { ApplicationListInterface } from "../../../../features/applications/models";
import { AppConstants, UIConstants } from "../../../../features/core/constants";
import { history } from "../../../../features/core/helpers";
import { IdentityProviderInterface, IdentityProviderTemplateInterface } from "../../../authentication-providers/models";
import RegisterApplicationIllustration from "../google/assets/add-social-login-illustration.png";

/**
 * Prop types of the component.
 */
interface GoogleQuickStartPropsInterface extends TestableComponentInterface {
    identityProvider: IdentityProviderInterface;
    template: IdentityProviderTemplateInterface;
}

const ITEMS_PER_PAGE = 7;

/**
 * Quick start content for the Google IDP template.
 *
 * @param {GoogleQuickStartPropsInterface} props - Props injected into the component.
 * @return {React.ReactElement}
 */
const GoogleQuickStart: FunctionComponent<GoogleQuickStartPropsInterface> = (
    props: GoogleQuickStartPropsInterface
): ReactElement => {

    const {
        [ "data-testid" ]: testId
    } = props;

    const { t } = useTranslation();

    const dispatch = useDispatch();

    const [ showApplicationModal, setShowApplicationModal ] = useState<boolean>(false);
    const [ listOffset, setListOffset ] = useState<number>(0);
    const [ listItemLimit, setListItemLimit ] = useState<number>(ITEMS_PER_PAGE);
    const [ appList, setAppList ] = useState<ApplicationListInterface>({});

    /**
     * Retrieves the list of applications.
     *
     * @param {number} limit - List limit.
     * @param {number} offset - List offset.
     * @param {string} filter - Search query.
     */
    const getAppLists = (limit: number, offset: number, filter: string): void => {

        getApplicationList(limit, offset, filter)
            .then((response) => {
                setAppList(response);
            })
            .catch((error) => {
                if (error.response && error.response.data && error.response.data.description) {
                    dispatch(addAlert({
                        description: error.response.data.description,
                        level: AlertLevels.ERROR,
                        message: t("console:develop.features.applications.notifications.fetchApplications" +
                            ".error.message")
                    }));

                    return;
                }

                dispatch(addAlert({
                    description: t("console:develop.features.applications.notifications.fetchApplications" +
                        ".genericError.description"),
                    level: AlertLevels.ERROR,
                    message: t("console:develop.features.applications.notifications.fetchApplications." +
                        "genericError.message")
                }));
            });
    };

    /**
     * Called on every `listOffset` & `listItemLimit` change.
     */
    useEffect(() => {
        getAppLists(listItemLimit, listOffset, null);
    }, [ listOffset, listItemLimit ]);

    /**
     * Handles per page dropdown page.
     *
     * @param {React.MouseEvent<HTMLAnchorElement>} event - Mouse event.
     * @param {DropdownProps} data - Dropdown data.
     */
    const handleItemsPerPageDropdownChange = (event: MouseEvent<HTMLAnchorElement>,
                                              data: DropdownProps): void => {
        setListItemLimit(data.value as number);
    };

    /**
     * Handles the pagination change.
     *
     * @param {React.MouseEvent<HTMLAnchorElement>} event - Mouse event.
     * @param {PaginationProps} data - Pagination component data.
     */
    const handlePaginationChange = (event: MouseEvent<HTMLAnchorElement>, data: PaginationProps): void => {
        setListOffset((data.activePage as number - 1) * listItemLimit);
    };

    const generateConfigureStep = (): ReactNode => {
        return (
            <>
                <Text>
                    Drag and drop the <strong>Google</strong> authenticator to <strong>Step 1</strong>, on
                    the <strong>Sign-on Method</strong> section of your <LinkButton
                        onClick={
                            () => setShowApplicationModal(true)
                        }
                        className="p-0"
                    >
                        application.
                    </LinkButton>
                </Text>
                <GenericIcon
                    icon={ RegisterApplicationIllustration }
                    size="huge"
                    transparent
                    style={ {
                        justifyContent: "start"
                    } }
                />
                {
                    showApplicationModal &&
                    <Modal
                        data-testid={ testId }
                        open={ true }
                        className="wizard application-create-wizard"
                        dimmer="blurring"
                        size="large"
                        onClose={ () => setShowApplicationModal(false) }
                        closeOnDimmerClick={ false }
                        closeOnEscape
                    >
                        <Modal.Header className="wizard-header">
                            { "Add Googel Login" }
                            <Heading as="h6">
                                { "Select an application you want to setup social login with." }
                            </Heading>
                        </Modal.Header>
                        <Modal.Content className="content-container" scrolling>
                            <ListLayout
                                currentListSize={ appList.count }
                                listItemLimit={ listItemLimit }
                                onItemsPerPageDropdownChange={ handleItemsPerPageDropdownChange }
                                onPageChange={ handlePaginationChange }
                                showPagination={ appList?.totalResults > listItemLimit }
                                totalPages={ Math.ceil(appList.totalResults / listItemLimit) }
                                totalListSize={ appList.totalResults }
                                data-testid={ `${ testId }-list-layout` }
                                showTopActionPanel={ false }
                                paginationOptions={ {
                                    itemsPerPageDropdownLowerLimit: ITEMS_PER_PAGE
                                } }
                            >
                                <ApplicationList
                                    isSetStrongerAuth
                                    list={ appList }
                                    onEmptyListPlaceholderActionClick={
                                        () => history.push(
                                            AppConstants.getPaths().get("APPLICATION_TEMPLATES")
                                        )
                                    }
                                    data-testid={ `${ testId }-list` }
                                />
                            </ListLayout>
                        </Modal.Content>
                        <Modal.Actions>
                            <Grid>
                                <Grid.Row column={ 1 }>
                                    <Grid.Column mobile={ 8 } tablet={ 8 } computer={ 8 }>
                                        <LinkButton
                                            data-testid={ `${ testId }-cancel-button` }
                                            floated="left"
                                            onClick={ () => setShowApplicationModal(false) }
                                        >
                                            { t("common:cancel") }
                                        </LinkButton>
                                    </Grid.Column>
                                </Grid.Row>
                            </Grid>
                        </Modal.Actions>
                    </Modal>
                }
            </>
        );
    };

    return (
        <Grid data-testid={ testId } className="ml-0 mr-0">
            <Grid.Row textAlign="left">
                <Grid.Column width={ 16 }>
                    <PageHeader
                        className="mb-2"
                        title={ "Add Google Login" }
                        imageSpaced={ false }
                        bottomMargin={ false }
                    />
                    <Heading subHeading as="h6">
                        Google Identity provider is now ready to be used as a login option for your application users.
                    </Heading>
                </Grid.Column>
            </Grid.Row>
            <Grid.Row textAlign="left">
                <Grid.Column width={ 16 }>
                    { generateConfigureStep() }
                </Grid.Column>
            </Grid.Row>
        </Grid>
    );
};

/**
 * Default props for the component
 */
GoogleQuickStart.defaultProps = {
    "data-testid": "google-quick-start"
};

/**
 * A default export was added to support React.lazy.
 * TODO: Change this to a named export once react starts supporting named exports for code splitting.
 * @see {@link https://reactjs.org/docs/code-splitting.html#reactlazy}
 */
export default GoogleQuickStart;
