import React, { FC, Fragment, useState, useContext } from "react";
import cx from 'classnames';
import { InputNumericProps } from "./InputNumeric.types";
import { Tooltip, Button, Icons } from "../";
import "./Input.scss";
import { AssistiveText } from "../AssistiveText";
import { Label } from "../Label";
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 InputNumeric: React.FC<InputNumericProps> = ({
  id,
  type = "number",
  style = {},
  className = "",
  isInteger = false, //float by default
  step = 0.1,
  decimalPlaces,
  label = "",
  assistiveText = "",
  placeholder = "",
  icon,
  buttonText,
  isDisabled = false,
  min,
  max,
  tooltip,
  value,
  iconPosition = "right",
  loading = false,
  maxLength,
  onChange,
  onClick,
  isRequiere,
}) => {

  const [focused, setFocused] = useState(false);
  const formContext: any = useContext(FormContext as any);

  const labels = {
    label: useLocale(label),
    tooltip: useLocale(tooltip),
    placeholder: useLocale(placeholder),
    buttonText: useLocale(buttonText),
    assistiveText: useLocale(assistiveText)
  }

  let currencyValue = ""
  if (decimalPlaces && value) {
    currencyValue = '$' + parseFloat(value).toFixed(decimalPlaces)
  } else if (value) {
    currencyValue = '$' + parseFloat(value)
  }

  return (
    <div className="input-gtc-rc-wrap" style={style}>
      <div className="input-gtc-rc-top-div">
        {label &&
          <div className="input-gtc-rc-label">
            <Label>{labels["label"]}</Label>
          </div>
        }
        {tooltip &&
          <div className="inputTooltip-gtc-rc">
            <Tooltip title={labels["tooltip"]}>
              <Icons name={"info"} color="#8b8b8b" size="small" />
            </Tooltip>
          </div>
        }
      </div>
      <div className={cx(
        "input-gtc-rc-mid-div",
        focused && "input-gtc-rc-focused",
        (isDisabled || loading) && "input-gtc-rc-mid-div-disabled",
        (isRequiere && formContext?.submitAttempted && (value === undefined || value === null || value === "")) && "is-required",
        className
      )}>
        {icon && iconPosition === 'left' &&
          <div className="input-gtc-rc-icon-div">
            <Icons name={icon} size="small" />
          </div>
        }
        <input
          id={id}
          style={style}
          className={cx('input-gtc-rc-normal', icon && iconPosition === 'left' && "inputWithIcon-gtc-rc", (isDisabled || loading) && "input-gtc-rc-disabled")}
          type={focused ? "number" : "text"}
          placeholder={labels["placeholder"]}
          value={!focused && type == "currency" ? currencyValue : value}
          min={min != undefined && min != null ? min : undefined}
          max={max != undefined && max != null ? max : undefined}
          onChange={(e) => {
            // Sanitize HTML tags first
            const sanitizedValue = sanitizeHtmlTags(e.target.value);
            
            //fix the decimal places
            if (sanitizedValue.split(".")[1]) {
              if (decimalPlaces && sanitizedValue.split(".")[1]?.length > decimalPlaces) {
                return;
              }
            }

            const inputValue = sanitizedValue;
            const parsedValue = parseFloat(sanitizedValue);
            if (maxLength && !isNaN(parsedValue) && inputValue.toString().length > maxLength) {
              return
            }

            const newValue = (isInteger && sanitizedValue ? parseInt(sanitizedValue) : sanitizedValue);
            onChange && onChange(newValue)
          }}
          disabled={isDisabled || loading}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          step={isInteger ? 1 : step}
          maxLength={maxLength}
        />
        {icon && iconPosition === 'right' &&
          <div className="input-gtc-rc-icon-div">
            <Icons name={icon} size="small" />
          </div>
        }
        {buttonText &&
          <div className="button-input-gtc-rc">
            <Button
              variant="tertiary"
              onClick={onClick!}    // ! added to avoid message about undefined
              isDisabled={isDisabled}
            >
              {labels["buttonText"]}
            </Button>
          </div>
        }
      </div>
      <div className="input-gtc-rc-bottom-div">
        {assistiveText &&
          <AssistiveText focused={focused}>
            {labels["assistiveText"]}
          </AssistiveText>
        }
      </div>
    </div>
  );
};