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()),
});

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?.some(
        (empRole) => empRole.roleId === role.id
      );
      defaults[role.id] = isRoleEnabled;
    });

    return defaults;
  };

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

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

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

  useEffect(() => {
    if (!data) return;
  
    const updatedRoles = {};
    data.forEach((role) => {
      const isRoleEnabled = employeeRoles?.some(
        (empRole) => empRole.roleId === role.id && empRole.isEnabled
      );
      updatedRoles[role.id] = isRoleEnabled || false;
    });
  
    setInitialRoles(updatedRoles);
  
    reset({
      selectedRole: updatedRoles,
    });
  }, [employeeRoles, data, reset]);
  
  // const onSubmit = (formdata) => {
  //   setIsLoading(true);
  //   const result = [];
  
  //   const selectedRoles = formdata.selectedRole;
  
  //   for (const [roleId, isChecked] of Object.entries(selectedRoles)) {
  //     const existingRole = employeeRoles?.find((role) => role.roleId === roleId);
  //     const wasChecked = !!existingRole?.isEnabled;
  
  //     // Only push if the checked status has changed
  //     if (isChecked !== wasChecked) {
  //       result.push({
  //         id: existingRole?.id || "00000000-0000-0000-0000-000000000000",
  //         employeeId,
  //         roleId,
  //         isEnabled: isChecked,
  //       });
  //     }
  //   }
  
  //   if (result.length === 0) {
  //     showToast("No changes made", "info");
  //     setIsLoading(false);
  //     return;
  //   }
  
  //   console.log(result);
  
  //   RolesRepository.createEmployeeRoles(result)
  //     .then(() => {
  //       showToast("Roles updated successfully", "success");
  //       setIsLoading(false);
  //       reset();
  //       onClosed();
  //     })
  //     .catch((err) => {
  //       console.error(err);
  //       showToast(err.message, "error");
  //       setIsLoading(false);
  //     });
  // };
  
  const onSubmit = (formdata) => {
    setIsLoading(true);
    const result = [];
    const selectedRoles = formdata.selectedRole;
  
    for (const [roleId, isChecked] of Object.entries(selectedRoles)) {
      const existingRole = employeeRoles?.find((role) => role.roleId === roleId);
      const wasChecked = !!existingRole?.isEnabled;
  
      // Only push if the checked status has changed
      if (isChecked !== wasChecked) {
        result.push({
          id: existingRole?.id || "00000000-0000-0000-0000-000000000000",
          employeeId,
          roleId,
          isEnabled: isChecked,
        });
      }
    }
  
    if (result.length === 0) {
      showToast("No changes made", "info");
      setIsLoading(false);
      return;
    }
  
    console.log(result);
  
    RolesRepository.createEmployeeRoles(result)
      .then(() => {
        showToast("Roles updated successfully", "success");
        setIsLoading(false);
        reset();
        onClosed();
      })
      .catch((err) => {
        console.error(err);
        showToast(err.message, "error");
        setIsLoading(false);
      });
  };
  
  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" }}
              >
                {roleLoading && <p>Loading...</p>}
                {loading && <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}`)}

                        />
                        <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;