import React, { useState, useEffect, useCallback } from "react";
import { useFieldArray, useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";

import {
  useCreateActivity,
  useUpdateActivity,
} from "../../../hooks/masterHook/useMaster";
import Label from "../../common/Label";

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

const ManageActivity = ({ activity = null, whichGroup = null, close }) => {
  const maxDescriptionLength = 255;
  const { mutate: createActivity, isPending: isLoading } = useCreateActivity(
    () => close?.()
  );
  const { mutate: UpdateActivity, isPending: isUpdating } = useUpdateActivity(
    () => close?.()
  );

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

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

  const addChecklistItem = useCallback(() => {
    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 });
  }, [checkListItems, getValues, append, setError, clearErrors]);

  const removeChecklistItem = useCallback(
    (index) => {
      remove(index);
    },
    [remove]
  );

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

  const onSubmit = (formData) => {
    let payload = {
      ...formData,
      activityGroupId: whichGroup,
    };
    if (activity) {
      UpdateActivity({ id: activity.id, payload: payload });
    } else {
      createActivity(payload);
    }
  };

  useEffect(() => {
    if (activity) {
      reset({
        activityName: activity.activityName || "",
        unitOfMeasurement: activity.unitOfMeasurement || "",
        checkList: activity.checkLists?.map((check) => ({
          id: check.id || null, // Use the ID provided in the checklist
          description: check.description || "",
          isMandatory: check.isMandatory || false,
        })) || [{ description: "", isMandatory: false }], // Default to an empty checklist item
      });
    }
  }, [activity, reset]);
  const handleClose = useCallback(() => {
    reset();
    close();
  }, [reset, close]);

  useEffect(() => {
    const tooltipTriggerList = Array.from(
      document.querySelectorAll('[data-bs-toggle="tooltip"]')
    );
    tooltipTriggerList.forEach((el) => new bootstrap.Tooltip(el));
  }, []);
  let isPending = isLoading || isUpdating;
  return (
    <form onSubmit={handleSubmit(onSubmit)} className="px-7">
      {/* <h6>Create Activity</h6> */}
      <div className="row border border-1 border-secondary rounded-3 mt-2">
        <div className="col-6 text-start mt-3">
          <Label className="form-label" required>
            Activity
          </Label>
          <input
            type="text"
            {...register("activityName")}
            className={`form-control form-control-sm ${
              errors.activityName ? "is-invalid" : ""
            }`}
          />
          {errors.activityName && (
            <p className="danger-text">{errors.activityName.message}</p>
          )}
        </div>

        <div className="col-6 text-start mt-3">
          <Label className="form-label" required>
            Measurement
          </Label>
          <input
            type="text"
            {...register("unitOfMeasurement")}
            className={`form-control form-control-sm ${
              errors.unitOfMeasurement ? "is-invalid" : ""
            }`}
          />
          {errors.unitOfMeasurement && (
            <p className="danger-text">{errors.unitOfMeasurement.message}</p>
          )}
        </div>

        <div className="col-md-12 text-start mt-3">
          <label className="py-1 form-label my-0">
            Add Check List <i
              className="bx bx-plus-circle text-primary cursor-pointer"
              data-bs-toggle="tooltip"
              title="Add Check"
              data-bs-original-title="Add check"
               onClick={addChecklistItem}
            ></i>
          </label>
          {checkListItems.length > 0 ? (
            <table className="table mt-1  border-none">
              <thead className="py-0 my-0  border-none  ">
                <tr className="py-1 border-secondary ">
                  <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 className="table-border-bottom-0 border-secondary ">
                {checkListItems.map((item, index) => (
                  <tr key={index}>
                    <td colSpan={2} className="border-none" >
                      <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-none">
                      <input
                        className="form-check-input"
                        type="checkbox"
                        {...register(`checkList.${index}.isMandatory`)}
                        defaultChecked={item.isMandatory}
                      />
                    </td>
                    <td className="text-center border-none">
                      <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="Remove Check"
                          data-bs-original-title="Remove check"
                        ></i>
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          ):(<div className="d-flex justify-content-center my-0"><p className="text-secondary m-0">Not Yet Added</p> </div>)}
        
        </div>

        <div className="col-12 text-end mt-3 mb-4">
          <button
            type="reset"
            className="btn btn-sm btn-label-secondary me-3"
            onClick={handleClose}
            disabled={isPending}
          >
            Cancel
          </button>
          <button type="submit" className="btn btn-sm btn-primary">
            {isPending ? "Please Wait" : activity ? "Update" : "Submit"}
          </button>
        </div>
      </div>
    </form>
  );
};

export default ManageActivity;
