import { useState } from "react";
import {
  useActivitiesByGroups,
  useGroups,
} from "../../../hooks/masterHook/useMaster";
import ManageGroup from "./ManageGroup";
import ManageActivity from "./ManageActivity";
import { useMasterContext } from "../../../pages/master/MasterPage";
const ServiceGroups = ({ service }) => {
  const [openService, setOpenService] = useState(true);
  const [activeGroupId, setActiveGroupId] = useState(null); // track selected group
  const {setDeleletingServiceItem}  =useMasterContext()
  const [isManageGroup, setManageGroup] = useState({
    isOpen: false,
    group: null,
    serviceId: null,
  });
  const [isManageActivity, setManageActivity] = useState({
    isOpen: false,
    activity: null, // activity is either a single activity for editing or null for creating new activity
    groupId: null, // groupId for managing activities in specific groups
  });

  // Fetch groups and activities data
  const { data: groups, isLoading } = useGroups(service?.id); // Fetch groups for the service
  const { data: activities, isLoading: actLoading } =
    useActivitiesByGroups(activeGroupId); // Fetch activities based on activeGroupId

  if (isLoading) return <div>Loading groups...</div>; // Show loading state while groups are being fetched

  // Handle toggling of group to view activities
  const toggleGroup = (groupId) => {
    setActiveGroupId((prev) => (prev === groupId ? null : groupId)); // If the same group is clicked again, close it
  };

  return (

    <div className="w-100 my-2">
      
      <div className="accordion" id="accordionExample">
        <div className="accordion-item active shadow-none">
          {/* Service Header */}
          <div className="d-flex justify-content-between text-start align-items-center accordion-header py-1">
            <p className="m-0 fw-bold fs-6">{service.name}</p>
            <button
              className="btn btn-sm btn-primary"
              onClick={() =>
                setManageGroup({
                  isOpen: true,
                  group: null, // No group selected, for creating a new group
                  serviceId: service.id,
                })
              }
            >
              <i className="bx bx-plus-circle me-2"></i>Add Group
            </button>
          </div>

          {/* Groups Section */}
          <div
            id="accordionOne"
            className={`accordion-collapse collapse ${
              openService ? "show" : ""
            }`}
            aria-labelledby="headingOne"
            data-bs-parent="#accordionExample"
          >
            {/* Show ManageGroup for creating a new group */}
            {isManageGroup.isOpen && isManageGroup.group === null ? (
              <ManageGroup
                group={null} // Indicating new group creation
                whichService={isManageGroup.serviceId}
                close={() =>
                  setManageGroup({
                    isOpen: false,
                    group: null,
                    serviceId: service.id,
                  })
                }
              />
            ) : (
              <div className="accordion-body text-start m-0 p-0">
                <div className="dropdown-divider border"></div>
              {!isLoading && groups?.data?.length === 0 && (<div className="text-center py-2"><p>No Group available.</p></div>)}
                {groups && groups?.data?.map((group) => {
                  const isOpen = activeGroupId === group.id;

                  return (
                    <div
                      className="accordion-item shadow-none m-0 py-2 px-2"
                      key={group.id}
                    >
                      <div className="d-flex justify-content-between text-start accordion-header">
                        {/* Show group toggle button only if ManageGroup is not open */}
                        <div className="d-flex gap-1 align-items-center">
                          {!isManageGroup.isOpen && (
                            <span
                              onClick={() => toggleGroup(group.id)}
                              className="text-end cursor-pointer"
                              data-bs-toggle="collapse"
                              data-bs-target={`#accordionGroup${group.id}`}
                              aria-expanded={isOpen}
                              aria-controls={`accordionGroup${group.id}`}
                            >
                              <i
                                className={`bx bx-lg ${
                                  isOpen ? "bx-chevron-up" : "bx-chevron-down"
                                }`}
                              />
                            </span>
                          )}
                          <p className="m-0 ">{group.name}</p>
                        </div>
                        <div className="d-flex flex-row gap-3">
                          <div className="d-flex flex-row gap-2">
                            {/* Create New Activity */}
                            <i
                              className="bx bx-plus-circle text-primary cursor-pointer"
                              onClick={() => {
                                setManageActivity({
                                  isOpen: true,
                                  activity: null, // Indicating new activity creation
                                  groupId: group.id, // Set the groupId for the new activity
                                });
                              }}
                            />
                            {/* Edit Group */}
                            <i
                              className="bx bx-edit text-secondary cursor-pointer"
                              onClick={() =>
                                setManageGroup({
                                  isOpen: true,
                                  group: group, // Group selected for Editing
                                  serviceId: service.id,
                                })
                              }
                            />
                            {/* Delete Group */}
                            <i className="bx bx-trash text-danger cursor-pointer" onClick={()=>setDeleletingServiceItem({isOpen:true,ItemId:group.id,whichItem:"group"})} />
                          </div>
                        </div>
                      </div>

                      {/* Only show ManageGroup for the specific group if it's open */}
                      {isManageGroup.isOpen &&
                      isManageGroup.group?.id === group.id ? (
                        <ManageGroup
                          group={group} // For editing
                          whichService={isManageGroup.serviceId}
                          close={() =>
                            setManageGroup({
                              isOpen: false,
                              group: null,
                              serviceId: null,
                            })
                          }
                        />
                      ) : isManageActivity.isOpen &&
                        isManageActivity.groupId === group.id ? (
                        <ManageActivity
                          activity={isManageActivity.activity} // Pass the activity object for editing
                          whichGroup={group.id} // Set groupId for creating/editing activity
                          close={() => {
                            setManageActivity({
                              isOpen: false,
                              activity: null,
                              groupId: null,
                            });
                          }}
                        />
                      ) : (
                        <div
                          id={`accordionGroup${group.id}`}
                          className={`accordion-collapse collapse ${
                            isOpen ? "show" : ""
                          }`}
                          aria-labelledby={group.id}
                          data-bs-parent="#accordionOne"
                        >
                          <div className="accordion-body ">
                            {isOpen && actLoading && (
                              <p className="text-center m-0">
                                Loading activities...
                              </p>
                            )}

                            {isOpen && activities?.data?.length > 0 ? (
                              <div className="row border-top-2">
                                {/* Header Row */}
                                <div className="col-12 d-flex justify-content-between py-2 border-bottom px-4">
                                  <span className="fw-semibold text-uppercase">
                                    Activity Name
                                  </span>
                                  <span className="fw-semibold text-uppercase">
                                    Unit of Measurement
                                  </span>
                                  <span className="fw-semibold text-uppercase">
                                    Action
                                  </span>
                                </div>

                                {/* Map through activities */}
                                {activities.data.map((activity) => (
                                  <div
                                    className="col-12 d-flex justify-content-between py-2 "
                                    key={activity.id}
                                  >
                                    {/* Activity Name Column */}
                                    <div className="col d-flex justify-content-start">
                                      <span>{activity.activityName}</span>
                                    </div>

                                    {/* Unit of Measurement Column */}
                                    <div className="col d-flex justify-content-start">
                                      <span>{activity.unitOfMeasurement}</span>
                                    </div>

                                    {/* Action Column */}
                                    <div className="col-auto d-flex gap-3 justify-content-end">
                                      {/* Edit Activity */}
                                      <i
                                        className="bx bx-sm bx-edit text-secondary cursor-pointer"
                                        onClick={() => {
                                          setManageActivity({
                                            isOpen: true,
                                            activity: activity, // Pass the specific activity for editing
                                            groupId: group.id, // Set groupId for the specific activity
                                          });
                                        }}
                                      />
                                      {/* Delete Activity */}
                                      <i
                                        className="bx bx-sm bx-trash text-danger cursor-pointer"
                                        onClick={() => setDeleletingServiceItem({isOpen:true,ItemId:activity.id,whichItem:"activity"})}
                                      />
                                    </div>
                                  </div>
                                ))}
                              </div>
                            ) : (
                              isOpen && (
                                <p className="text-center m-0">
                                  No activities found
                                </p>
                              )
                            )}
                          </div>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default ServiceGroups;
