"use client";

import toast from "react-hot-toast";
import { errorMessage } from "./variables";

export const validateForm = (items, requiredFields = []) => {
  const errors = {};

  requiredFields.forEach((field) => {
    if (!items[field]?.toString().trim()) {
      errors[field] = "This field is required";
    }
  });

  return errors;
};

export const validateAndAlert = (formData, requiredFields = null) => {
  const errorMessage = (message) => {
    toast.dismiss();
    toast.error(message);
  };

  const errors = {};

  const fieldsToCheck = (requiredFields || Object.keys(formData)).filter(
    (field) => field !== "id"
  );

  fieldsToCheck.forEach((field) => {
    if (!formData[field]?.toString().trim()) {
      errors[field] = "is required";
    }
  });

  if (Object.keys(errors).length > 0) {
    const errorMessages = Object.entries(errors)
      .map(
        ([field, message]) =>
          `${field
            .replace(/_/g, " ")
            .replace(/\b\w/g, (c) => c.toUpperCase())} ${message}`
      )
      .join("\n");

    errorMessage(errorMessages);
    return false;
  }

  return true;
};


export const validateBetweenDate = (startDate, expiryDate, startLabel, expiryLabel) => {
  const start = new Date(startDate);
  const expiry = new Date(expiryDate);

  if (expiry < start) {
    errorMessage(`${expiryLabel} should not be earlier than ${startLabel}`);
    return false;
  }else{
return true;
  }

  
};



 export const handleChange = (eOrValue, setForm) => {
    let name, value;

    if (eOrValue?.target) {
      name = eOrValue.target.name;
      value =
        eOrValue.target.type === "checkbox"
          ? eOrValue.target.checked
          : eOrValue.target.value;
    } else if (Array.isArray(eOrValue)) {
      name = "tags";
      value = eOrValue;
    }

   
      if (name) {
    setForm((prev) => ({
      ...prev,
      [name]: value,
    }));
  }
  
  };