/* eslint-disable spire/export-styles */
import { getFocalPointStyles } from "@insite/client-framework/Common/BasicSelectors";
import Zone from "@insite/client-framework/Components/Zone";
import { ColumnAlignment } from "@insite/client-framework/Types/FieldDefinition";
import WidgetModule from "@insite/client-framework/Types/WidgetModule";
import WidgetProps from "@insite/client-framework/Types/WidgetProps";
import GridContainer from "@insite/mobius/GridContainer";
import GridItem, { GridWidths } from "@insite/mobius/GridItem";
import * as cssLinter from "css";
import * as React from "react";
import { css } from "styled-components";

const enum fields {
    columns = "columns",
    gap = "gap",
    alignment = "alignment",
    reflow = "reflow",
    isFullWidth = "isFullWidth",
    fullWidthStylingType = "fullWidthStylingType",
    fullWidthColor = "fullWidthColor",
    fullWidthImage = "fullWidthImage",
    fullWidthImageFocalPoint = "fullWidthImageFocalPoint",
    customCSS = "customCSS",
}

interface Props extends WidgetProps {
    fields: {
        [fields.columns]: GridWidths[];
        [fields.gap]: number;
        [fields.alignment]: ColumnAlignment[];
        [fields.reflow]: boolean;
        [fields.isFullWidth]: boolean;
        [fields.fullWidthStylingType]: string;
        [fields.fullWidthColor]: string;
        [fields.fullWidthImage]: string;
        [fields.fullWidthImageFocalPoint]:
            | "topLeft"
            | "topCenter"
            | "topRight"
            | "centerLeft"
            | "center"
            | "centerRight"
            | "bottomLeft"
            | "bottomCenter"
            | "bottomRight";
        [fields.customCSS]: string;
    };
}

const mobileColumnsRef: { [key: number]: GridWidths | GridWidths[] } = {
    1: [3, 3, 1, 1, 1],
    2: [4, 4, 2, 2, 2],
    3: [6, 6, 3, 3, 3],
    4: [6, 6, 4, 4, 4],
    5: [12, 12, 5, 5, 5],
    6: [12, 12, 6, 6, 6],
    7: [12, 12, 7, 7, 7],
    8: [12, 12, 8, 8, 8],
    9: [12, 12, 9, 9, 9],
    10: [12, 12, 10, 10, 10],
    11: [12, 12, 11, 11, 11],
    12: 12,
};

const convertToResponsive = (column: GridWidths): GridWidths | GridWidths[] => {
    return mobileColumnsRef[column] || column;
};

const Row = (props: Props) => {
    const {
        fields: {
            columns,
            gap,
            alignment,
            reflow,
            isFullWidth,
            fullWidthStylingType,
            fullWidthColor,
            fullWidthImage,
            fullWidthImageFocalPoint,
            customCSS,
        },
        id,
    } = props;

    const columnElements: JSX.Element[] = [];

    for (let x = 0; x < columns.length; x += 1) {
        const align = alignment[x] ? alignment[x] : "top";
        columnElements.push(
            <GridItem key={x} width={reflow ? convertToResponsive(columns[x]) : columns[x]} align={align}>
                <Zone contentId={id} zoneName={`Content${x}`} />
            </GridItem>,
        );
    }

    const fullWidthBackgroundCss = !isFullWidth
        ? undefined
        : fullWidthStylingType === "solidColor"
        ? css`
              background-color: ${fullWidthColor};
          `
        : fullWidthStylingType === "image"
        ? css`
              background-image: url("${fullWidthImage}");
              background-size: cover;
              ${getFocalPointStyles(fullWidthImageFocalPoint)}
          `
        : undefined;

    const finalCss = css`
        ${fullWidthBackgroundCss}
        ${customCSS}
    `;

    return (
        <GridContainer gap={gap || 0} isFullWidth={isFullWidth} css={finalCss}>
            {columnElements}
        </GridContainer>
    );
};

const defaultCustomCss = `& {

}`;

const advancedTab = {
    displayName: "Advanced",
    sortOrder: 1,
};

const widgetModule: WidgetModule = {
    component: Row,
    definition: {
        group: "Basic",
        icon: "distribute-spacing-vertical",
        fieldDefinitions: [
            {
                name: fields.columns,
                displayName: "Layout",
                editorTemplate: "ColumnsField",
                defaultValue: [4, 4, 4],
                fieldType: "General",
                sortOrder: 1,
                validate: value => (value.length > 0 ? null : "Please enter a valid layout."),
            },
            {
                name: fields.reflow,
                displayName: "Use default reflow for responsive screens sizes",
                editorTemplate: "CheckboxField",
                defaultValue: true,
                fieldType: "General",
                sortOrder: 10,
            },
            {
                name: fields.gap,
                displayName: "Gap Between Items",
                editorTemplate: "IntegerField",
                defaultValue: 0,
                fieldType: "General",
                max: 1000,
                min: 0,
                sortOrder: 2,
            },
            {
                name: fields.isFullWidth,
                displayName: "Full Width",
                editorTemplate: "CheckboxField",
                defaultValue: false,
                fieldType: "General",
                isVisible: (_item, _advancedFeaturesEnabled, theme) => !!theme?.content?.isFullWidth,
                sortOrder: 3,
            },
            {
                name: fields.fullWidthStylingType,
                displayName: "Styling",
                editorTemplate: "RadioButtonsField",
                options: [
                    {
                        displayName: "Solid Color",
                        value: "solidColor",
                    },
                    {
                        displayName: "Image",
                        value: "image",
                    },
                ],
                defaultValue: "solidColor",
                horizontal: true,
                fieldType: "General",
                isVisible: ({ fields: { isFullWidth } }, _advancedFeaturesEnabled, theme) =>
                    !!theme?.content?.isFullWidth && !!isFullWidth,
                sortOrder: 4,
            },
            {
                name: fields.fullWidthColor,
                displayName: "Color",
                editorTemplate: "ColorPickerField",
                defaultValue: "transparent",
                fieldType: "General",
                isVisible: ({ fields: { isFullWidth, fullWidthStylingType } }, _advancedFeaturesEnabled, theme) =>
                    !!theme?.content?.isFullWidth && !!isFullWidth && fullWidthStylingType === "solidColor",
                sortOrder: 5,
            },
            {
                name: fields.fullWidthImage,
                displayName: "Image",
                editorTemplate: "ImagePickerField",
                defaultValue: "",
                fieldType: "General",
                isVisible: ({ fields: { isFullWidth, fullWidthStylingType } }, _advancedFeaturesEnabled, theme) =>
                    !!theme?.content?.isFullWidth && !!isFullWidth && fullWidthStylingType === "image",
                sortOrder: 6,
            },
            {
                name: fields.fullWidthImageFocalPoint,
                displayName: "Focal Point",
                editorTemplate: "DropDownField",
                options: [
                    { displayName: "Top Left", value: "topLeft" },
                    { displayName: "Top Center", value: "topCenter" },
                    { displayName: "Top Right", value: "topRight" },
                    { displayName: "Center Left", value: "centerLeft" },
                    { displayName: "Center", value: "center" },
                    { displayName: "Center Right", value: "centerRight" },
                    { displayName: "Bottom Left", value: "bottomLeft" },
                    { displayName: "Bottom Center", value: "bottomCenter" },
                    { displayName: "Bottom Right", value: "bottomRight" },
                ],
                defaultValue: "center",
                fieldType: "General",
                hideEmptyOption: true,
                isVisible: ({ fields: { isFullWidth, fullWidthStylingType } }, _advancedFeaturesEnabled, theme) =>
                    !!theme?.content?.isFullWidth && !!isFullWidth && fullWidthStylingType === "image",
                sortOrder: 7,
            },
            {
                name: fields.alignment,
                displayName: "Column Alignment",
                editorTemplate: "ColumnAlignmentField",
                defaultValue: [],
                fieldType: "General",
                sortOrder: 1,
                tab: advancedTab,
            },
            {
                name: "customCSS",
                displayName: "Custom CSS",
                editorTemplate: "CodeField",
                fieldType: "General",
                tab: advancedTab,
                defaultValue: defaultCustomCss,
                isVisible: (item, shouldDisplayAdvancedFeatures) => !!shouldDisplayAdvancedFeatures,
                validate: value => {
                    if (value === undefined || value === null) {
                        return "";
                    }

                    const result = cssLinter.parse(value, { silent: true });
                    if (result?.stylesheet?.parsingErrors) {
                        // the error output at this time only has room for one line so we just show the first error
                        return result.stylesheet.parsingErrors.length <= 0
                            ? ""
                            : result.stylesheet.parsingErrors.map(error => `${error.reason} on line ${error.line}`)[0];
                    }

                    return "Unable to parse Css";
                },
                options: {
                    mode: "css",
                    lint: true,
                    autoRefresh: true,
                },
            },
        ],
    },
};

export default widgetModule;
