import formatUrlWithWidthAndHeight from "@insite/client-framework/Common/Utilities/formatUrlWithWidthAndHeight";
import Button from "@insite/mobius/Button";
import Scrim from "@insite/mobius/Overlay/Scrim";
import TextField from "@insite/mobius/TextField";
import DisabledInCodeTooltip from "@insite/shell/Components/Shell/StyleGuide/DisabledInCodeTooltip";
import { createSetNewValueInDraft } from "@insite/shell/Components/Shell/StyleGuide/Helpers";
import { PresetHelpers } from "@insite/shell/Components/Shell/StyleGuide/Types";
import { TS } from "@insite/shell/TS";
import get from "lodash/get";
import React, { useState } from "react";
import styled, { css } from "styled-components";

type Props = {
    locationInTheme: string;
    title?: string;
    disabled?: boolean;
} & PresetHelpers;

const ImagePickerConfig = ({ locationInTheme, title, disabled, theme, postStyleGuideTheme, update }: Props) => {
    const [imagePickerIsOpen, setImagePickerIsOpen] = useState(false);

    const changeImageHandler = () => {
        setImagePickerIsOpen(true);

        (window as any).CKFinder.modal({
            chooseFiles: true,
            chooseFilesClosePopup: true,
            resizeImages: false,
            onInit: (finder: any) => {
                const hideOverlay = () => setImagePickerIsOpen(false);

                document.getElementById("ckf-modal-close")?.addEventListener("click", hideOverlay);

                finder.on("files:choose", (evt: any) => {
                    hideOverlay();
                    const url = evt.data.files.first().getUrl();
                    update(draft => {
                        createSetNewValueInDraft(locationInTheme)(draft, url);
                    });
                    updateFieldWithWidthAndHeight(url);
                });

                finder.on("file:choose:resizedImage", (evt: any) => {
                    hideOverlay();
                    updateFieldWithWidthAndHeight(evt.data.resizedUrl);
                });
            },
        });
    };

    const deleteImageHandler = () => {
        update(draft => {
            createSetNewValueInDraft(locationInTheme)(draft, "");
        });
    };

    const imageUrlChangeHandler = (event: React.FormEvent<HTMLInputElement>) => {
        const url = event.currentTarget.value;
        update(draft => {
            createSetNewValueInDraft(locationInTheme)(draft, url);
        });
    };

    const updateFieldWithWidthAndHeight = (url: string) => {
        const image = new Image();
        image.src = url;
        image.onload = function onLoadHandler(this: any) {
            const { width, height } = this;
            const urlWithQueryStrings = formatUrlWithWidthAndHeight({ url, width, height });
            update(draft => {
                createSetNewValueInDraft(locationInTheme)(draft, urlWithQueryStrings);
            });
        };
    };

    const appendWidthAndHeightBeforeSave = () => {
        const url = get(theme, locationInTheme);
        updateFieldWithWidthAndHeight(url);
    };

    const codeOverridden = !!get(postStyleGuideTheme, locationInTheme);
    const finallyDisabled = codeOverridden || disabled;
    const url = get(theme, locationInTheme);
    return (
        <Wrapper>
            {imagePickerIsOpen && <Scrim zIndexLevel="modal" />}
            <Label>
                {title || "Image"} {codeOverridden && <DisabledInCodeTooltip />}
            </Label>
            <TextField
                type="text"
                value={url}
                onChange={imageUrlChangeHandler}
                onBlur={appendWidthAndHeightBeforeSave}
                disabled={finallyDisabled}
            />
            <Button css={changedImageButtonStyles} onClick={changeImageHandler} disabled={finallyDisabled}>
                {url ? TS("Change") : TS("Add Image")}
            </Button>
            {url && (
                <Button onClick={deleteImageHandler} variant="secondary" disabled={finallyDisabled}>
                    {TS("Delete")}
                </Button>
            )}
        </Wrapper>
    );
};

const changedImageButtonStyles = css`
    margin: 8px 8px 0 0;
    height: 32px;
    border-radius: 3px;
    border-width: 1px;
    padding: 0 16px;
`;

const Wrapper = styled.div``;

const Label = styled.label`
    display: block;
    font-size: 16px;
    line-height: 21px;
    margin: 10px 0 -4px;
    position: relative;
`;

export default ImagePickerConfig;
