import React, { useState, useEffect, useRef, useMemo } from "react";
import {
  FwTabs,
  FwTab,
  FwTabPanel,
  FwSpinner,
  ToastController,
  FwToast,
  FwPagination,
  FwModalTitle,
  FwModalContent,
  FwToggle,
  FwButton,
  FwIcon,
  FwListOptions,
  FwPopover,
  FwModal,
} from "@freshworks/crayons/react";
import {
  getTicketCreationRules,
  getTicketUpdationRules,
  getHourlyRules,
  getAgents,
  pagination,
} from "../common";

const cleanText = (text) =>
  String(text || "")
    .toLowerCase()
    .replace(/<img[^>]*>/gi, "")
    .replace(/&nbsp;/gi, " ")
    .replace(/<[^>]*>/g, "")
    .replace(/[,\.]/g, "")
    .replace(/([a-zA-Z])(\d)/g, "$1 $2")
    .replace(/(\d)([a-zA-Z])/g, "$1 $2")
    .replace(/\s+/g, " ")
    .trim()
    .replace(/\bcomma\b\s*\bfull\s*stop\b/g, "comma fullstop");

const normalizeConditionParts = (rawConditions) => {
  let parts = [];

  if (typeof rawConditions === "string") {
    parts = rawConditions.split(",");
  } else if (Array.isArray(rawConditions)) {
    parts = rawConditions;
  } else if (typeof rawConditions === "object" && rawConditions !== null) {
    parts = Object.values(rawConditions).flat();
  } else {
    parts = [];
  }

  const set1 = [];
  const set2 = [];
  let currentSet = null;

  for (let part of parts) {
    const cleaned = cleanText(part);
    if (cleaned === "condition set 1") {
      currentSet = set1;
      continue;
    }
    if (cleaned === "condition set 2") {
      currentSet = set2;
      continue;
    }
    if (!currentSet) currentSet = set1;

    currentSet.push(cleaned);
  }

  set1.sort();
  set2.sort();

  return { set1, set2 };
};

const normalizeActions = (actions) => {
  if (Array.isArray(actions)) {
    return actions
      .map((action) => {
        if (typeof action === "string") {
          return cleanText(action);
        } else if (typeof action === "object" && action !== null) {
          return Object.values(action)
            .map((v) => cleanText(v))
            .join(" ");
        } else {
          return "";
        }
      })
      .sort()
      .join(",");
  } else if (typeof actions === "string") {
    return actions
      .split(",")
      .map((a) => cleanText(a))
      .sort()
      .join(",");
  }
  return "";
};

const getRuleSignatureNormalized = (rule) => {
  const rawConditions = rule.summary?.conditions || rule.conditions || "";
  const rawActions = rule.summary?.actions || rule.actions || "";
  const operator = rule.operator || "";

  const { set1, set2 } = normalizeConditionParts(rawConditions);
  const normalizedActions = normalizeActions(rawActions);
  const normalizedOperator = cleanText(operator);

  const key1 = JSON.stringify({
    set1,
    set2,
    actions: normalizedActions,
    operator: normalizedOperator,
  });
  const key2 = JSON.stringify({
    set1: set2,
    set2: set1,
    actions: normalizedActions,
    operator: normalizedOperator,
  });

  return key1 < key2 ? key1 : key2;
};

const groupDuplicates = (rules) => {
  const groups = {};

  rules
    .filter((rule) => rule.active === true || rule.active === "true")
    .forEach((rule) => {
      const signature = getRuleSignatureNormalized(rule);
      if (!groups[signature]) groups[signature] = [];
      groups[signature].push(rule);
    });

  return Object.values(groups);
};

const Filterrecords = async (automationTypeId, newRulePloadDB3) => {
  let allRecords = [];
  let nextMarker = null;

  try {
    do {
      const queryObj = { query: { automation_type_id: automationTypeId } };
      if (nextMarker) queryObj.next = { marker: nextMarker };

      const response = await newRulePloadDB3.getAll(queryObj);
      if (!response.records || !Array.isArray(response.records)) break;

      const filtered = response.records.map((record) => ({
        ...record.data,
        display_id: record.display_id,
        rule_id: record.data.rule_id,
        automation_type_id: record.data.automation_type_id,
        id: record.data.rule_id || record.data.id,
      }));

      allRecords = allRecords.concat(filtered);

      nextMarker = response.links?.next?.marker || null;
    } while (nextMarker);

    allRecords.sort((a, b) => {
      const posA = typeof a.position === "number" ? a.position : Number.MAX_SAFE_INTEGER;
      const posB = typeof b.position === "number" ? b.position : Number.MAX_SAFE_INTEGER;
      return posA - posB;
    });

    console.log(`✅ Filtered Records for Type ${automationTypeId}:`, allRecords);
    return allRecords;
  } catch (error) {
    console.error("❌ Error fetching filtered records:", error);
    return [];
  }
};

const calculateLastModified = (updated_at) => {
  const updatedDate = new Date(updated_at);
  const currentDate = new Date();
  const diffInMilliseconds = currentDate - updatedDate;
  const seconds = Math.floor(diffInMilliseconds / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);
  const months = Math.floor(days / 30);
  const years = Math.floor(days / 365);

  if (years > 0) return years === 1 ? "a year ago" : `${years} years ago`;
  if (months > 0) return months === 1 ? "a month ago" : `${months} months ago`;
  if (days > 0) return `${days} day${days > 1 ? "s" : ""} ago`;
  if (hours > 0) return `${hours} hour${hours > 1 ? "s" : ""} ago`;
  if (minutes > 0) return `${minutes} minute${minutes > 1 ? "s" : ""} ago`;
  return "Just now";
};

const AutomationCard = ({
  rule = {},
  index,
  isFirstInGroup = false,
  onDelete,
  agent,
  activeTab,
  onSelect,
}) => {
  const {
    id,
    name = "Default Rule Name",
    summary = "",
    description = "",
    updated_at = "N/A",
    last_updated_by = "Unknown",
    affected_tickets_count = "--",
    active = false,
    position,
    automation_type_id,
  } = rule;

  const [menuOpen, setMenuOpen] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const modalRef = useRef(null);
  const menuContainerRef = useRef(null);

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (menuContainerRef.current && !menuContainerRef.current.contains(event.target)) {
        setMenuOpen(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  useEffect(() => {
    if (showDeleteModal && modalRef.current) {
      modalRef.current.open();
    }
  }, [showDeleteModal]);

  const openModal = () => setShowDeleteModal(true);
  const closeModal = () => {
    setShowDeleteModal(false);
    if (modalRef.current) modalRef.current.close();
  };

  const handleConfirmDelete = () => {
    closeModal();
    if (onDelete) onDelete(rule);
  };

  const handleClick = () => {
    if (onSelect) {
      onSelect(rule);
    }
  };

  const renderAgentName = () => {
    if (rule.agentName) {
      return rule.agentName;
    }
    if (!agent || !Array.isArray(agent)) {
      return last_updated_by || "Unknown";
    } else {
      const foundAgent = agent.find((e) => e.value === last_updated_by);
      return foundAgent ? foundAgent.text : last_updated_by || "Unknown";
    }
  };

  function extractText(htmlString) {
    if (!htmlString || typeof htmlString !== "string") return "";
    let text = htmlString.replace(/<[^>]+>/g, "").trim();

    if (text.toLowerCase().startsWith("if ")) {
      text = text.substring(3).trim();
    }

    // console.log("Actual Text :", text);
    return text;  // do not convert to lowercase here
  }

  function generateSummary(summary) {
    if (!summary) return "";
    if (typeof summary === "string") {
      return summary;
    }
    let conditionTexts = [];
    if (summary.conditions) {
      for (const setKey in summary.conditions) {
        if (Object.prototype.hasOwnProperty.call(summary.conditions, setKey)) {
          const conditionsVal = summary.conditions[setKey];
          const conditionsArray = Array.isArray(conditionsVal) ? conditionsVal : [conditionsVal];
          const cleanConditions = conditionsArray.map(extractText);
          conditionTexts.push(cleanConditions.join(", "));
        }
      }
    }
    const conditionsStr = conditionTexts.join(", ");
    let actionsStr = "";
    if (summary.actions && Array.isArray(summary.actions)) {
      const cleanActions = summary.actions.map(extractText);
      actionsStr = cleanActions.join(", ");
    }
    if (conditionsStr && actionsStr) {
      return `if ${conditionsStr}, then ${actionsStr}`;
    } else if (conditionsStr) {
      return `if ${conditionsStr}`;
    } else if (actionsStr) {
      return actionsStr;
    }
    return "";
  }

  function MenuList({ visible, onEdit, onClone, rule }) {
    return (
      <ul
        style={{
          position: "absolute",
          backgroundColor: "white",
          boxShadow: "0 8px 24px rgba(0, 0, 0, 0.15)",
          borderRadius: 6,
          padding: "8px 0",
          minWidth: 160,
          right: 0,
          top: 28,
          listStyle: "none",
          zIndex: 9999,
          margin: 0,
          opacity: visible ? 1 : 0,
          transform: visible ? "translateY(0px) scale(1)" : "translateY(-10px) scale(0.98)",
          transition: "opacity 300ms ease, transform 300ms ease",
          pointerEvents: visible ? "auto" : "none",
          willChange: "opacity, transform",
        }}
      >
        {[
          { name: "edit", label: "Edit", onClick: onEdit },
          { name: "clone", label: "Clone", onClick: onClone },
          {
            name: "delete",
            label: "Delete",
            onClick: () => {
              setMenuOpen(false);
              openModal();
            },
          },
        ].map(({ name, label, onClick }) => (
          <li
            key={name}
            style={{
              display: "flex",
              alignItems: "center",
              gap: 8,
              padding: "8px 16px",
              cursor: "pointer",
              color: "#333",
              fontWeight: 500,
              userSelect: "none",
              backgroundColor: "transparent",
              transition: "background-color 0.2s",
            }}
            onClick={(e) => {
              e.stopPropagation();
              onClick?.();
              setMenuOpen(false);
            }}
            onMouseEnter={(e) => (e.currentTarget.style.backgroundColor = "#f5f7f9")}
            onMouseLeave={(e) => (e.currentTarget.style.backgroundColor = "transparent")}
          >
            <FwIcon name={name} size={18} color="#333" />
            <div>{label}</div>
          </li>
        ))}
      </ul>
    );
  }

  return (
    <>
      <div
        className="fw-card-1 fw-flex fw-flex-column"
        style={{
          overflow: "visible",
          border: "0.5px solid #ddd",
          backgroundColor: isFirstInGroup ? "#fff" : "#e5f2fd",
          cursor: "pointer",
        }}
        onClick={handleClick}
      >
        <section
          className="fw-flex-grow fw-px-16 fw-flex fw-flex-row"
          style={{
            justifyContent: "space-between",
            alignItems: "center",
            marginBottom: "40px",
          }}
        >
          <div
            style={{
              paddingLeft: "16px",
              maxWidth: "80%",
              flexBasis: "80%",
              flexShrink: 0,
              whiteSpace: "normal",
            }}
          >
            <h5 className="fw-type-h1 fw-mt-0 fw-mb-8">
              {position}. {name}
            </h5>
            <p
              className="fw-type-xs fw-mt-0 fw-mb-20"
              style={{ marginBottom: "10px", fontSize: "14px" }}
            >
              {generateSummary(rule.summary)}
            </p>
          </div>
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: "8px",
              padding: "8px 16px",
              flexBasis: "20%",
              flexShrink: 0,
              marginTop: "-50px",
              justifyContent: "flex-end",
              position: "relative",
            }}
          >
            <FwToggle size="medium" checked={active} />
            <div ref={menuContainerRef} style={{ position: "relative" }}>
              <div
                role="button"
                tabIndex={0}
                onClick={(e) => {
                  e.stopPropagation();
                  setMenuOpen(!menuOpen);
                }}
                style={{
                  zIndex: 1,
                  background: "none",
                  border: "none",
                  cursor: "pointer",
                }}
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  className="app-icon dropdown-toggle"
                >
                  <path
                    fillRule="evenodd"
                    d="M12 5c-1.38 0-2.5-1.12-2.5-2.5S10.62 0 12 0s2.5 1.12 2.5 2.5S13.38 5 12 5zM12 14c-1.38 0-2.5-1.12-2.5-2.5S10.62 9 12 9s2.5 1.12 2.5 2.5S13.38 14 12 14zM12 24c-1.38 0-2.5-1.12-2.5-2.5S10.62 19 12 19s2.5 1.12 2.5 2.5S13.38 24 12 24z"
                  />
                </svg>
              </div>
              <MenuList
                visible={menuOpen}
                onEdit={() => alert("Edit clicked")}
                onClone={() => alert("Clone clicked")}
                rule={rule}
              />
            </div>
          </div>
        </section>
        <section
          className="fw-type-xs fw-flex fw-flex-row fw-items-center options"
          style={{
            background: "#f5f7f9",
            padding: "10px 16px",
            borderRadius: "5px",
          }}
        >
          <div
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-evenly",
              width: "100%",
              fontSize: "14px",
              color: "#666",
              textAlign: "center",
            }}
          >
            <span>
              Last Modified: <strong>{calculateLastModified(updated_at)}</strong>
            </span>
            <span>|</span>
            <span>By: {renderAgentName()}</span>
            <span>|</span>
            <span>Impacted tickets (Last 7 days): {affected_tickets_count}</span>
          </div>
        </section>
      </div>

      <FwModal
        id={`delete-modal-${id}`}
        ref={modalRef}
        size="small"
        submit-color="danger"
        submit-text="Delete"
        onFwSubmit={(e) => {
          e.preventDefault?.();
          handleConfirmDelete();
        }}
        onFwClose={() => {
          setShowDeleteModal(false);
          if (modalRef.current) modalRef.current.close();
        }}
      >
        <FwModalTitle>
          <span>Delete message</span>
        </FwModalTitle>
        <FwModalContent>
          <span>Are you sure you want to delete this Message?</span>
        </FwModalContent>
      </FwModal>
    </>
  );
};

const AutomationTabs = ({ client }) => {
  const [isRulesDBReady, setIsRulesDBReady] = useState(false);
  const [loadingBannerVisible, setLoadingBannerVisible] = useState(true);
  const intervalIdRef = useRef(null);
  const [showSearchHint, setShowSearchHint] = useState(false);

  const [searchTerm, setSearchTerm] = useState("");
  const [searchQuery, setSearchQuery] = useState("");
  const [searchTriggered, setSearchTriggered] = useState(false);

  const [errorMessage, setErrorMessage] = useState(null);

  const [activeTab, setActiveTab] = useState("ticketcreate");
  const [inputState, setInputState] = useState("normal");
  const [tabsInitialized, setTabsInitialized] = useState(false);
  const modalRef = useRef(null);

  const [ticketCreationRules, setTicketCreationRules] = useState([]);
  const [ticketUpdateRules, setTicketUpdateRules] = useState([]);
  const [hourlyTriggerRules, setHourlyTriggerRules] = useState([]);

  const [loading, setLoading] = useState(false);
  const [agent, setAgent] = useState([]);
  const rulesPerPage = 30;

  const [currentPage, setCurrentPage] = useState({
    ticketcreate: 1,
    ticketupdate: 1,
    hourly: 1,
  });

  const [recentDataCache, setRecentDataCache] = useState({
    ticketcreate: null,
    ticketupdate: null,
    hourly: null,
  });

  const toast = useRef(ToastController({ position: "top-center" }));

  const newRulePloadDB5 = useRef(null);
  const warningTimerRef = useRef(null);

  const ticketCreate = 1;
  const ticketUpdate = 4;
  const hourlyTriggers = 3;

  const [fetchFromApi, setFetchFromApi] = useState(false);

  const [showPagination, setShowPagination] = useState(false);

  const [ticketCreationRuleGroups, setTicketCreationRuleGroups] = useState([]);
  const [ticketUpdateRuleGroups, setTicketUpdateRuleGroups] = useState([]);
  const [hourlyRuleGroups, setHourlyRuleGroups] = useState([]);

  const ruleViewOptions = [
    {
      value: "all_rules",
      text: "All Rules",
      graphicsProps: { name: "list" },
    },
    {
      value: "duplicate_rules",
      text: "Duplicate Rules",
      graphicsProps: { name: "warning" },
    },
  ];
  const [ruleViewFilter, setRuleViewFilter] = useState(ruleViewOptions[0]);

  useEffect(() => {
    if (!loading) {
      const timer = setTimeout(() => {
        setShowPagination(true);
      }, 200);
      return () => clearTimeout(timer);
    } else {
      setShowPagination(false);
    }
  }, [loading, activeTab, currentPage]);

  const paginateDuplicateGroups = (groups, rulesPerPage, searchQuery) => {
    const filteredGroups = groups
      .map((group) =>
        group.filter(
          (rule) =>
            !searchQuery.trim() ||
            rule.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
            rule.description?.toLowerCase().includes(searchQuery.toLowerCase())
        )
      )
      .filter((group) => group.length > 0);
  
    const paginatedGroups = [];
    let currentChunk = [];
    let currentCount = 0;
  
    for (const group of filteredGroups) {
      const groupSize = group.length;
  
      if (groupSize > rulesPerPage) {
        if (currentCount > 0) {
          paginatedGroups.push(currentChunk);
          currentChunk = [];
          currentCount = 0;
        }
        paginatedGroups.push([group]);
      } else {
        if (currentCount + groupSize <= rulesPerPage) {
          currentChunk.push(group);
          currentCount += groupSize;
        } else {
          if (currentCount > 0) {
            paginatedGroups.push(currentChunk);
          }
          currentChunk = [group];
          currentCount = groupSize;
        }
      }
    }
    if (currentCount > 0) {
      paginatedGroups.push(currentChunk);
    }
  
    return paginatedGroups;
  };

  useEffect(() => {
    const initializeDatabase = async () => {
      const entity = await client.db.entity({ version: "v1" });
      newRulePloadDB5.current = entity.get("newRulePloadDB5");

      const agentdaa = await getAgents(client);
      setAgent(agentdaa);

      try {
        const tabData = await client.db.get("TabDB");
        if (!tabData || !tabData.LastVisitedTab) {
          await client.db.set("TabDB", { LastVisitedTab: "ticketcreate" });
          setActiveTab("ticketcreate");
        } else {
          setActiveTab(tabData.LastVisitedTab);
        }
      } catch (error) {
        await client.db.set("TabDB", { LastVisitedTab: "ticketcreate" });
        setActiveTab("ticketcreate");
      } finally {
        setTabsInitialized(true);
      }
    };

    initializeDatabase();
  }, [client]);

  useEffect(() => {
    setCurrentPage((prev) => ({
      ...prev,
      [activeTab]: 1,
    }));
    setRuleViewFilter(ruleViewOptions[0]);
  }, [activeTab, fetchFromApi]);

  useEffect(() => {
    const fetchOnTabOrModeChange = async () => {
      setLoading(true);
      setErrorMessage(null);

      try {
        let error = null;

        if (fetchFromApi) {
          if (recentDataCache.agent) {
            setAgent(recentDataCache.agent);
          } else {
            await getAgents(client, (data) => {
              setAgent(data);
              setRecentDataCache((prev) => ({ ...prev, agent: data }));
            });
          }

          if (recentDataCache[activeTab]) {
            if (activeTab === "ticketcreate") {
              setTicketCreationRules(recentDataCache.ticketcreate);
            } else if (activeTab === "ticketupdate") {
              setTicketUpdateRules(recentDataCache.ticketupdate);
            } else if (activeTab === "hourly") {
              setHourlyTriggerRules(recentDataCache.hourly);
            }
          } else {
            if (activeTab === "ticketcreate") {
              error = await getTicketCreationRules(client, (data) => {
                setTicketCreationRules(data);
                setRecentDataCache((prev) => ({ ...prev, ticketcreate: data }));
              });
            } else if (activeTab === "ticketupdate") {
              error = await getTicketUpdationRules(client, (data) => {
                setTicketUpdateRules(data);
                setRecentDataCache((prev) => ({ ...prev, ticketupdate: data }));
              });
            } else if (activeTab === "hourly") {
              error = await getHourlyRules(client, (data) => {
                setHourlyTriggerRules(data);
                setRecentDataCache((prev) => ({ ...prev, hourly: data }));
              });
            }
          }
        } else {
          if (!newRulePloadDB5.current) {
            setLoading(false);
            return;
          }

          if (activeTab === "ticketcreate") {
            const data = await Filterrecords(ticketCreate, newRulePloadDB5.current);
            setTicketCreationRules(data);
          } else if (activeTab === "ticketupdate") {
            const data = await Filterrecords(ticketUpdate, newRulePloadDB5.current);
            setTicketUpdateRules(data);
          } else if (activeTab === "hourly") {
            const data = await Filterrecords(hourlyTriggers, newRulePloadDB5.current);
            setHourlyTriggerRules(data);
          }

          setRecentDataCache({
            ticketcreate: null,
            ticketupdate: null,
            hourly: null,
            agent: null,
          });

          setAgent(null);
        }

        if (error) {
          setErrorMessage(error);
        }
      } catch (err) {
        setErrorMessage("An unexpected error occurred while fetching data.");
      }

      setLoading(false);
    };

    if (tabsInitialized && isRulesDBReady) {
      fetchOnTabOrModeChange();
    }
  }, [activeTab, fetchFromApi, client, tabsInitialized, isRulesDBReady]);

  const duplicateGroupsMap = useMemo(() => {
    // groups: array of arrays of duplicate rules with length > 1
    let allRules = [];
    if (activeTab === "ticketcreate") allRules = ticketCreationRules;
    else if (activeTab === "ticketupdate") allRules = ticketUpdateRules;
    else if (activeTab === "hourly") allRules = hourlyTriggerRules;
  
    // group duplicates, filtered active only
    const groups = groupDuplicates(allRules).filter((g) => g.length > 1);
  
    // Map rule_id -> isFirstInGroup flag (true only for first rule of each duplicate group)
    const firstRuleIds = new Set();
    groups.forEach((group) => {
      if (group.length > 0) {
        firstRuleIds.add(group[0].id);
      }
    });
  
    // Return structure for lookup: firstRuleIds set + flattened set of all duplicate IDs
    const duplicateRuleIds = new Set(groups.flat().map((r) => r.id));
  
    return { firstRuleIds, duplicateRuleIds };
  }, [activeTab, ticketCreationRules, ticketUpdateRules, hourlyTriggerRules]);


  const highlightDuplicates =
    ruleViewFilter.value === "all_rules" &&
    (!searchQuery || searchQuery.trim() === "");

  const getFilteredRules = (rules) => {
    if (!searchQuery.trim()) return rules;

    return rules.filter(
      (rule) =>
        rule.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
        rule.description?.toLowerCase().includes(searchQuery.toLowerCase())
    );
  };

  const flattenGroups = (groups) => groups.flat();

  // const getCurrentPageItemCount = () => {
  //   if (ruleViewFilter.value !== "duplicate_rules") {
  //     return rulesPerPage;
  //   }

  //   let groups = [];
  //   if (activeTab === "ticketcreate") groups = ticketCreationRuleGroups;
  //   else if (activeTab === "ticketupdate") groups = ticketUpdateRuleGroups;
  //   else if (activeTab === "hourly") groups = hourlyRuleGroups;

  //   const paginatedGroups = paginateDuplicateGroups(groups, rulesPerPage, searchQuery);
  //   const pageIndex = currentPage[activeTab] - 1;
  //   const groupsToShow = paginatedGroups[pageIndex] || [];
  //   const count = flattenGroups(groupsToShow).length || rulesPerPage;

  //   console.log(`[Pagination] Duplicate mode per-page on tab '${activeTab}' page ${pageIndex + 1}: ${count}`);

  //   return count;
  // };

  const getCurrentPageItemCount = () => {

    if (ruleViewFilter.value !== "duplicate_rules") {
      return rulesPerPage;
    }
  
    let groups = [];

    if (activeTab === "ticketcreate") groups = ticketCreationRuleGroups;
    else if (activeTab === "ticketupdate") groups = ticketUpdateRuleGroups;
    else if (activeTab === "hourly") groups = hourlyRuleGroups;
  
    const paginatedGroups = paginateDuplicateGroups(groups, rulesPerPage, searchQuery);
    const pageIndex = currentPage[activeTab] - 1;
    const groupsToShow = paginatedGroups[pageIndex];
  
    if (!groupsToShow || groupsToShow.length === 0) {
      return 0;
    }
  
    // exact count of items on current page
    const count = flattenGroups(groupsToShow).length;  
    console.log(`[Pagination] Duplicate mode per-page on tab '${activeTab}' page ${pageIndex + 1}: ${count}`);   
  
    return count;
  };

  const getPaginationTotalCount = () => {

    if (ruleViewFilter.value === "duplicate_rules") {
      let groups = [];
      if (activeTab === "ticketcreate") groups = ticketCreationRuleGroups;
      else if (activeTab === "ticketupdate") groups = ticketUpdateRuleGroups;
      else if (activeTab === "hourly") groups = hourlyRuleGroups;

      const filteredGroups = groups
        .map((group) =>
          group.filter(
            (rule) =>
              !searchQuery.trim() ||
              rule.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
              rule.description?.toLowerCase().includes(searchQuery.toLowerCase())
          )
        )
        .filter((group) => group.length > 0);

      return filteredGroups.reduce((acc, g) => acc + g.length, 0);


    } else {
      return getCurrentTotalCount();
    }
  };

// 4.41pm 16th may 2025
  useEffect(() => {
    if (ruleViewFilter.value === "duplicate_rules") {
      // Recalculate duplicate groups for the active tab automatically
      if (activeTab === "ticketcreate") {
        const grouped = groupDuplicates(ticketCreationRules);
        const duplicateGroups = grouped
          .filter((group) => group.length > 1)
          .sort((a, b) => b.length - a.length);
        setTicketCreationRuleGroups(duplicateGroups);
        setCurrentPage((prev) => ({ ...prev, ticketcreate: 1 }));
      } else if (activeTab === "ticketupdate") {
        const grouped = groupDuplicates(ticketUpdateRules);
        const duplicateGroups = grouped
          .filter((group) => group.length > 1)
          .sort((a, b) => b.length - a.length);
        setTicketUpdateRuleGroups(duplicateGroups);
        setCurrentPage((prev) => ({ ...prev, ticketupdate: 1 }));
      } else if (activeTab === "hourly") {
        const grouped = groupDuplicates(hourlyTriggerRules);
        const duplicateGroups = grouped
          .filter((group) => group.length > 1)
          .sort((a, b) => b.length - a.length);
        setHourlyRuleGroups(duplicateGroups);
        setCurrentPage((prev) => ({ ...prev, hourly: 1 }));
      }
    } else {
      // Clear duplicate groups when switching away from duplicate_rules view
      setTicketCreationRuleGroups([]);
      setTicketUpdateRuleGroups([]);
      setHourlyRuleGroups([]);
    }
  }, [ruleViewFilter, activeTab, ticketCreationRules, ticketUpdateRules, hourlyTriggerRules]);

  const getCurrentTotalCount = () => {
    if (activeTab === "ticketcreate") {
      if (ruleViewFilter.value === "duplicate_rules" && ticketCreationRuleGroups.length > 0) {
        return flattenGroups(ticketCreationRuleGroups).filter(
          (r) =>
            !searchQuery.trim() ||
            r.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
            r.description?.toLowerCase().includes(searchQuery.toLowerCase())
        ).length;
      }
      return getFilteredRules(ticketCreationRules).length;
    } else if (activeTab === "ticketupdate") {
      if (ruleViewFilter.value === "duplicate_rules" && ticketUpdateRuleGroups.length > 0) {
        return flattenGroups(ticketUpdateRuleGroups).filter(
          (r) =>
            !searchQuery.trim() ||
            r.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
            r.description?.toLowerCase().includes(searchQuery.toLowerCase())
        ).length;
      }
      return getFilteredRules(ticketUpdateRules).length;
    } else if (activeTab === "hourly") {
      if (ruleViewFilter.value === "duplicate_rules" && hourlyRuleGroups.length > 0) {
        return flattenGroups(hourlyRuleGroups).filter(
          (r) =>
            !searchQuery.trim() ||
            r.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
            r.description?.toLowerCase().includes(searchQuery.toLowerCase())
        ).length;
      }
      return getFilteredRules(hourlyTriggerRules).length;
    }
    return 0;
  };



  const renderRulesOrGroups = () => {
    let groups = [];
    let flatRules = [];

    if (activeTab === "ticketcreate") {
      groups = ticketCreationRuleGroups;
      flatRules = ticketCreationRules;
    } else if (activeTab === "ticketupdate") {
      groups = ticketUpdateRuleGroups;
      flatRules = ticketUpdateRules;
    } else if (activeTab === "hourly") {
      groups = hourlyRuleGroups;
      flatRules = hourlyTriggerRules;
    }

    if (loading) {
      return (
        <div
          style={{ display: "flex", justifyContent: "center", alignItems: "center", height: "200px" }}
        >
          <FwSpinner size="medium" color="green" />
        </div>
      );
    }

    if (ruleViewFilter.value === "duplicate_rules") {
      if (groups.length === 0) {
        return <p style={{ textAlign: "center", marginTop: "20px" }}>No Rules Found.</p>;
      }

      const paginatedGroups = paginateDuplicateGroups(groups, rulesPerPage, searchQuery);
      const pageIndex = currentPage[activeTab] - 1;
      const groupsToShow = paginatedGroups[pageIndex] || [];

      const flattenedRulesOnPage = flattenGroups(groupsToShow);
      const filteredRulesOnPage = getFilteredRules(flattenedRulesOnPage);

      const filteredGroupsToShow = groupsToShow
        .map((group) =>
          group.filter((rule) =>
            filteredRulesOnPage.some((filteredRule) => filteredRule.id === rule.id)
          )
        )
        .filter((group) => group.length > 0);

      if (filteredGroupsToShow.length === 0) {
        return <p style={{ textAlign: "center", marginTop: "20px" }}>No Rules Found.</p>;
      }

      return (
        <div style={{ marginLeft: 10, marginRight: "auto" }}>
          {filteredGroupsToShow.map((group, idx) => (
            <div
              key={`group-${pageIndex}-${idx}`}
              style={{ marginBottom: "12px", boxShadow: "0 4px 8px rgba(0, 0, 0, 0.2)" }}
            >
              {group.map((rule, i) => (
                <div
                  key={rule.id}
                  className="fw-card-1"
                  style={{
                    marginTop: i === 0 ? "10px" : "2px",
                    padding: "5px 8px",
                    borderRadius: "4px",
                  }}
                >
                  <AutomationCard
                    rule={rule}
                    index={i + 1}
                    isFirstInGroup={i === 0}
                    onDelete={() => deleteRule(rule, flattenedRulesOnPage)}
                    activeTab={activeTab}
                    onSelect={openRuleDetails}
                    agent={agent}
                  />
                </div>
              ))}
            </div>
          ))}
        </div>
      );
    } else {
      const filteredFlatRules = getFilteredRules(flatRules);
      const paginatedFlatRules = pagination(filteredFlatRules, currentPage[activeTab]);

      if (paginatedFlatRules.length === 0) {
        return <p style={{ textAlign: "center", marginTop: "20px" }}>No Rules Found.</p>;
      }

      return paginatedFlatRules.map((rule, idx) => {
        // If duplicates coloring enabled and this rule is a duplicate
        if (highlightDuplicates && duplicateGroupsMap.duplicateRuleIds.has(rule.id)) {
          const isFirstInGroup = duplicateGroupsMap.firstRuleIds.has(rule.id);
          return (
            <div
              key={rule.id || idx}
              className="fw-card-1"
              style={{
                marginBottom: "5px",
                marginTop: "10px",
                padding: "5px 8px",
                marginLeft: 10,
                marginRight: "auto",
              }}
            >
              <AutomationCard
                rule={rule}
                index={idx + 1}
                isFirstInGroup={isFirstInGroup} // first in duplicates = true, no color; others = false, colored
                onDelete={() => deleteRule(rule, filteredFlatRules)}
                activeTab={activeTab}
                onSelect={openRuleDetails}
                agent={agent}
              />
            </div>
          );
        } else {
          // Not duplicate or highlight not enabled: normal card
          return (
            <div
              key={rule.id || idx}
              className="fw-card-1"
              style={{
                marginBottom: "5px",
                marginTop: "10px",
                padding: "5px 8px",
                marginLeft: 10,
                marginRight: "auto",
              }}
            >
              <AutomationCard
                rule={rule}
                index={idx + 1}
                isFirstInGroup={true}
                onDelete={() => deleteRule(rule, filteredFlatRules)}
                activeTab={activeTab}
                onSelect={openRuleDetails}
                agent={agent}
              />
            </div>
          );
        }
      });


    }
  };

  // const deleteRule = async (rule, allRulesList) => {
  //   const { id } = rule;
  //   const matchedRecord = allRulesList.find((rec) => rec.id === id);

  //   let automationTypeId;
  //   let currentRules,
  //     setRulesFunc,
  //     groupSetterFunc,
  //     currentTabPage,
  //     tabKey;

  //   switch (activeTab) {
  //     case "ticketcreate":
  //       automationTypeId = ticketCreate;
  //       currentRules = ticketCreationRules;
  //       setRulesFunc = setTicketCreationRules;
  //       groupSetterFunc = setTicketCreationRuleGroups;
  //       currentTabPage = currentPage.ticketcreate;
  //       tabKey = "ticketcreate";
  //       break;
  //     case "ticketupdate":
  //       automationTypeId = ticketUpdate;
  //       currentRules = ticketUpdateRules;
  //       setRulesFunc = setTicketUpdateRules;
  //       groupSetterFunc = setTicketUpdateRuleGroups;
  //       currentTabPage = currentPage.ticketupdate;
  //       tabKey = "ticketupdate";
  //       break;
  //     case "hourly":
  //       automationTypeId = hourlyTriggers;
  //       currentRules = hourlyTriggerRules;
  //       setRulesFunc = setHourlyTriggerRules;
  //       groupSetterFunc = setHourlyRuleGroups;
  //       currentTabPage = currentPage.hourly;
  //       tabKey = "hourly";
  //       break;
  //     default:
  //       return;
  //   }

  //   const targetDisplayId = matchedRecord ? matchedRecord.display_id : undefined;

  //   if (targetDisplayId && newRulePloadDB5.current) {
  //     try {
  //       await newRulePloadDB5.current.delete(targetDisplayId);
  //     } catch (err) {}
  //   }

  //   try {
  //     const response = await client.request.invokeTemplate("deleterule", {
  //       context: {
  //         automationid: automationTypeId,
  //         ruleid: id,
  //       },
  //     });

  //     if (response.status === 204) {
  //       const updatedRules = currentRules.filter((r) => r.id !== id);
  //       setRulesFunc(updatedRules);

  //       groupSetterFunc([]);

  //       let filteredRules = getFilteredRules(updatedRules);

  //       const paginatedItems = pagination(filteredRules, currentTabPage);

  //       if (paginatedItems.length === 0 && currentTabPage > 1) {
  //         setCurrentPage((prev) => ({
  //           ...prev,
  //           [tabKey]: prev[tabKey] - 1,
  //         }));
  //       }

  //       toast.current.trigger({ type: "success", content: "Rule deleted successfully!" });
  //     } else {
  //       toast.current.trigger({ type: "error", content: "Failed to delete rule." });
  //     }
  //   } catch (error) {
  //     toast.current.trigger({ type: "error", content: "Error deleting rule." });
  //   }
  // };


  const deleteRule = async (rule, allRulesList) => {
    const { id } = rule;
    const matchedRecord = allRulesList.find((rec) => rec.id === id);
  
    let automationTypeId;
    let currentRules,
      setRulesFunc,
      groupSetterFunc,
      currentTabPage,
      tabKey;
  
    switch (activeTab) {
      case "ticketcreate":
        automationTypeId = ticketCreate;
        currentRules = ticketCreationRules;
        setRulesFunc = setTicketCreationRules;
        groupSetterFunc = setTicketCreationRuleGroups;
        currentTabPage = currentPage.ticketcreate;
        tabKey = "ticketcreate";
        break;
      case "ticketupdate":
        automationTypeId = ticketUpdate;
        currentRules = ticketUpdateRules;
        setRulesFunc = setTicketUpdateRules;
        groupSetterFunc = setTicketUpdateRuleGroups;
        currentTabPage = currentPage.ticketupdate;
        tabKey = "ticketupdate";
        break;
      case "hourly":
        automationTypeId = hourlyTriggers;
        currentRules = hourlyTriggerRules;
        setRulesFunc = setHourlyTriggerRules;
        groupSetterFunc = setHourlyRuleGroups;
        currentTabPage = currentPage.hourly;
        tabKey = "hourly";
        break;
      default:
        return;
    }
  
    const targetDisplayId = matchedRecord ? matchedRecord.display_id : undefined;
  
    if (targetDisplayId && newRulePloadDB5.current) {
      try {
        await newRulePloadDB5.current.delete(targetDisplayId);
      } catch (err) {}
    }
  
    try {
      const response = await client.request.invokeTemplate("deleterule", {
        context: {
          automationid: automationTypeId,
          ruleid: id,
        },
      });
  
      if (response.status === 204) {
        // Remove deleted rule from the current flat rules list
        const updatedRules = currentRules.filter((r) => r.id !== id);
        setRulesFunc(updatedRules);
  
        if (ruleViewFilter.value === "duplicate_rules") {
          // Recalculate duplicate groups with updated rules after deletion
          const updatedGroups = groupDuplicates(updatedRules)
            .filter((g) => g.length > 1)
            // Optional: sort largest groups first or as you prefer
            .sort((a, b) => b.length - a.length);
  
          groupSetterFunc(updatedGroups);
  
          // Flatten the updated groups to find rules on current page
          const flattenUpdatedGroups = flattenGroups(updatedGroups);
          const filteredRules = getFilteredRules(flattenUpdatedGroups);
          const paginated = pagination(filteredRules, currentTabPage);
  
          // If current page empty and not first page, shift current page back
          if (paginated.length === 0 && currentTabPage > 1) {
            setCurrentPage((prev) => ({ ...prev, [tabKey]: prev[tabKey] - 1 }));
          }
        } else {
          // In "all_rules" mode or others, just clear groups cache (optional)
          groupSetterFunc([]);
        }
  
        toast.current.trigger({ type: "success", content: "Rule deleted successfully!" });
      } else {
        toast.current.trigger({ type: "error", content: "Failed to delete rule." });
      }
    } catch (error) {
      console.log(error);
      toast.current.trigger({ type: "error", content: "Error deleting rule." });
    }
  };

  const openRuleDetails = (rule) => {};

  const closeRuleDetails = () => {};

  const handleFilterApiClick = () => {
    if (activeTab === "ticketcreate") {
      const grouped = groupDuplicates(ticketCreationRules);
      const duplicateGroups = grouped
        .filter((group) => group.length > 1)
        .sort((a, b) => b.length - a.length);
      setTicketCreationRuleGroups(duplicateGroups);
      setCurrentPage((prev) => ({ ...prev, ticketcreate: 1 }));
    } else if (activeTab === "ticketupdate") {
      const grouped = groupDuplicates(ticketUpdateRules);
      const duplicateGroups = grouped
        .filter((group) => group.length > 1)
        .sort((a, b) => b.length - a.length);
      setTicketUpdateRuleGroups(duplicateGroups);
      setCurrentPage((prev) => ({ ...prev, ticketupdate: 1 }));
    } else if (activeTab === "hourly") {
      const grouped = groupDuplicates(hourlyTriggerRules);
      const duplicateGroups = grouped
        .filter((group) => group.length > 1)
        .sort((a, b) => b.length - a.length);
      setHourlyRuleGroups(duplicateGroups);
      setCurrentPage((prev) => ({ ...prev, hourly: 1 }));
    }
  };

  const getPaginatedItemCount = () => {
    let rules = [];
    if (activeTab === "ticketcreate") rules = ticketCreationRules;
    else if (activeTab === "ticketupdate") rules = ticketUpdateRules;
    else if (activeTab === "hourly") rules = hourlyTriggerRules;

    let groups = [];
    if (activeTab === "ticketcreate") groups = ticketCreationRuleGroups;
    else if (activeTab === "ticketupdate") groups = ticketUpdateRuleGroups;
    else if (activeTab === "hourly") groups = hourlyRuleGroups;

    if (ruleViewFilter.value === "duplicate_rules" && groups.length > 0) {
      const flatList = flattenGroups(groups);
      const filtered = getFilteredRules(flatList);
      const paginated = pagination(filtered, currentPage[activeTab]);
      return paginated.length;
    } else {
      const flatList = rules;
      const filtered = getFilteredRules(flatList);
      const paginated = pagination(filtered, currentPage[activeTab]);
      return paginated.length;
    }
  };

  const handlePageChange = (tab) => (event) => {
    setCurrentPage((prev) => ({
      ...prev,
      [tab]: event.detail.page,
    }));
  };

  useEffect(() => {
    setSearchTerm("");
    setSearchQuery("");
    setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
  }, [activeTab]);

  useEffect(() => {
    const fwTabs = document.querySelector("fw-tabs");

    const saveActiveTab = async (e) => {
      const newActiveTab = e.target.panel;
      setActiveTab(newActiveTab);

      try {
        let tabData = (await client.db.get("TabDB")) || {};
        tabData.LastVisitedTab = newActiveTab;
        await client.db.set("TabDB", tabData);
      } catch (error) {}
    };

    if (fwTabs) {
      fwTabs.addEventListener("fwChange", saveActiveTab);
    }

    return () => {
      if (fwTabs) {
        fwTabs.removeEventListener("fwChange", saveActiveTab);
      }
    };
  }, [client]);

  const fetchData = async () => {
    setSearchTerm("");
    setSearchQuery("");
    setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));

    setFetchFromApi((prev) => !prev);

    toast.current.trigger({
      type: "info",
      content: `${fetchFromApi ? "Going Back" : "Fetching Recent Data"}...`,
    });
  };

  const checkAndSetButtonState = async () => {
    try {
      const storedvalue1 = await client.db.get("RulesDB");
      const isButtonEnabled = !!storedvalue1.stored;
      if (isButtonEnabled) {
        setIsRulesDBReady(true);
        setLoadingBannerVisible(false);

        if (intervalIdRef.current) {
          clearInterval(intervalIdRef.current);
          intervalIdRef.current = null;
        }
      } else {
        setIsRulesDBReady(false);
        setLoadingBannerVisible(true);
        if (!intervalIdRef.current) {
          intervalIdRef.current = setInterval(checkAndSetButtonState, 60000);
        }
      }
    } catch (error) {
      if (error.status === 404) {
        setIsRulesDBReady(faise);
        setLoadingBannerVisible(true);
        if (intervalIdRef.current) {
          clearInterval(intervalIdRef.current);
          intervalIdRef.current = null;
        }
      }
    }
  };

  useEffect(() => {
    checkAndSetButtonState();
    return () => {
      if (intervalIdRef.current) clearInterval(intervalIdRef.current);
    };
  }, []);

  // const ruleViewPopoverRef = useRef(null);

  const ruleViewPopoverRef = useRef(null);
  
  const searchInputs = (
    <div
      style={{
        display: "flex",
        alignItems: "center",
        marginBottom: 10,
        marginLeft: 20,
        marginTop: 15,
        maxWidth: "100%",
        gap: "20px",
      }}
    >


<div style={{ flexShrink: 0 }}>
  <FwPopover
    sameWidth="false"
    placement="bottom-start"
    ref={ruleViewPopoverRef}  
  >
    <FwButton slot="popover-trigger" color="secondary" showCaretIcon>
      <FwIcon slot="before-label" name={ruleViewFilter.graphicsProps.name} />
      <span>{ruleViewFilter.text}</span>
    </FwButton>
    <div slot="popover-content" style={{ width: 220 }}>
      <span
        style={{ fontStyle: "italic" }}
        className="row fw-flex fw-type-xs fw-p-4 fw-type-semibold"
      >
        Select Rule View
      </span>
      <hr style={{ margin: 0 }} />
      <FwListOptions
        onFwChange={(event) => {
          const selected = event.detail?.meta?.selectedOptions[0];
          if (selected) {
            setRuleViewFilter(selected);
            setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));

            if (selected.value === "all_rules") {
              setTicketCreationRuleGroups([]);
              setTicketUpdateRuleGroups([]);
              setHourlyRuleGroups([]);
            } else if (selected.value === "duplicate_rules") {
              handleFilterApiClick();
            }

            // Close popover programmatically
            if (ruleViewPopoverRef.current) {
              ruleViewPopoverRef.current.close();
            }
          }
        }}
        selectedOptions={[ruleViewFilter]}
        options={ruleViewOptions}
        variant="icon"
      />
    </div>
  </FwPopover>
</div>

      <div style={{ flex: 1, display: "flex", justifyContent: "center", marginTop: 20 }}>
        <fw-input
          clear-input
          ref={useRef(null)}
          icon-left="search"
          hint-text="Type Keyword to Search"
          placeholder="Enter a Keyword to Search..."
          warning-text="Please Enter a Keyword to Search..."
          state={inputState}
          style={{
            width: "400px",
            height: "60px",
            fontSize: "18px",
          }}
          value={searchTerm}
          onInput={(e) => {
            const val = e.target.value;
            if (val.length < searchTerm.length) {
              setSearchQuery("");
            }
            setSearchTerm(val);
            if (showSearchHint) setShowSearchHint(false);
            if (inputState !== "normal") setInputState("normal");
            if (warningTimerRef.current) {
              clearTimeout(warningTimerRef.current);
              warningTimerRef.current = null;
            }
          }}
          onKeyDown={(e) => {
            if (e.key === "Enter") {
              const trimmed = e.target.value.trim();
              if (!trimmed) {
                setSearchQuery("");
                setShowSearchHint(false);
                setInputState("warning");

                warningTimerRef.current = setTimeout(() => {
                  setInputState("normal");
                  warningTimerRef.current = null;
                }, 3000);
              } else {
                setSearchQuery(trimmed);
                setShowSearchHint(false);
                setInputState("normal");
              }
              setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
            }
          }}
          fwInputClear={() => {
            setSearchTerm("");
            setSearchQuery("");
            setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
            setInputState("normal");

            if (warningTimerRef.current) {
              clearTimeout(warningTimerRef.current);
              warningTimerRef.current = null;
            }
          }}
        />
      </div>

      <div style={{ flexShrink: 0 }}>
        <FwButton color="primary" onFwClick={() => {}}>
          <fw-icon name="plus" size="16" style={{ marginRight: "8px" }}></fw-icon>
          Add New Rule
        </FwButton>
      </div>
    </div>
  );

  return (
    <>
      {errorMessage ? (
        <div
          style={{
            position: "fixed",
            top: 0,
            left: 0,
            width: "100vw",
            height: "100vh",
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            backgroundColor: "rgba(255, 255, 255, 0.8)",
            zIndex: 9999,
          }}
        >
          <div
            style={{
              color: "red",
              fontSize: "2rem",
              fontWeight: "bold",
              textAlign: "center",
              padding: "20px",
              backgroundColor: "white",
            }}
          >
            {errorMessage}
          </div>
        </div>
      ) : (
        <>
          <h2>Automations - Rules</h2>

          {showSearchHint && (
            <p style={{ color: "red", marginTop: "4px", fontSize: "0.9em" }}>
              Please enter a search term before searching.
            </p>
          )}

          {loadingBannerVisible && !isRulesDBReady && (
            <div
              style={{
                justifyContent: "center",
                alignItems: "center",
                height: "40px",
                width: "50%",
                margin: "0 auto",
              }}
            >
              <FwSpinner size="medium" color="green" />
              <span style={{ marginLeft: "8px" }}>Waiting for rules to be ready...</span>
            </div>
          )}

          {tabsInitialized && (
            <div style={{ width: "60%", marginRight: "auto" }}>
              <div
                style={{
                  display: "flex",
                  justifyContent: fetchFromApi ? "flex-start" : "flex-end",
                  marginBottom: 15,
                }}
              >
                <FwButton color="secondary" onFwClick={fetchData} disabled={!isRulesDBReady}>
                  {fetchFromApi ? (
                    <>
                      <FwIcon
                        slot="before-label"
                        name="arrow-left"
                        size={16}
                        style={{ marginRight: "8px" }}
                      />
                      Back
                    </>
                  ) : (
                    <>
                      Get Recent Data
                      <FwIcon
                        slot="after-label"
                        name="refresh"
                        size={16}
                        style={{ marginLeft: "8px" }}
                      />
                    </>
                  )}
                </FwButton>
              </div>

              <FwTabs activeTab={activeTab}>
                <FwTab slot="tab" panel="ticketcreate" onClick={() => setActiveTab("ticketcreate")}>
                  Ticket Creation
                </FwTab>
                <FwTab slot="tab" panel="ticketupdate" onClick={() => setActiveTab("ticketupdate")}>
                  Ticket Updates
                </FwTab>
                <FwTab slot="tab" panel="hourly" onClick={() => setActiveTab("hourly")}>
                  Hourly Triggers
                </FwTab>

                <FwTabPanel name="ticketcreate">
                  {searchInputs}
                  {renderRulesOrGroups()}
                  {showPagination && getPaginatedItemCount() > 0 && (
                    <div style={{ marginTop: 10 }}>
                      <div style={{ display: "flex", justifyContent: "center" }}>
                        <FwPagination
                          per-page={getCurrentPageItemCount()}
                          total={getPaginationTotalCount()}
                          page={currentPage.ticketcreate}
                          onFwChange={handlePageChange("ticketcreate")}
                        />
                      </div>
                    </div>
                  )}
                </FwTabPanel>

                <FwTabPanel name="ticketupdate">
                  {searchInputs}
                  {renderRulesOrGroups()}
                  {showPagination && getPaginatedItemCount() > 0 && (
                    <div style={{ marginTop: 10 }}>
                      <div style={{ display: "flex", justifyContent: "center" }}>
                        <FwPagination
                          per-page={getCurrentPageItemCount()}
                          total={getPaginationTotalCount()}
                          page={currentPage.ticketupdate}
                          onFwChange={handlePageChange("ticketupdate")}
                        />
                      </div>
                    </div>
                  )}
                </FwTabPanel>

                <FwTabPanel name="hourly">
                  {searchInputs}
                  {renderRulesOrGroups()}
                  {showPagination && getPaginatedItemCount() > 0 && (
                    <div style={{ marginTop: 10 }}>
                      <div style={{ display: "flex", justifyContent: "center" }}>
                        <FwPagination
                          per-page={getCurrentPageItemCount()}
                          total={getPaginationTotalCount()}
                          page={currentPage.hourly}
                          onFwChange={handlePageChange("hourly")}
                        />
                      </div>
                    </div>
                  )}
                </FwTabPanel>
              </FwTabs>
            </div>
          )}
        </>
      )}

      <FwToast />
    </>
  );
};

export default AutomationTabs;


in this explain how checkandsetbuttonstate