import { useEffect } from "react";
import { modelProps } from "../types/props";

export function setFormId(modelName: string, field: string) {
  return `${modelName}[${field}]`;
}

export function setValue(field: string, model: modelProps): string | undefined {
  if (model.fields !== undefined) {
    if (field in model.fields) {
      const value = model.fields;
      return value[field] as string;
    }
  }
  return undefined;
}

export function setLabels(
  label: string | boolean | null | undefined,
  field: string,
  model: modelProps,
): string | false {
  if (model.labels === undefined) {
    return false;
  }
  if (label === null || label === undefined || label === true) {
    const labels = model.labels;
    if (field in labels) {
      label = labels[field];
    } else {
      label = false;
    }
  }
  return label;
}

export function setHints(
  hint: string | boolean | null,
  field: string,
  model: modelProps,
): string | false {
  if (hint === true) {
    const hints = model.hints;
    if (field in hints) {
      hint = hints[field];
    } else {
      hint = false;
    }
  } else if (hint === null) {
    hint = false;
  }
  return hint;
}

export function setGroupClass(groupClass: string | null | undefined) {
  if (groupClass === undefined) {
    groupClass = "mb-3";
  }
  if (groupClass === null) {
    groupClass = "";
  }
  return groupClass;
}

export function SetErrorValidation(
  setErrorClass: React.Dispatch<React.SetStateAction<string>>,
  setFormValidation: React.Dispatch<React.SetStateAction<string>>,
  errorMessage: string | null | undefined,
) {
  useEffect(() => {
    if (errorMessage === null || errorMessage === undefined) {
      // Skip initial execution
      return;
    }

    if (errorMessage !== "") {
      setErrorClass("invalid-feedback");
      setFormValidation("is-invalid");
    } else {
      setErrorClass("valid-feedback");
      setFormValidation("is-valid");
    }
  }, [errorMessage, setErrorClass, setFormValidation]);
}

export function performChangeValidation(
  input: EventTarget & HTMLInputElement,
  setValidated: React.Dispatch<React.SetStateAction<boolean>>,
) {
  const parent = input.parentNode as HTMLDivElement;
  const feedbackField = (
    parent.className === "input-group" ? parent.nextSibling : input.nextSibling
  ) as HTMLDivElement;

  if (input.checkValidity() === false) {
    // Not Valid
    input.classList.add("is-invalid");
    input.classList.remove("is-valid");
    feedbackField.classList?.add("invalid-feedback");
    feedbackField.classList?.remove("valid-feedback");
    feedbackField.innerHTML = input.validationMessage;
    setValidated(false);
  } else {
    // Valid
    input.classList.add("is-valid");
    input.classList.remove("is-invalid");
    feedbackField.classList?.add("valid-feedback");
    feedbackField.classList?.remove("invalid-feedback");
    feedbackField.innerHTML = "";
  }
}
