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


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

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

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

  const { mutate: updateContactCategory, isPending: isLoading } = useUpdateContactCategory(() => onClose?.());

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

    updateContactCategory({ id: data?.id, payload });
  };
  // const onSubmit = (formdata) => {
  //     setIsLoading(true)
  //     const result = {
  //       id:data?.id,
  //       name: formdata?.name,
  //       description: formdata.description,  
  //     };



  //     MasterRespository.updateContactCategory(data?.id,result).then((resp)=>{
  //       setIsLoading(false) 
  //       showToast("Contact Category Updated successfully.", "success");
  //       const cachedData = getCachedData("Contact Category");
  //       if (cachedData) {

  //         const updatedData = cachedData.map((category) =>
  //           category.id === data?.id ? { ...category, ...resp.data } : category
  //         );
  //         cacheData("Contact Category", updatedData);
  //       }

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

  //   };

  const resetForm = () => {
    reset({ name: "", description: "" });
    setDescriptionLength(0);
  };

  useEffect(() => {
    return () => resetForm();
  }, []);

  return (<>
    <form className="row g-2" onSubmit={handleSubmit(onSubmit)}>
      <div className="col-12 col-md-12">
        <label className="form-label">Category Name</label>
        <input type="text"
          {...register("name")}
          className={`form-control ${errors.name ? 'is-invalids' : ''}`}
        />
        {errors.name && <p className="text-danger">{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' : ''}`}
          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"   // ✅ not reset
          className="btn btn-sm btn-label-secondary"
          onClick={() => {
            resetForm();   // clear inputs
            onClose?.();   // close modal from parent
          }}
        >
          Cancel
        </button>
      </div>

    </form>

  </>
  )
}

export default EditContactCategory;