import React, { useEffect, useState } from "react";
import { useForm, useFieldArray } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import {MasterRespository} from "../../repositories/MastersRepository";
import showToast from "../../services/toastService";
import {getCachedData,cacheData} from "../../slices/apiDataManager";


const schema = z.object({
  activityName: z.string().min(1, { message: "Activity name is required" }),
  unitOfMeasurement: z.string().min(1, { message: "Measurement is required" }),
  checkList: z
    .array(
      z.object({
        id: z.any().default(null),
        description: z.string().min(1, { message: "Checklist item cannot be empty" }),
        isMandatory: z.boolean().default(false),
      })
    )
    .optional(),
});


const UpdateActivity = ({ activityData, onClose }) => {
  const [isLoading, setIsLoading] = useState(false);

  const {
    register,
    handleSubmit,
    control,
    setValue,
    reset,
    setError,
    clearErrors,
    getValues,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(schema),
    defaultValues: {
        id:activityData.id,
        activityName: activityData.activityName,
        unitOfMeasurement: activityData.unitOfMeasurement,
        checkLists: activityData.checkLists || [],
    },
  });

  const { fields: checkListItems, append, remove } = useFieldArray({
    control,
    name: "checkList",
  });

  // Load initial data
  useEffect(() => {
    if (activityData) {
      reset( {
        id:activityData.id,
        activityName: activityData.activityName,
        unitOfMeasurement: activityData.unitOfMeasurement,
        checkList: activityData.checkLists || [],
      });
    }
  }, [activityData]);

  
  const handleChecklistChange = (index, value) => {
    setValue(`checkList.${index}`, value);
  };

  // Submit handler
  const onSubmit = async(data) => {
    setIsLoading(true);
  
    const Activity = {...data, id:activityData.id}
    try
    {
      const response = await MasterRespository.updateActivity( activityData?.id, Activity );
      const updatedActivity = response.data;
      const cachedData = getCachedData("Activity")
  
      if (cachedData) {
        const updatedActivities = cachedData.map((activity) =>
          activity.id === updatedActivity.id ? { ...activity, ...updatedActivity } : activity
        );
  
        cacheData( "Activity", updatedActivities );
        onClose()
      }
      setIsLoading( false )
      showToast("Activity Successfully Updated", "success");
    } catch ( err )
    {
      setIsLoading( false )

      showToast("error.message", "error");
    }
  };



  // Add new checklist item
  const addChecklistItem = () => {
    const values = getValues("checkList");
    const lastIndex = checkListItems.length - 1;

    if (
      checkListItems.length > 0 &&
      (!values?.[lastIndex] || values[lastIndex].description.trim() === "")
    ) {
      setError(`checkList.${lastIndex}.description`, {
        type: "manual",
        message: "Please fill this checklist item before adding another.",
      });
      return;
    }

    clearErrors(`checkList.${lastIndex}.description`);
    append({ id: null, description: "", isMandatory: false });
  };

  const removeChecklistItem = (index) => {
    remove(index);
  };


    // for tooltip
      useEffect(() => {
        const tooltipTriggerList = Array.from(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        tooltipTriggerList.forEach((el) => new bootstrap.Tooltip(el));
      }, []);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <h6>Update Activity</h6>
      <div className="row">
        {/* Activity Name */}
        <div className="col-md-6">
          <label  className="form-label">Activity Name</label>
          <input
            type="text"
            {...register("activityName")}
            className={`form-control form-control-sm ${errors.activityName ? "is-invalid" : ""}`}
          />
          {errors.activityName && (
            <div className="text-danger">{errors.activityName.message}</div>
          )}
        </div>

        {/* Unit of Measurement */}
        <div className="col-md-6">
          <label  className="form-label">Measurement</label>
          <input
            type="text"
            {...register("unitOfMeasurement")}
            className={`form-control form-control-sm ${errors.unitOfMeasurement ? "is-invalid" : ""}`}
          />
          {errors.unitOfMeasurement && (
            <div className="text-danger">{errors.unitOfMeasurement.message}</div>
          )}
        </div>

        {/* Checklist */}
        <div className="col-md-12 text-start mt-1">
          <p className="py-1 my-0">{checkListItems.length > 0 ? "Check List" : "Add Check List"}</p>
          {checkListItems.length > 0 && (
             <table className="table mt-1  border-0">
             <thead className="py-0 my-0 table-border-top-0">
                 <tr className="py-1">
                   <th colSpan={2} className="py-1">
                     <small>Name</small>
                   </th>
                   <th colSpan={2} className="py-1 text-center">
                     <small>Is Mandatory</small>
                   </th>
                   <th className="text-center py-1">Action</th>
                 </tr>
               </thead>
               <tbody>
               {checkListItems.map((item, index) => (
                   <tr key={item.id} className="border-top-0">
                     <td colSpan={2} className=" border-0">
                       <input
                         className="d-none"
                         {...register(`checkList.${index}.id`)}
                       ></input>
                       <input
                         {...register(`checkList.${index}.description`)}
                         className="form-control form-control-sm"
                         placeholder={`Checklist item ${index + 1}`}
                         onChange={(e) =>
                           handleChecklistChange(index, e.target.value)
                         }
                       />
                       {errors.checkList?.[index]?.description && (
                         <small
                           style={{ fontSize: "10px" }}
                           className="danger-text"
                         >
                           {errors.checkList[index]?.description?.message}
                         </small>
                       )}
                     </td>
                     <td colSpan={2} className="text-center border-0">
                       <input
                         className="form-check-input"
                         type="checkbox"
                         {...register(`checkList.${index}.isMandatory`)}
                         defaultChecked={item.isMandatory}
                       />
                     </td>
                     <td className="text-center border-0">
                       <button
                         type="button"
                         onClick={() => removeChecklistItem(index)}
                       className="btn btn-xs btn-icon btn-text-secondary"
                       
                       >
                         <i className="bx bxs-minus-circle text-danger"data-bs-toggle="tooltip"
                title="Add Check"
                data-bs-original-title="Add check"  ></i>
                       </button>
                     </td>
                   </tr>
                 ))}
               </tbody>
             </table>
          )}
         

          <button
             type="button"
            className="btn btn-xs btn-primary mt-2"
            onClick={addChecklistItem}
          >
         <i class="bx bx-plus-circle" data-bs-toggle="tooltip"
                title="Add Check"
                data-bs-original-title="Add check" ></i>
          </button>
        </div>

        {/* Submit / Cancel */}
        <div className="col-12 text-center mt-3">
          <button type="submit" className="btn btn-sm btn-primary me-3">
            {isLoading ? "Please Wait" : "Submit"}
          </button>
          <button
            type="reset"
            className="btn btn-sm btn-label-secondary"
            onClick={onClose}
          >
            Cancel
          </button>
        </div>
      </div>
    </form>
  );
};

export default UpdateActivity;
