import { Dispatch, SetStateAction, useEffect } from "react";
import { useFormContext } from "react-hook-form";
import { FieldArrayErrorConfig } from "../input";
import WarnIcon from "../../../resources/icons/warnIcon";
import React from "react";

export type InputWrapperProps = {
  isActive: boolean;
  inputState: "default" | "active" | "error" | "disabled";
  setInputState: Dispatch<
    SetStateAction<"default" | "active" | "error" | "disabled">
  >;
  hasFocus: boolean;
  wrapperClassName?: string;
  disabled?: boolean;
  hasDropdown?: boolean;
  name: string;
  children: React.ReactNode;
  heightClassName?: string;
  errorConfig?: FieldArrayErrorConfig;
  noBorder?: boolean;
};

export default function InputWrapper({
  isActive,
  inputState,
  setInputState,
  hasFocus,
  name,
  wrapperClassName,
  disabled,
  children,
  hasDropdown = false,
  heightClassName = "h-14",
  errorConfig,
  noBorder = false,
}: InputWrapperProps) {
  const {
    formState: { errors, isValidating },
  } = useFormContext();

  const hasError = () => {
    const error = errorConfig ? errors[errorConfig.baseName] : errors[name];

    if (!error) {
      return false;
    }

    if (error && !errorConfig) {
      return true;
    }

    if (!Array.isArray(error) || !errorConfig) {
      return false;
    }

    const errorElement = error[errorConfig.errorIndex];

    if (!errorElement) {
      return false;
    }

    const errorMessage = errorElement[errorConfig.fieldName];

    if (errorMessage) {
      return true;
    }
  };

  const getErrorMsg = () => {
    const error = errorConfig ? errors[errorConfig.baseName] : errors[name];

    if (!error) {
      return;
    }

    if (!errorConfig) {
      return error?.message?.toString();
    }

    if (!Array.isArray(error)) {
      return;
    }

    const errorElement = error[errorConfig.errorIndex];
    const errorMessage = errorElement[errorConfig.fieldName];

    if (errorMessage) {
      return errorMessage.message.toString();
    }

    return "";
  };

  useEffect(() => {
    if (disabled) {
      setInputState("disabled");
      return;
    }

    if (hasError() && !hasFocus) {
      setInputState("error");
      return;
    }

    if (hasFocus) {
      setInputState("active");
      return;
    }

    if (!hasFocus) {
      setInputState("default");
    }
  }, [isValidating, disabled, isActive, hasFocus, errors]);

  return (
    <div className={`${wrapperClassName}`} id={`error-${name}`}>
      {noBorder ? (
        <div
          className={`input-state-${inputState}  relative rounded-lg flex justify-start ${heightClassName} ${
            !hasDropdown && "overflow-hidden"
          }`}
        >
          {children}
        </div>
      ) : (
        <div
          className={`input-state-${inputState} ${
            inputState === "active" ? "border-2" : "border"
          } relative rounded-lg flex justify-start ${heightClassName} ${
            !hasDropdown && "overflow-hidden"
          }`}
        >
          {children}
        </div>
      )}
      {hasError() && !hasFocus && (
        <div className="pt-2 h-fit flex flex-row gap-2">
          <WarnIcon className="fill-semantic-alarm" width={16} height={16} />
          <span className="text-neutral-very-dark leading-none">
            {getErrorMsg()}
          </span>
        </div>
      )}
    </div>
  );
}
