import React, { useEffect, useState } from "react";
import useMaster from "../../hooks/masterHook/useMaster";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { RolesRepository } from "../../repositories/MastersRepository";
import { useEmployeeRoles } from "../../hooks/useEmployees";
import { useDispatch } from "react-redux";
import { changeMaster } from "../../slices/localVariablesSlice";
import showToast from "../../services/toastService";

const formSchema = z.object({
  selectedRole: z.record(z.boolean()).refine(
    (data) => {
      return Object.values(data).some((value) => value === true);
    },
    {
      message: "At least one checkbox must be selected.",
    }
  ),
});

const ManageRole = ({ employeeId, onClosed }) => {
  const disptach = useDispatch();
  disptach(changeMaster("Application Role"));
  const [isLoading, setIsLoading] = useState(false);
  const { employeeRoles, loading } = useEmployeeRoles(employeeId);
  const { data, loading: roleLoading } = useMaster();

  const buildDefaultRoles = () => {
    const defaults = {};
    data.forEach((role) => {
      const isRoleEnabled = employeeRoles?.data?.some(
        (empRole) => empRole.roleId === role.id
      );
      defaults[role.id] = isRoleEnabled;
    });

    return defaults;
  };

  const [initialRoles, setInitialRoles] = useState({});

  useEffect(() => {
    if (employeeRoles && data) {
      const updatedRoles = buildDefaultRoles();
      setInitialRoles(updatedRoles);
    }
  }, [employeeRoles, data]);

  const {
    register,
    handleSubmit,
    formState: { errors },
    reset,
  } = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: {
      selectedRole: initialRoles,
    },
  });

  useEffect(() => {
    if (Object.keys(initialRoles).length > 0) {
      reset({
        selectedRole: initialRoles,
      });
    }
  }, [initialRoles, reset]);

  const onSubmit = (formdata) => {
    setIsLoading(true);
    const result = [];
    for (const [roleId, isEnabled] of Object.entries(formdata.selectedRole)) {
      if (isEnabled) {
        result.push({
          employeeId: employeeId,
          isEnabled: true,
          roleId: roleId,
        });
      }
    }
    RolesRepository.createEmployeeRoles(result)
      .then((resp) => {
        showToast("Role assigned successfully", "success");
        setIsLoading(false);
        onClosed();
      })
      .catch((err) => {
        console.log(err);
        setIsLoading(false);

        showToast(err.message, "error");
      });
    setIsLoading(false);
  };
  console.log(data)

  return (
    <div
      className={`modal fade `}
      id="managerole-modal"
      tabIndex="-1"
      aria-hidden="true"
    >
      <div className="modal-dialog  modal-simple modal-md d-flex align-items-center justify-content-center">
        <div className="modal-content ">
          <div className="modal-body">
            <button
              type="button"
              className="btn-close"
              data-bs-dismiss="modal"
              aria-label="Close"
            ></button>
            <form onSubmit={handleSubmit(onSubmit)}>
              <div className="text-start my-0">
                <p className="lead">Select Roles</p>
              </div>

              <div
                className="d-flex flex-wrap justify-content-between align-items-center pb-5 "
                style={{ maxHeight: "70vh", overflowY: "scroll" }}
              >
                {(loading || roleLoading) && <p>Loading...</p>}
                {data &&
                  data.map((item) => (
                    <div className="col-md-6 col-lg-4 mb-4" key={item.id}>
                      <div className="form-check ms-2 text-start">
                        <input
                          className="form-check-input"
                          type="checkbox"
                          id={item.id}
                          {...register(`selectedRole.${item.id}`, {
                            value: initialRoles[item.id] || false,
                          })}
                        />
                        <label
                          className="form-check-label text-bold"
                          htmlFor={item.id}
                        >
                          <small>{item.role || "--"}</small>
                        </label>
                      </div>
                    </div>
                  ))}
              </div>
              {errors.selected && (
                <div className="text-center">{errors.selected.message}</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="reset"
                  className="btn btn-sm btn-label-secondary"
                  data-bs-dismiss="modal"
                  aria-label="Close"
                >
                  Cancel
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ManageRole;
