import React, { useEffect } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useCreatePaymentMode, useUpdatePaymentMode } from "../../hooks/masterHook/useMaster";

const ExpnseSchema = z.object({
  name: z.string().min(1, { message: "Name is required" }),
  description: z.string().min(1, { message: "Description is required" }),
});

const ManagePaymentMode = ({ data = null, onClose }) => {
  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(ExpnseSchema),
    defaultValues: { name: "",  description: "" },
  });

  const { mutate: CreatePaymentMode, isPending } = useCreatePaymentMode(() =>
    onClose?.()
  );
  const {mutate:UpdatePaymentMode,isPending:Updating} = useUpdatePaymentMode(()=>onClose?.())

  const onSubmit = (payload) => {
    if(data){
        UpdatePaymentMode({id:data.id,payload:{...payload,id:data.id}})
    }else(
        CreatePaymentMode(payload)
    )
    
  };

  useEffect(()=>{
    if(data){ 
      reset({
        name:data.name ?? "",
        description:data.description ?? ""
      })
    }
  },[data])


  return (
    <form className="row g-2" onSubmit={handleSubmit(onSubmit)}>
      <div className="col-12 col-md-12">
        <label className="form-label">Payment Mode Name</label>
        <input
          type="text"
          {...register("name")}
          className={`form-control ${errors.name ? "is-invalids" : ""}`}
        />
        {errors.name && <p className="danger-text">{errors.name.message}</p>}
      </div>
      <div className="col-12 col-md-12">
        <label className="form-label" htmlFor="description">
          Description
        </label>
        <textarea
          rows="3"
          {...register("description")}
          className={`form-control ${errors.description ? "is-invalids" : ""}`}
        ></textarea>

        {errors.description && (
          <p className="danger-text">{errors.description.message}</p>
        )}
      </div>

      <div className="col-12 text-center">
        <button
          type="submit"
          className="btn btn-sm btn-primary me-3"
          disabled={isPending || Updating}
        >
          {isPending || Updating? "Please Wait..." : Updating ? "Update" : "Submit"}
        </button>
        <button
          type="reset"
          className="btn btn-sm btn-label-secondary "
          data-bs-dismiss="modal"
          aria-label="Close"
          disabled={isPending || Updating}
        >
          Cancel
        </button>
      </div>
    </form>
  );
};

export default ManagePaymentMode;
