import React, { FC, useState, useContext } from "react";
import cx from 'classnames';
import { InputInlineProps } from "./InputInline.types";
import { IconButton } from "..";
import "./InputInline.scss";
import { AssistiveText } from "../AssistiveText";
import { useLocale } from "../../hooks/useLocale";
import { FormContext } from "../Form";

/**
 * Function to detect and malform HTML tags in input text
 * This prevents HTML injection by breaking the tag structure
 * @param text - The input text to sanitize
 * @returns The sanitized text with malformed HTML tags
 */
const sanitizeHtmlTags = (text: string): string => {
  // Regular expression to match HTML tags (opening and closing)
  const htmlTagRegex = /<\/?[a-zA-Z][^>]*>/g;
  
  return text.replace(htmlTagRegex, (match) => {
    // Malform the tag by inserting a space after the opening < or before the closing >
    if (match.startsWith('</')) {
      // Closing tag: </tag> -> </ tag>
      return match.replace('</', '</ ');
    } else {
      // Opening tag: <tag> -> < tag>
      return match.replace('<', '< ');
    }
  });
};

export const InputInline: FC<InputInlineProps> = ({
    id,
    type = "text",
    style = {},
    valueStyle = {},
    className,
    maxLength,
    assistiveText = "",
    placeholder = "",
    disabled = false,
    value = "",
    onChange,
    onClick,
    loading,
    isRequiere
}) => {
    const [focused, setFocused] = useState(false);
    const [invalid, setInvalid] = useState(false);
    const [editMode, setEditMode] = useState(false);
    const [backupValue, setBackupValue] = useState("");
    const formContext: any = useContext(FormContext as any);

    const labels = {
        placeholder: useLocale(placeholder),
        assistiveText: useLocale(assistiveText)
    }
    return (
        <div className="input-inline-container">
            {
                (editMode || !value) ?
                    <div
                        className={cx(
                            "input-inline-wrap",
                            focused && "input-gtc-rc-focused",
                            (invalid || (isRequiere && formContext?.submitAttempted && !backupValue && !value)) && "is-required",
                            (loading || disabled) && "input-gtc-rc-mid-div-disabled",
                            className
                        )}
                    >
                        <input
                            id={id}
                            style={style}
                            className={cx(
                                'input-gtc-rc-normal',
                                (loading || disabled) && "input-gtc-rc-disabled",
                                "input-inline",
                            )}
                            type={type}
                            placeholder={labels['placeholder']}
                            value={backupValue}
                            onClick={onClick}
                            onChange={(e) => {
                                setInvalid(false);
                                const sanitizedValue = sanitizeHtmlTags(e.target.value);
                                setBackupValue(sanitizedValue)
                            }}
                            maxLength={maxLength}
                            disabled={disabled || loading}
                            onFocus={() => setFocused(true)}
                            onBlur={() => setFocused(false)}
                        />

                        <div className="input-inline-check-button">
                            <IconButton
                                icon="check"
                                className="inline-icon check-icon"
                                size="xsmall"
                                onClick={(e: any) => {
                                    if (e) e.preventDefault();
                                    if (!backupValue) {
                                        setInvalid(true);
                                        return;
                                    }

                                    if(onChange) {
                                        onChange(backupValue);
                                    }
                                    setBackupValue("");
                                    setEditMode(false);
                                }}
                            />
                        </div>

                        <div className="input-inline-cancel-button">
                            <IconButton
                                icon="close"
                                className="input-inline-icon cancel-icon"
                                size="xsmall"
                                onClick={(e) => {
                                    if (e) e.preventDefault();
                                    setBackupValue("");
                                    setEditMode(false);
                                }}
                            />
                        </div>
                    </div> :
                    <div
                        className="input-inline-value"
                        onClick={() => {
                            setEditMode(true);
                            setBackupValue(value);
                        }}
                        style={valueStyle}
                    >
                        {value}
                    </div>
            }


            <div className="input-gtc-rc-bottom-div">
                {assistiveText &&
                    <AssistiveText warning={false} focused={focused}>
                        {labels["assistiveText"]}
                    </AssistiveText>
                }
            </div>
        </div>
    );
};
