import useVuelidate from "@vuelidate/core";
import {
  email,
  helpers,
  minLength,
  numeric,
  required,
  requiredIf,
  url,
} from "@vuelidate/validators";
import type { ComputedRef } from "vue";

export const invalid = (vuelidateProp: any) => {
  return vuelidateProp.$invalid && vuelidateProp.$dirty;
};

export const invalidRef = (vuelidateProp: any) => {
  return vuelidateProp.$invalid.value && vuelidateProp.$dirty.value;
};

export const getInvalidMessageVuelidate = (vuelidateProp: any) => {
  return {
    invalid: vuelidateProp.$invalid,
    message: vuelidateProp.$response.$message,
  };
};

export const requiredRule = helpers.withMessage(
  "Ce champ est obligatoire.",
  required
);

export const requiredIfRule = (value: boolean) =>
  helpers.withMessage("Ce champ est obligatoire.", requiredIf(value));

export const mustBeTrueRule = helpers.withMessage(
  "Ce champ doit être coché.",
  (value: boolean) => value
);

export const codePostalRule = helpers.withMessage(
  "Le code postal est invalide.",
  (value: string) => {
    return value.length === 5 && !isNaN(Number(value));
  }
);

export const emailRule = helpers.withMessage(
  "L'email est obligatoire et doit être au format correct.",
  email
);

export const passwordMinLengthRule = helpers.withMessage(
  "Le mot de passe doit contenir au moins 8 caractères.",
  minLength(8)
);

export const numericRule = helpers.withMessage(
  "Ce champ doit être numérique.",
  numeric
);

export const urlRule = helpers.withMessage(
  "Ce champ doit être une URL valide.",
  url
);

export const minLengthRule = (length: number) => {
  return helpers.withMessage(
    `Ce champ doit contenir au moins ${length} caractères.`,
    minLength(length)
  );
};

export const useV = (
  data: any,
  rules: ComputedRef<any>,
  options: { onSubmit?: (data?: any) => any } = {}
) => {
  const v = useVuelidate(rules, data);

  const validate = async () => {
    await v.value.$validate();
  };

  const isValid = async () => {
    await validate();

    if (v.value.$invalid) {
      console.log(v.value.$errors);
    }

    return !v.value.$invalid;
  };

  const isPropInvalid = (prop: string) => invalid(v.value[prop]);

  const getErrors = (prop: string): string =>
    v.value[prop]?.$errors?.map((e: any) => e.$message) || "";

  const getTextErrors = (prop: string): string =>
    v.value[prop]?.$errors?.map((e: any) => e.$message).join(", ") || "";

  const onSubmit = async (_data: any = {}) => {
    console.log(data);

    if (!(await isValid())) {
      console.log(v.value.$errors);
      return;
    }
    if (options.onSubmit) {
      options.onSubmit();
    }
  };

  return {
    validate,
    isValid,
    v,
    isPropInvalid,
    getErrors,
    getTextErrors,
    onSubmit,
  };
};
