import React, { useEffect,useState } from 'react'
import { useForm ,Controller} from 'react-hook-form';
import { set, z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { MasterRespository } from '../../repositories/MastersRepository';
import { cacheData,getCachedData } from '../../slices/apiDataManager';
import showToast from '../../services/toastService';
import {useUpdateJobRole} from '../../hooks/masterHook/useMaster';



const schema = z.object({
  role: z.string().min(1, { message: "Role is required" }),
  description: z.string().min(1, { message: "Description is required" })
  .max(255, { message: "Description cannot exceed 255 characters" }),
});



const EditJobRole = ({data,onClose}) => {
const [descriptionLength, setDescriptionLength] = useState(data?.description?.length || 0);
  const maxDescriptionLength = 255;

  const {
    register,
    handleSubmit,
    formState: { errors },
    reset,
    watch,
  } = useForm({
    resolver: zodResolver(schema),
    defaultValues: {
      role: data?.name || "",
      description: data?.description || "",
    },
  });

  const { mutate: updateJobRole, isPendin:isLoading } = useUpdateJobRole(() => {
    onClose?.();
  });
// const onSubmit = (formdata) => {
    //   setIsLoading(true)
    //   const result = {
    //     id:data?.id,
    //     name: formdata?.role,
    //     description: formdata.description,  
    //   };

     
    
    //   MasterRespository.updateJobRole(data?.id,result).then((resp)=>{
    //     setIsLoading(false) 
    //     showToast("JobRole Update successfully.", "success");
    //     const cachedData = getCachedData("Job Role");
    //     if (cachedData) {

    //       const updatedData = cachedData.map((role) =>
    //         role.id === data?.id ? { ...role, ...resp.data } : role
    //       );
    //       cacheData("Job Role", updatedData);
    //     }

    //     onClose()
    //   }).catch((error)=>{
    //      showToast(error.message, "error")
    //     setIsLoading(false)
    //   })
     
    // };

  const onSubmit = (formData) => {
    updateJobRole({
      id: data?.id,
      payload: {
        id: data?.id,
        name: formData.role,
        description: formData.description,
      },
    });
  };

  useEffect(() => {
    reset({
      role: data?.name || "",
      description: data?.description || "",
    });
    setDescriptionLength(data?.description?.length || 0);
  }, [data, reset]);

  useEffect(() => {
    const sub = watch((values) => {
      setDescriptionLength(values.description?.length || 0);
    });
    return () => sub.unsubscribe();
  }, [watch]);
     
  return (<>
    <form  className="row g-2" onSubmit={handleSubmit(onSubmit)}>
      {/* <div className="col-12 col-md-12">
        <label className="fs-5 text-dark text-center d-flex align-items-center justify-content-center flex-wrap">Edit Job Role</label>        
      </div> */}
        <div className="col-12 col-md-12">
          <label className="form-label">Role</label>
          <input type="text" 
           {...register("role")} 
             className={`form-control ${errors.role ? 'is-invalids' : ''}`}
          />
          {errors.role && <p className="text-danger">{errors.role.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' : ''}`}
          onChange={(e) => {
            setDescriptionLength(e.target.value.length);
            register("description").onChange(e);
          }}
        ></textarea>
        <div className="text-end small text-muted">
          {maxDescriptionLength - descriptionLength} characters left
        </div>
        {errors.description && (
          <p className="text-danger">{errors.description.message}</p>
        )}

        </div>

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

export default EditJobRole;