import React, { FC, Fragment, useState, useRef, useContext } from "react";
import cx from 'classnames';
import { InferProps } from "prop-types";
import { InputProps } from "./Input.types";
import { Tooltip, Icons, Button } 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('<', '< ');
    }
  });
};


/**
* 
* @prop  {string} id-> String to identify component as unique
* @prop {string} Label -> String to place as label related to this input 
* @prop {"text"| "password"| "email"} type -> Type of input (text) needed
* @property {string} assistiveText -> Text to be displayed below input for aditional information
* @prop {string} placeholder -> Text to display when there is no input yet.
*/
export const Input: FC<InputProps> = ({
  id,
  type = "text",
  style = {},
  className,
  maxLength,
  label = "",
  assistiveText = "",
  placeholder = "",
  icon,
  buttonText,
  isDisabled = false,
  tooltip,
  value = "",
  onChange,
  onClick,
  loading,
  iconPosition = 'right',
  autoFocus= false,
  isRequiere,
}) => {
  const [focused, setFocused] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);
  const formContext: any = useContext(FormContext as any);
  const labels = {
    label: useLocale(label),
    tooltip: useLocale(tooltip),
    placeholder: useLocale(placeholder),
    buttonText: useLocale(buttonText),
    assistiveText: useLocale(assistiveText)
  }

  const handleIconClick = () => {
    if (inputRef.current && !isDisabled && !loading) {
      inputRef.current.focus();
    }
  };
  return (
    <div className="input-gtc-rc-wrap">
      <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",
        (loading || isDisabled)  && "input-gtc-rc-mid-div-disabled",
        (isRequiere && formContext?.submitAttempted && !value) && "is-required",
        className
      )}>
        {icon && iconPosition === 'left' &&
          <div className="input-gtc-rc-icon-div" onClick={handleIconClick} style={{ cursor: 'pointer' }}>
            <Icons name={icon} size="small"/>
          </div>
        }
        <input
          ref={inputRef}
          id={id}
          style={ style }
          className={cx('input-gtc-rc-normal', icon && iconPosition === 'left' && "inputWithIcon-gtc-rc", (loading ||isDisabled) && "input-gtc-rc-disabled" )}
          type={type}
          placeholder={labels['placeholder']}
          value={value}
          onChange={(e) => {
            const sanitizedValue = sanitizeHtmlTags(e.target.value);
            onChange && onChange(sanitizedValue);
          }}
          maxLength={maxLength}
          disabled={isDisabled || loading}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          autoFocus={autoFocus}
        />
        {icon && iconPosition === 'right' &&
          <div className="input-gtc-rc-icon-div" onClick={handleIconClick} style={{ cursor: 'pointer' }}>
            <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 || loading}
            >
              {labels["buttonText"]}
            </Button>
          </div>
        }
      </div>
      <div className="input-gtc-rc-bottom-div">
        {assistiveText && 
          <AssistiveText warning={false} focused={focused}>
            {labels["assistiveText"]} 
          </AssistiveText>
        }
      </div>
    </div>
  );
};
