import { useMutation } from "@tanstack/react-query";
import axios from "axios";
import { FC, useEffect } from "react";
import { useFormContext } from "react-hook-form";
import { InputField } from "../forms/Inputs";

type props = {
  name: string;
  labelText?: string;
  placeholder?: string;
  mandatory?: boolean;
  message?: string;
  fieldId?: string | number | null;
};
const UniqueField: FC<props> = ({
  name,
  labelText,
  placeholder,
  mandatory = false,
  message = undefined,
  fieldId = undefined,
}) => {
  const {
    setValue,
    setError,
    watch,
    formState: { errors },
  } = useFormContext();
  const {
    mutate: checkDuplicate,
    isPending: pending,
    error,
  } = useMutation({
    mutationFn: async (formData: any) => {
      const { data } = await axios.post(
        `/api/check-duplicate?item=${name}`,
        formData
      );
      return data?.data;
    },
    onSuccess: (data) => {
      if (data) {
        const msg = message ?? name;
        setError(name, { type: "custom", message: `${msg} already exist!` });
      }
    },
    onError: (error: any) => {},
  });

  const field = watch(name);

  useEffect(() => {
    if (field?.length > 1) {
      checkDuplicate({
        [name]: field,
        uuid: fieldId,
      });
    }
  }, [field, fieldId]);

  useEffect(() => {
    if (fieldId) {
      setValue("id", fieldId);
    }
  }, [fieldId]);

  return (
    <>
      <InputField
        name={name}
        labelText={labelText}
        placeholder={placeholder}
        errors={errors}
        mandatory={mandatory}
      />
    </>
  );
};

export default UniqueField;
