import Button from "@insite/mobius/Button";
import Modal from "@insite/mobius/Modal";
import TextField from "@insite/mobius/TextField";
import getColor from "@insite/mobius/utilities/getColor";
import { parseAdminTokenFromLocalStorage } from "@insite/shell/Store/BearerToken";
import {
    closeRestoreContentModal,
    restoreContent,
} from "@insite/shell/Store/ImportExportModal/ImportExportModalActionCreators";
import ShellState from "@insite/shell/Store/ShellState";
import { TS } from "@insite/shell/TS";
import React, { useEffect, useState } from "react";
import { connect, ResolveThunks } from "react-redux";
import styled, { css } from "styled-components";

const mapStateToProps = (state: ShellState) => ({
    visible: !!state.importExportModal.showRestoreModal,
    errorMessage: state.importExportModal.errorMessage,
    taskInProgress: state.importExportModal.taskInProgress,
});

const mapDispatchToProps = {
    closeRestoreContentModal,
    restoreContent,
};

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

const RestoreContentModal: React.FC<Props> = ({
    visible,
    errorMessage,
    taskInProgress,
    closeRestoreContentModal,
    restoreContent,
}) => {
    const [username, setUsername] = useState("");
    const [tokenUsername, setTokenUsername] = useState("");

    useEffect(() => {
        if (!visible) {
            setUsername("");
        }
    }, [visible]);

    const usernameChangeHandler = (event: React.FormEvent<HTMLInputElement>) => {
        setUsername(event.currentTarget.value.toLowerCase());
        if (!tokenUsername) {
            const token = parseAdminTokenFromLocalStorage();
            if (token?.preferred_username) {
                setTokenUsername(token?.preferred_username.substring("admin_".length).toLowerCase());
            }
        }
    };

    const modalContent = () => {
        if (errorMessage) {
            return (
                <>
                    <ContentWrapperStyle>
                        <ErrorStyle data-test-selector="restore_content_error_message">{errorMessage}</ErrorStyle>
                    </ContentWrapperStyle>
                </>
            );
        }

        return (
            <>
                <ContentWrapperStyle>
                    <InfoStyle>
                        {TS("All content for this site will be reset to the contents in the backup table.")}
                    </InfoStyle>
                    <InfoStyle>
                        {TS(
                            "This action is irreversible. Please type your username in the box below to confirm your decision.",
                        )}
                    </InfoStyle>
                    <UsernameWrapperStyle>
                        <TextField
                            data-test-selector="restore_content_username"
                            label={TS("Username")}
                            value={username}
                            onChange={usernameChangeHandler}
                        />
                    </UsernameWrapperStyle>
                </ContentWrapperStyle>
                <ButtonsStyle>
                    <Button variant="tertiary" onClick={closeRestoreContentModal}>
                        {TS("Cancel")}
                    </Button>
                    <Button
                        data-test-selector="restore_content_reset_button"
                        disabled={taskInProgress || !username || username !== tokenUsername}
                        onClick={restoreContent}
                    >
                        {TS("Reset")}
                    </Button>
                </ButtonsStyle>
            </>
        );
    };

    return (
        <Modal
            isOpen={visible}
            handleClose={closeRestoreContentModal}
            headline={TS("Sitewide Content Reset")}
            size={600}
            cssOverrides={{
                modalContent: css`
                    padding: 0;
                `,
            }}
        >
            {modalContent()}
        </Modal>
    );
};

const ErrorStyle = styled.p`
    color: ${getColor("danger.main")};
    margin: 20px 0;
`;

const InfoStyle = styled.p`
    margin-bottom: 20px;
`;

const UsernameWrapperStyle = styled.div`
    width: 60%;
`;

const ContentWrapperStyle = styled.div`
    padding: 15px;
`;

const ButtonsStyle = styled.div`
    padding: 15px;
    display: flex;
    justify-content: flex-end;
    & > button {
        margin-left: 10px;
    }
    border-top: 1px solid ${getColor("common.border")};
    background: #e7e7e7;
`;

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