import React, { useMemo, useState } from "react";
import { TextField, TextFieldProps } from "@mui/material";
import { Dictionary } from "@types";

export type TextFieldCustomProps = {
  onFix?: () => void;
  onChangeValue?: (val: string) => void;
  messages?: Dictionary;
  readonly?: boolean;
} & TextFieldProps;

export default function TextFieldCustom({
  onFix,
  onChangeValue,
  messages,
  readonly,
  ...others
}: TextFieldCustomProps) {
  const [oldValue, setOldValue] = useState<string | null>(null);

  const inputProps = useMemo(() => {
    if (readonly) {
      return {
        style: { color: "rgb(50, 50, 50)" },
        disabled: true,
      };
    } else {
      return undefined;
    }
  }, [readonly]);

  const fix = (newValue: string) => {
    if (oldValue !== newValue) {
      setOldValue(newValue);
      if (onFix) {
        onFix();
      }
    }
  };

  const handleEnter = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") {
      if (e.target instanceof HTMLInputElement) {
        fix(e.target.value);
      }
    }
  };

  const handleBlur = (e: React.FocusEvent<HTMLInputElement>) => {
    if (!others.select) {
      fix(e.target.value);
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (onChangeValue) {
      onChangeValue(e.target.value);
    }
    if (others.select) {
      fix(e.target.value);
    }
  };

  const message = useMemo(() => {
    if (messages && others.name) {
      return messages[others.name] ?? "";
    } else {
      return "";
    }
  }, [messages]);

  const error = useMemo(() => {
    if (messages && others.name) {
      return (
        messages[others.name] !== undefined &&
        messages[others.name].length !== 0
      );
    } else {
      return false;
    }
  }, [messages]);

  return (
    <TextField
      size="small"
      onKeyDown={handleEnter}
      onBlur={handleBlur}
      onChange={handleChange}
      helperText={message}
      error={error}
      inputProps={inputProps}
      {...others}
    />
  );
}
