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

import { useFeatures } from "../../hooks/useMasterRole";
import { MasterRespository } from "../../repositories/MastersRepository";
import { cacheData, getCachedData } from "../../slices/apiDataManager";
import showToast from "../../services/toastService";
import { useUpdateApplicationRole } from "../../hooks/masterHook/useMaster";
import Label from "../common/Label";

const updateSchema = 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" }),
  permissions: z.record(z.boolean()).refine((permission) => Object.values(permission).includes(true), {
    message: "At least one permission must be selected",
  }),
});

const EditMaster = ({ master, onClose }) => {
  const maxDescriptionLength = 255;
  const popoverRefs = useRef([]);
  const { masterFeatures } = useFeatures();
  const { mutate: updateApplicationRole, isPending: isLoading } = useUpdateApplicationRole(() => onClose?.());

  const buildDefaultPermissions = () => {
    const defaults = {};
    masterFeatures.forEach((feature) => {
      feature.featurePermissions.forEach((perm) => {
        const existing = master?.item?.featurePermission?.find(p => p.id === perm.id);
        defaults[perm.id] = existing?.isEnabled || false;
      });
    });
    return defaults;
  };

  const initialPermissions = buildDefaultPermissions();

  const {
    register,
    handleSubmit,
    formState: { errors, dirtyFields },
    setError,
    reset,
  } = useForm({
    resolver: zodResolver(updateSchema),
    defaultValues: {
      role: master?.item?.role || "",
      description: master?.item?.description || "",
      permissions: initialPermissions,
    },
  });

  const [descriptionLength, setDescriptionLength] = useState(master?.item?.description?.length || 0);

  const onSubmit = (data) => {
    const existingIds = new Set(master?.item?.featurePermission?.map(p => p.id));

    const updatedPermissions = Object.entries(data.permissions)
      .filter(([id, value]) => {
        return existingIds.has(id) || value === true || (dirtyFields.permissions?.[id]);
      })
      .map(([id, value]) => ({ id, isEnabled: value }));

    if (updatedPermissions.length === 0) {
      setError("permissions", {
        type: "manual",
        message: "At least one permission must be selected.",
      });
      return;
    }

    const payload = {
      id: master?.item?.id,
      role: data.role,
      description: data.description,
      featuresPermission: updatedPermissions,
    };

    updateApplicationRole({ id: payload.id, payload });
  };
  // const onSubmit = (data) => {
  //     setIsLoading(true)
  //     const existingIds = new Set(
  //       master?.item?.featurePermission?.map((p) => p.id)
  //     );


  //     const updatedPermissions = Object.entries(data.permissions)
  //       .filter(([id, value]) => {
  //         if (existingIds.has(id)) return true;

  //         return (
  //           value === true ||
  //           (dirtyFields.permissions && dirtyFields.permissions[id])
  //         );
  //       })
  //       .map(([id, value]) => ({ id, isEnabled: value }));


  //     if (updatedPermissions.length === 0) {
  //       setError("permissions", {
  //         type: "manual",
  //         message: "At least one permission must be selected.",
  //       });
  //       return;
  //     }

  //     const updatedRole = {
  //       id: master?.item?.id,
  //       role: data.role,
  //       description: data.description,
  //       featuresPermission: updatedPermissions,
  //     };
  //     MasterRespository.updateRoles(master?.item?.id, updatedRole).then((resp) => {
  //       setIsLoading(false)


  //       const cachedData = getCachedData("Application Role");

  //       if (cachedData) {

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

  //         cacheData("Application Role", updatedData);
  //       }
  //       showToast("Application Role Updated successfully.", "success");
  //       setIsLoading(false)
  //       onClose()
  //     }).catch((Err) => {
  //       showToast(Err.message, "error");
  //       setIsLoading(false)
  //     })

  //   };
  useEffect(() => {
    reset({
      role: master?.item?.role || "",
      description: master?.item?.description || "",
      permissions: buildDefaultPermissions(),
    });
    setDescriptionLength(master?.item?.description?.length || 0);
  }, [master, reset]);

  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 text-start">
        <Label className="form-label" required>Role</Label>
        <input type="text"
          {...register("role")}
          className={`form-control ${errors.role ? 'is-invalid' : ''}`}
        />
        {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="col-12 text-start">
        {/* Scrollable Container with Border */}
        <div
          className="border rounded p-3"
          style={{
            maxHeight: "350px",
            overflowY: "auto",
            overflowX: "hidden", // Prevent horizontal scrollbar
            paddingRight: "10px",
          }}
        >
          {masterFeatures.map((feature, featureIndex) => (
            <div key={feature.id} className="mb-3">
              {/* Feature Group Title */}
              <div className="fw-semibold mb-2">{feature.name}</div>

              {/* Permissions Grid */}
              <div className="row">
                {feature.featurePermissions.map((perm, permIndex) => {
                  const refIndex = featureIndex * 10 + permIndex;
                  return (
                    <div
                      key={perm.id}
                      className="col-12 col-sm-6 col-md-4 mb-3 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}
                          {...register(`permissions.${perm.id}`, {
                            value: initialPermissions[perm.id] || false,
                          })}
                        />
                        {perm.name}
                      </label>

                      {/* Info Icon */}
                      <div style={{ display: "flex", alignItems: "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>

              <hr className="my-2" />
            </div>
          ))}
        </div>

        {/* Error Display */}
        {errors.permissions && (
          <p className="text-danger">{errors.permissions.message}</p>
        )}
      </div>




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

      </div>

    </form>

  );
}


export default EditMaster;
