import { Input, Typography } from "@material-tailwind/react";
import { HTMLInputTypeAttribute, useEffect, useState } from "react";
import { UseFormReturn } from "react-hook-form";

import { useFormStore } from "../stores/formStore";
import { renderTitleWithRedAsterisk } from "../utils/app.util";

export interface InputFieldProps {
  title: string;
  placeholder?: string;
  value?: string;
  type?: HTMLInputTypeAttribute;
  name?: string;
  formId: string;
  disabled?: boolean;
  className?: string;
  readOnly?: boolean;
  format?: string;
  onChange?: (e: React.FormEvent<HTMLInputElement>) => void;
}

export default function Inputfield({
  className,
  title,
  placeholder,
  value,
  name,
  formId,
  type = "text",
  readOnly,
  format,
  disabled,
  onChange,
}: InputFieldProps) {
  const { reactHookUseForm } = useFormStore();
  const { register, formState, setValue, watch } =
    (reactHookUseForm as { [key: string]: UseFormReturn<any> })?.[formId] ?? {};
  const { errors } = formState ?? {};
  const [error, setError] = useState<any>(null);
  const fieldKey = name ?? title?.toLowerCase();

  const watchField = watch?.(`${fieldKey}`);

  useEffect(() => {
    setTimeout(() => {
      if (errors?.[fieldKey]) {
        setError(errors[fieldKey]);
      } else {
        setError(null);
      }
    }, 100);
  }, [watchField, errors, fieldKey]);

  const handleOnChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setValue(`${fieldKey}`, e.target.value, { shouldValidate: true });
    if (onChange) onChange(e);
  };

  if (!reactHookUseForm || !register) return <></>;

  return (
    <div className="w-full">
      <Typography
        variant="lead"
        className="text-xs font-medium text-black-400 mb-1"
      >
        {renderTitleWithRedAsterisk(title)}
        {format && <span className="text-purple-500">&nbsp;E.g: {format}</span>}
      </Typography>
      <Input
        placeholder={placeholder ?? title}
        value={value}
        type={type}
        readOnly={readOnly}
        error={error ? true : false}
        disabled={disabled}
        crossOrigin={undefined}
        labelProps={{
          className: "hidden",
        }}
        className={`
                    w-full min-w-full h-10 text-xs font-normal p-3
                    bg-white rounded-md	
                    text-gray-900 
                    shadow-gray-200/5 
                    ring-2 ring-transparent 
                    placeholder:text-gray-300 placeholder:opacity-100 
                    !border !border-slate-100 !border-t-slate-100  
                    ${error ? "!border-red-500 !border-t-red-500 ring-red-50 bg-red-100/10" : "!border-t-slate-100"} 
                    focus:!border-slate-300                  
                    focus:ring-gray-300/10 
                    focus:bg-offWhite
                    shadow-none 
                    ${className}
                    `}
        containerProps={{ className: "h-10 min-w-min" }}
        {...register(`${fieldKey}`, { onChange: handleOnChange })}
      ></Input>

      {error && error?.message && (
        <Typography
          variant="lead"
          className="text-red-500 font-normal text-[0.6rem]  px-1 block md:absolute -bottom-[1.1rem] left-0 errorText"
        >
          {error?.message}{" "}
        </Typography>
      )}
    </div>
  );
}
