import * as React from "react";
import { FormElementProps, FormElementRegistration } from "@vertigis/workflow";
import Button from '@mui/material/Button';


/**
 * The generic type argument provided to `FormElementProps<T>` controls the type
 * of `props.value` and `props.setValue(value)`. If your element doesn't need a
 * `value`, you can omit the type argument.
 *
 * You can also declare additional public properties of your element by adding
 * properties to this interface. The properties will be managed by the Workflow
 * runtime, and passed in as `props`. You can update the properties by using
 * `props.setProperty(key, value)`.
 */
interface HeaderwithHelpProps extends FormElementProps<string> {
    setting?: settingConfig
    //Following NOT necessary, to be Compatible with old header only
    backgroundColor?: string
    imgSrc?: string
    text?: string;
    imgPosition?: string;
    divHeight?: string;
    margin?: string;
    padding?: string;
    fontSize?: string;
    fontWeight?: string;
    fontFamily?: string;
    fontColor?: string;
    borderRaius?: string;
    align?: string;
    innermargin?: string;
}

/**
 * A Workflow element built using React.
 * @displayName HeaderwithHelp
 * @description Header to display icon and title, optional to provide help video if available.
 * @param props The props that will be provided by the Workflow runtime. For new header, give value to property "setting"; for existing header, copy the old load activities and add new setting for help button, then assign click events.
 */

interface settingConfig {
    headerText?: string,
    headerIcon?: string,
    smallSize?: boolean,
    helpIcon?: string,
    backgroundColor?: string,
    helpTitle?: string,
    helpUrl?: string,
}


function HeaderwithHelp(props: HeaderwithHelpProps): React.ReactElement {
    const { raiseEvent } = props;
    const helpInfo = { title: props.setting?.helpTitle || '!!please contact GIS Admin to provide setting.helpTitle', url: props.setting?.helpUrl || "https://descriptusercontent.com/published/e09ca015-acd7-4980-b4b4-7ca72ebb7208/original.mp4" }
    const handleHelpClick = () => {
        raiseEvent("clicked", JSON.stringify(helpInfo)); // Pass the entire item data structure
    };
    function addLengths(...lengths) {
        if (lengths.length === 0) return '0px'; // Handle no input case

        let total = 0;
        let baseUnit = '';

        lengths.forEach(length => {
            const match: string = length.match(/(\d+)([a-zA-Z%]+)/);
            if (match) {
                // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
                const value = parseFloat(length.toString());
                const unit = match[2];

                if (baseUnit === '') {
                    baseUnit = unit; // Set the base unit from the first input
                }
                if (baseUnit === 'rem') {
                    baseUnit = 'px'; // Set the base unit to px if first rem
                }

                if (unit === baseUnit) {
                    total += value; // Add directly if units are the same
                } else if (unit === 'rem' && baseUnit === 'px') {
                    total += value * 10; // Convert rem to px
                } else {
                    throw new Error(`Unsupported unit: ${unit}`);
                }
            } else {
                throw new Error(`Invalid length format: ${length}`);
            }
        });

        return total + baseUnit; // Return total with the original base unit
    }
    // Example usage:
    let helpButtonHeight:string = ''
    if (props.divHeight && props.padding) {
        helpButtonHeight = addLengths(props.divHeight, props.padding, props.padding)
    }
    

    const helpExist: boolean = Boolean(props.setting?.helpTitle) || Boolean(props.setting?.helpUrl)

    const smallStyle = Boolean(props.setting && props.setting.smallSize)

    const helpIconHeight =helpButtonHeight !== '' ? parseFloat(helpButtonHeight)/2 + 'px' : (smallStyle ? '24px' : '30px')

    return (
        <>
            <div style={{
                display: 'flex',
                gap: '0.5em',
                margin: 0,
                padding: 0,
                fontFamily: props.fontFamily!==undefined? `${("'"+props.fontFamily+"'")} , Arial, sans-serif !important`: `'NetworkNeo', Arial, sans-serif !important`,

            }}>
                <div
                    style={{
                        backgroundColor: props.backgroundColor !== undefined ? props.backgroundColor : (props.setting && props.setting.backgroundColor ? props.setting.backgroundColor : 'rgb(255, 199, 9)'),
                        padding: props.padding !== undefined ? props.padding : (smallStyle ? '12px' : '15px'),
                        borderRadius: props.borderRaius || '5px',
                        cursor: 'default',
                        textAlign: 'center',
                        flex: '1 ',
                        flexGrow: '4   ',
                    }}
                >
                    <div style={{
                        display: 'flex',
                        height: props.divHeight !== undefined ? props.divHeight : (smallStyle ? '24px' : '30px'),
                        justifyContent: 'start',
                        alignItems: 'center'
                    }}>
                        <img
                            src={props.imgSrc !== undefined ? props.imgSrc : (props.setting && props.setting.headerIcon ? props.setting.headerIcon : 'https://cdn-icons-png.flaticon.com/24/6679/6679617.png')}
                            alt=""
                            style={{
                                marginRight: '2px',
                                marginLeft: '2px',
                                height: '24px',
                                width: "auto"
                            }}
                        />
                        <span style={{
                            fontFamily: 'Arial',
                            fontSize: props.fontSize !== undefined ? props.fontSize : (smallStyle ? '16px' : '22px'),
                            fontWeight: props.fontWeight || 700,
                            color: props.fontColor || 'rgb(0, 0, 0)',
                            margin: '10px'
                        }}>
                            {props.text !== undefined ? props.text : (props.setting && props.setting.headerText ? props.setting.headerText : 'edit setting.headerText ')}
                        </span>
                    </div>
                </div>

                {
                    helpExist ? <Button startIcon={<img className="material-icons notranslate MuiIcon-root MuiIcon-fontSizeMedium" aria-hidden="true" src={props.setting && props.setting.helpIcon || "https://cdn-icons-png.flaticon.com/24/189/189665.png"} style={{ height: helpIconHeight, width: helpIconHeight ,transform: 'translateX(6px)'}} />} style={{
                        flex: '1 !important',
                        justifyContent: 'center',
                        height: helpButtonHeight !== '' ? helpButtonHeight : (smallStyle ? '48px' : '60px'),
                        minWidth: 'auto',
                        padding: '0px',
                        lineHeight: 0,
                        backgroundColor: props.backgroundColor !== undefined ? props.backgroundColor : (props.setting && props.setting.backgroundColor ? props.setting.backgroundColor : 'rgb(255, 199, 9)'),
                        width: helpButtonHeight !== '' ? helpButtonHeight :(smallStyle ? '48px' : '60px'),
                    }}
                        onClick={() => handleHelpClick()}>
                    </Button> : <></>
                }
            </div>
        </>

    );
}
const HeaderwithHelpElementRegistration: FormElementRegistration<HeaderwithHelpProps> = {
    component: HeaderwithHelp,
    id: "HeaderwithHelp",
};
export default HeaderwithHelpElementRegistration;
