import { objectMap } from "./Object";
import {
  isValidDateString,
  isValidEmailString,
  isValidTelephoneString,
  isValidZipCodeString,
} from "./String";

export const getFormDataDefaults = (fields, defaults) =>
  objectMap(
    (field, key) => ({
      value:
        (typeof defaults === "undefined" ? field.default : defaults[key]) || "",
      error: false,
      message: "",
    }),
    fields
  );

export const getValidatedFormData = (data, fields) =>
  objectMap((state, key) => {
    const field = fields[key];
    const value = state.value.trim();
    let error = false;
    let message = "";
    if (!error && field.required && value === "") {
      error = true;
      message = "This field is required";
    }
    if (
      !error &&
      typeof field.minLength !== "undefined" &&
      ((!field.required && value === "") || value.length < field.minLength)
    ) {
      error = true;
      message = `This field require at least ${field.minLength} symbols`;
    }
    if (
      !error &&
      field.type === "date" &&
      ((!field.required && value === "") || !isValidDateString(value))
    ) {
      error = true;
      message = "Date format must be MM/DD/YYYY";
    }
    if (
      !error &&
      field.type === "email" &&
      ((!field.required && value === "") || !isValidEmailString(value))
    ) {
      error = true;
      message = "Invalid email format";
    }
    if (
      !error &&
      field.type === "phone" &&
      ((!field.required && value === "") || !isValidTelephoneString(value))
    ) {
      error = true;
      message = "Telephone format must be (###) ###-####";
    }
    if (
      !error &&
      field.type === "zip" &&
      ((!field.required && value === "") || !isValidZipCodeString(value))
    ) {
      error = true;
      message = "Zip Code must be 5 Digit";
    }
    if (
      !error &&
      field.type === "confirmPassword" &&
      data[field.compareTo].value !== value
    ) {
      error = true;
      message = "Passwords do not match";
    }
    return {
      ...state,
      value,
      error,
      message,
    };
  }, data);

export const handleFormDataChange = (e, name, data, fields) => {
  const value =
    (typeof e?.target?.value === "undefined" ? e.value : e.target.value) || "";
  const field = fields[name];
  if (
    typeof field.maxLength === "undefined" ||
    value.length <= field.maxLength
  ) {
    return { ...data, [name]: { ...data[name], value } };
  }
  return null;
};

export const isFormDataHasErrors = (data) => {
  console.log("data", data);
  return Object.values(data).reduce(
    (hasErrors, { error }) => hasErrors || error,
    false
  );
};
