import React, { useEffect, useState, useRef } from "react";
import { useFeatures } from "../../hooks/useMasterRole";

import { useForm } 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 { useCreateApplicationRole } from "../../hooks/masterHook/useMaster";
import Label from "../common/Label";

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" }),

  selectedPermissions: z
    .array(z.string())
    .min(1, { message: "Please select at least one permission" }),
});

const CreateRole = ({ modalType, onClose }) => {
  const maxDescriptionLength = 255;
  const [descriptionLength, setDescriptionLength] = useState(0);

  const popoverRefs = useRef([]);
  const { masterFeatures } = useFeatures();
  const { mutate: submitNewApplicationRole, isPending: isLoading } =
    useCreateApplicationRole(() => {
      onClose?.();
    });

  const {
    register,
    handleSubmit,
    formState: { errors },
    reset,
  } = useForm({
    resolver: zodResolver(schema),
    defaultValues: {
      role: "",
      description: "",
      selectedPermissions: [],
    },
  });

  const onSubmit = (values) => {
    const payload = {
      role: values.role,
      description: values.description,
      featuresPermission: values.selectedPermissions.map((id) => ({
        id,
        isEnabled: true,
      })),
    };

    submitNewApplicationRole(payload);
  };

  // const onSubmit = (values) => {
  //   setIsLoading(true)
  //   const result = {

  //     role: values.role,
  //     description: values.description,
  //     featuresPermission: values.selectedPermissions.map((id) => ({
  //       id,
  //       isEnabled: true,
  //     })),
  //   };

  //   MasterRespository.createRole(result).then((resp) => {
  //     setIsLoading(false)
  //     const cachedData = getCachedData("Application Role");
  //     const updatedData = [...cachedData, resp.data];
  //     cacheData("Application Role", updatedData);
  //     showToast("Application Role Added successfully.", "success");
  //     onClose()
  //   }).catch((err) => {

  //     showToast(err?.response?.data?.message, "error");
  //     setIsLoading(false)
  //     onClose()
  //   })

  // };
  useEffect(() => {
    setDescriptionLength(0);
  }, []);

  useEffect(() => {
    popoverRefs.current.forEach((el) => {
      if (el) {
        new bootstrap.Popover(el, {
          trigger: "focus",
          placement: "right",
          html: true,
          content: el.getAttribute("data-bs-content"),
        });
      }
    });
  }, [masterFeatures]);

  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">Create Application Role</label>

      </div> */}
      <div className="col-12 col-md-12 text-start">
        <Label className="form-label" required>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 text-start">
        <Label className="form-label" htmlFor="description" required>
          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="border rounded px-3"
        style={{
          maxHeight: "350px",
          overflowY: "auto",
          overflowX: "hidden", // Prevent bottom scrollbar
        }}
      >
        {masterFeatures.map((feature, featureIndex) => (
          <React.Fragment key={feature.id}>
            <div className="row my-1">
              {/* Feature Title */}
              <div className="col-12 text-start fw-semibold mb-2">
                {feature.name}
              </div>

              {/* Permissions Grid */}
              <div className="col-12">
                <div className="row">
                  {feature.featurePermissions.map((perm, permIndex) => {
                    const refIndex = featureIndex * 100 + permIndex;
                    return (
                      <div
                        className="col-12 col-sm-6 col-md-4 mb-3"
                        key={perm.id}
                      >
                        <div className="d-flex align-items-start">
                          <label
                            className="form-check-label d-flex align-items-center"
                            htmlFor={perm.id}
                          >
                            <input
                              type="checkbox"
                              className="form-check-input me-2"
                              id={perm.id}
                              value={perm.id}
                              {...register("selectedPermissions")}
                            />
                            {perm.name}
                          </label>

                          {/* Info icon */}
                          <div className="ms-1 d-flex align-items-center">
                            <div
                              ref={(el) => (popoverRefs.current[refIndex] = el)}
                              tabIndex="0"
                              className="d-flex align-items-center justify-content-center"
                              data-bs-toggle="popover"
                              data-bs-trigger="focus"
                              data-bs-placement="right"
                              data-bs-html="true"
                              data-bs-content={`<div class="border border-secondary rounded custom-popover p-2 px-3">${perm.description}</div>`}
                            >
                              &nbsp;
                              <svg
                                xmlns="http://www.w3.org/2000/svg"
                                width="13"
                                height="13"
                                fill="currentColor"
                                className="bi bi-info-circle"
                                viewBox="0 0 16 16"
                              >
                                <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z" />
                                <path d="m8.93 6.588-2.29.287-.082.38.45.083c.294.07.352.176.288.469l-.738 3.468c-.194.897.105 1.319.547 1.11l1.91-2.011c.241-.256.384-.592.287-.984-.172-.439-.58-.827-1.13-.967a.664.664 0 0 1-.58-.309l-.15-.241-.002-.002zM8 4c-.535 0-.943.372-.943.836 0 .464.408.836.943.836.535 0 .943-.372.943-.836 0-.464-.408-.836-.943-.836z" />
                              </svg>
                            </div>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            </div>

            <hr className="my-2" />
          </React.Fragment>
        ))}

        {errors.selectedPermissions && (
          <p className="text-danger">{errors.selectedPermissions.message}</p>
        )}
        {!masterFeatures && <p>Loading...</p>}
      </div>

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

export default CreateRole;
