import {useCallback} from "react";
import {
  TextareaAutosize,
  FormControl,
  InputLabel,
  FormHelperText,
} from "@mui/material";

import {TextAreaProps} from './interface'
import {getValidateMessageFunc} from '../InputWidget/utils';
import { InvalidMessage } from "@/widgetLibrary/PublicSector/InvalidMessage"

import { AutoHeightContainer } from "@/widgetLibrary/PublicSector/AutoHeightContainer"

export const TextArea= ({
  label,
  value,
  //   onChange,
  helperText,
  error,
  styles,
  minRows,
  maxRows,
  placeholder,
  required,
  tooltipText,
  validateMessage,
  hideValidationMessage,
  updateComponentHeight,
  handleUpdateDsl,
  maxLength,
  minLength,
  pattern,
  defaultValue,
  regex,
  disabled,
  readOnly,
  ...props
}:TextAreaProps) => {
  const handleValidate = useCallback(
    (value?: string) => {
  
      const message = getValidateMessageFunc(value, {
        hideValidationMessage: false,
        pattern: pattern,
        regex: regex,
        minLength: minLength,
        maxLength: maxLength,
        required: required,
      })
      handleUpdateDsl({
        validateMessage: message,
        value:value,
      })
      return message
    },
    [
      handleUpdateDsl,
      maxLength,
      minLength,
      pattern,
      regex,
      required,
    ],
  )

  const handleChange = (event) => {

    const {value} = event.target;
    
    handleValidate(value);
  };


  return (
    <AutoHeightContainer updateComponentHeight={updateComponentHeight}>
    <FormControl
      fullWidth
      variant="standard"
      error={error}
      {...props}
      sx={{padding:3,...styles}}
    >
      <InputLabel
        sx={label&&{
          position: "relative",
          paddingLeft: "10px",
          borderRadius: "10px",
          top: "-10px",
          left: "10px",
          zIndex: 4,
          background: "white",
          width: "100px",
          border: "1px solid gray",
        }}
      >
        {label}
      </InputLabel>
      <TextareaAutosize
        {...props}
        readOnly={readOnly}
        disabled={disabled}
        title={tooltipText}
        minRows={minRows}
        maxRows={maxRows}
        value={value}
        defaultValue={defaultValue}
        onChange={handleChange}
        placeholder={placeholder}
        required={required}
        style={{
          width: "100%",
          margin: "auto",
          borderRadius: "10px",
          paddingTop: "12px",
          paddingLeft: "5px",
        }}
      />
      {helperText && <FormHelperText>{helperText}</FormHelperText>}
    </FormControl>
    {((!hideValidationMessage&&validateMessage)&&value)&&(
        <div
        >
          <InvalidMessage validateMessage={validateMessage} />
        </div>
      )}
    </AutoHeightContainer>
  );
};

