import React, { useEffect, useState } from "react";
import Modal from "react-bootstrap/Modal";
import "react-toastify/dist/ReactToastify.css";
import { toast, ToastContainer } from "react-toastify";
import {
  getRoleWisePermissionList,
  toRoleAssignPermission,
} from "@/services/public";

interface CheckboxItem {
  id: number;
  name: string;
  is_selected: number;
}

interface CheckboxGroup {
  [key: string]: CheckboxItem[];
}

interface CheckboxStatus {
  [key: string]: boolean;
}

interface Props {
  child: {
    rowData: {
      id: string;
      label: string;
    };
  };
  onHide: () => void;
  show: boolean;
}

function MyVerticallyCenteredModal({ child, onHide, show }: Props) {
  const [checkboxGroups, setCheckboxGroups] = useState<CheckboxGroup>({});
  const [checkboxStatus, setCheckboxStatus] = useState<CheckboxStatus>({});
  const [roleWisePermissionList, setRoleWisePermissionList] =
    useState<CheckboxGroup>({});

  // Define your dynamic checkbox groups
  const info = child?.rowData;

  const getAllRoleWisePermissionsList = (value: string) => {
    let payloadObj = {
      access_token: null,
      role_id: value,
    };
    getRoleWisePermissionList(payloadObj).then((response: any) => {
      if (response.status === "success") {
        setRoleWisePermissionList(response.data);
      }
    });
  };

  useEffect(() => {
    getAllRoleWisePermissionsList(info.id);
  }, [info]);

  useEffect(() => {
    const dynamicCheckboxGroups: CheckboxGroup = Object.keys(
      roleWisePermissionList,
    ).reduce((acc: any, key: any) => {
      acc[key] = roleWisePermissionList[key].map((item: CheckboxItem) => ({
        ...item,
        isChecked: item.is_selected === 1,
      }));
      return acc;
    }, {});
    setCheckboxGroups(dynamicCheckboxGroups);

    // Initialize checkboxStatus based on the current state of checkboxes
    const initialCheckboxStatus: CheckboxStatus = Object.keys(
      dynamicCheckboxGroups,
    ).reduce((acc: any, group: any) => {
      dynamicCheckboxGroups[group].forEach((checkboxItem: CheckboxItem) => {
        acc[checkboxItem.name] = checkboxItem.isChecked;
      });
      return acc;
    }, {});
    setCheckboxStatus(initialCheckboxStatus);
  }, [roleWisePermissionList]);

  const handleCancel = () => {
    onHide();
  };

  const handleChangePermission = (groupId: string, itemName: string) => {
    setCheckboxStatus((prevStatus) => ({
      ...prevStatus,
      [itemName]: !prevStatus[itemName],
    }));
  };

  const handleSubmit = () => {
    const checkedPermissions = Object.entries(checkboxStatus)
      .filter(([_, isChecked]) => isChecked)
      .map(([itemName]) => itemName);

    if (checkedPermissions.length > 0) {
      // Perform any additional actions with checkedPermissions here
      updateCheckedPermissions(checkedPermissions);
    } else {
      toast.error("At least one permission is required", {
        position: toast.POSITION.TOP_CENTER,
      });
    }
  };

  const updateCheckedPermissions = (checkedPermissions: any) => {
    let payloadObj = {
      role_id: info.id,
      permissions: checkedPermissions,
    };
    toRoleAssignPermission(payloadObj).then((response: any) => {
      if (response.status === "success") {
        onHide();
        toast.success("Permissions submitted successfully", {
          position: toast.POSITION.TOP_CENTER,
        });
      } else {
        onHide();
        toast.error("Something went wrong", {
          position: toast.POSITION.TOP_CENTER,
        });
      }
    });
  };

  const renderDynamicCheckboxes = () => {
    return Object.keys(checkboxGroups).map((group) => (
      <div key={group} className="mt-3">
        <h6 className="popup__h6">{`${group.charAt(0).toUpperCase()}${group.slice(1)} Page`}</h6>
        <ul className="popup__ul">
          {checkboxGroups[group].map((checkboxItem: CheckboxItem) => (
            <li key={checkboxItem.id}>
              <div className="d-flex mb-1">
                <input
                  style={{ transform: "scale(1.4)" }}
                  type="checkbox"
                  checked={checkboxStatus[checkboxItem.name]}
                  onChange={() =>
                    handleChangePermission(group, checkboxItem.name)
                  }
                />
                &nbsp;&nbsp;
                <span>{checkboxItem.name}</span>
              </div>
            </li>
          ))}
        </ul>
      </div>
    ));
  };

  return (
    <Modal
      show={show}
      onHide={onHide}
      size="lg"
      aria-labelledby="contained-modal-title-vcenter"
      centered
      backdrop="static"
      keyboard={false}
    >
      <div className="modal-header1">
        <h5 className="modal-title text-center">Customer Permissions</h5>
      </div>
      <div className="modal-body">
        <ToastContainer limit={1} />
        <h6 className="popup__customer_title text-center">{info?.label}</h6>
        {renderDynamicCheckboxes()}
        <hr />
        <div className="d-flex justify-content-center align-items-center gap-3">
          <button onClick={handleSubmit} className="btn btn-submit">
            Submit
          </button>
          <div onClick={handleCancel} className="btn btn-cancel">
            Cancel
          </div>
        </div>
      </div>
    </Modal>
  );
}

export default function CustomerPermissionsUpdate(props: any) {
  const [modalShow, setModalShow] = React.useState(false);

  return (
    <>
      <button className="btn btn-warning" onClick={() => setModalShow(true)}>
        <i className="bi bi-gear"></i>&nbsp;Manage Permissions
      </button>
      <MyVerticallyCenteredModal
        show={modalShow}
        onHide={() => setModalShow(false)}
        child={props?.userdata}
      />
    </>
  );
}
