import React, { ChangeEvent, FocusEvent } from "react";
import { TextField, TextFieldProps } from "@mui/material";

interface IntelliwealthTextFieldProps extends Omit<TextFieldProps, "onChange"> {
  onFocus?: (event: FocusEvent<HTMLInputElement>) => void;
  onBlur?: (event: FocusEvent<HTMLInputElement>) => void;
  errorMessage?: string;
  setErrorMessage?: (message: string) => void;
  onChange?: (event: ChangeEvent<HTMLInputElement>) => void;
}

const IntelliwealthTextField: React.FC<IntelliwealthTextFieldProps> = ({
  id,
  type,
  value,
  placeholder,
  label,
  onChange,
  onFocus,
  onBlur,
  error,
  helperText,
  fullWidth,
  disabled,
  sx,
  errorMessage,
  setErrorMessage,
  ...rest
}) => {
  const handleFocus = (event: FocusEvent<HTMLInputElement>) => {
    if (setErrorMessage) setErrorMessage("");
    if (onFocus) onFocus(event);
  };

  const handleBlur = (event: FocusEvent<HTMLInputElement>) => {
    if (setErrorMessage && errorMessage && event.target.value.length > 0) {
      setErrorMessage(errorMessage);
    }
    if (onBlur) onBlur(event);
  };

  return (
    <TextField
      id={id}
      type={type}
      value={value}
      placeholder={placeholder}
      label={label}
      variant="outlined"
      onChange={onChange}
      onFocus={handleFocus}
      onBlur={handleBlur}
      error={error}
      helperText={helperText}
      fullWidth={fullWidth}
      disabled={disabled}
      sx={{
        "& .MuiOutlinedInput-root": {
          height: "45px",
          borderRadius: "8px",
          "& fieldset": { borderColor: "#757575" },
        },
        "& .MuiInputLabel-root": { color: "#000000", fontSize: "14px" },
        "& .MuiInputBase-input": { color: "#000000", fontSize: "14px", lineHeight: "20px" },
        ...sx,
      }}
      {...rest}
    />
  );
};

export default IntelliwealthTextField;