import formatUrlWithWidthAndHeight from "@insite/client-framework/Common/Utilities/formatUrlWithWidthAndHeight";
import parseImageUrl from "@insite/client-framework/Common/Utilities/parseImageUrl";
import { ImagePickerFieldDefinition } from "@insite/client-framework/Types/FieldDefinition";
import Button from "@insite/mobius/Button";
import Scrim from "@insite/mobius/Overlay/Scrim";
import MobiusTextField from "@insite/mobius/TextField";
import StandardControl from "@insite/shell-public/Components/StandardControl";
import { EditorTemplateProps } from "@insite/shell-public/EditorTemplateProps";
import { useFileBrowser } from "@insite/shell/Common/Hooks/FileBrowser";
import { TS } from "@insite/shell/TS";
import React, { useState } from "react";
import styled, { css } from "styled-components";

type Props = EditorTemplateProps<string, ImagePickerFieldDefinition>;

const ImagePickerField: React.FC<Props> = ({ fieldValue, fieldDefinition, updateField }) => {
    const { openFileBrowser } = useFileBrowser({
        onFileSelected: url => {
            updateField(fieldDefinition.name, url);
            updateFieldWithWidthAndHeight(url);
        },
        onClose: () => {
            setImagePickerIsOpen(false);
        },
    });

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

    const parsedValues = parseImageUrl(fieldValue);
    const [imagePickerIsOpen, setImagePickerIsOpen] = useState(false);
    const [srcForDisplay, setSrcForDisplay] = useState<string | undefined>(parsedValues.url);
    const [height, setHeight] = useState<number | string | undefined>(parsedValues.height);
    const [width, setWidth] = useState<number | string | undefined>(parsedValues.width);

    const deleteImageHandler = () => {
        setSrcForDisplay("");
        setHeight(undefined);
        setWidth(undefined);
        updateField(fieldDefinition.name, "");
    };

    const imageUrlChangeHandler = (event: React.FormEvent<HTMLInputElement>) => {
        const url = event.currentTarget.value;

        setSrcForDisplay(url);
        updateField(fieldDefinition.name, url);
    };

    const updateFieldWithWidthAndHeight = (url: string) => {
        const image = new Image();
        image.src = url;
        image.onload = function onLoadHandler(this: any) {
            const { width, height } = this;
            setSrcForDisplay(url);
            setWidth(width);
            setHeight(height);
            const urlWithQueryStrings = formatUrlWithWidthAndHeight({ url, width, height });
            updateField(fieldDefinition.name, urlWithQueryStrings);
        };
    };

    const appendWidthAndHeightBeforeSave = () => {
        if (srcForDisplay) {
            updateFieldWithWidthAndHeight(srcForDisplay);
        }
    };

    return (
        <StandardControl fieldDefinition={fieldDefinition}>
            <Wrapper>
                {imagePickerIsOpen && <Scrim zIndexLevel="modal" />}
                {fieldValue && (
                    <>
                        <Button css={changedImageButtonStyles} onClick={changeImageHandler} variant="secondary">
                            {TS("Change")}
                        </Button>
                        <Button onClick={deleteImageHandler} variant="secondary">
                            {TS("Delete")}
                        </Button>
                    </>
                )}
                {!fieldValue && (
                    <Button onClick={changeImageHandler} variant="secondary">
                        {TS("Add Image")}
                    </Button>
                )}
                <Label htmlFor={fieldDefinition.name}>{fieldDefinition.displayName}</Label>
                <MobiusTextField
                    id={fieldDefinition.name}
                    type="text"
                    value={srcForDisplay}
                    onChange={imageUrlChangeHandler}
                    onBlur={appendWidthAndHeightBeforeSave}
                />
                {(height || width) && (
                    <DimensionsContainer>
                        {TS("Image Dimensions")}
                        <DimensionsWrapper>
                            {width && (
                                <span>
                                    {TS("Width")}: {width}px
                                </span>
                            )}
                            {height && (
                                <span>
                                    {TS("Height")}: {height}px
                                </span>
                            )}
                        </DimensionsWrapper>
                    </DimensionsContainer>
                )}
            </Wrapper>
        </StandardControl>
    );
};

export default ImagePickerField;

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

const Wrapper = styled.div`
    padding-top: 10px;
`;

const Label = styled.label`
    display: block;
    font-size: 16px;
    line-height: 21px;
    font-weight: bold;
    margin: 25px 0 -4px;
    text-transform: uppercase;
    position: relative;
`;

const DimensionsContainer = styled.div`
    font-size: 12px;
`;

const DimensionsWrapper = styled.div`
    display: flex;
    gap: 12px;
`;
