import React, { useState, useEffect } from "react";
import { FwTabs, FwTab, FwTabPanel, FwSpinner, FwPagination } from "@freshworks/crayons/react";
import AutomationCard from "./AutomationCard";
import { getTicketCreationRules, getTicketUpdationRules, getHourlyRules } from '../common';

const getRuleSignature = (rule) => {
  return JSON.stringify({
    conditions: rule.summary.conditions,
    actions: rule.summary.actions,
  });
};

const groupDuplicates = (rules) => {
  const grouped = {};
  rules.forEach((rule) => {
    const signature = getRuleSignature(rule);
    if (!grouped[signature]) {
      grouped[signature] = [];
    }
    grouped[signature].push(rule);
  });
  return Object.values(grouped);
};

const ITEMS_PER_PAGE = 5; 

const AutomationTabs = ({ client }) => {
  const [searchTerm, setSearchTerm] = useState("");
  const [searchTriggered, setSearchTriggered] = useState(false);
  const [activeTab, setActiveTab] = useState("ticketcreate");

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

  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);

  const fetchRules = async () => {
    setLoading(true);
    await Promise.all([
      getTicketCreationRules(client, setTicketCreationRules),
      getTicketUpdationRules(client, setTicketUpdateRules),
      getHourlyRules(client, setHourlyTriggerRules),
    ]);
    setLoading(false);
  };

  useEffect(() => {
    fetchRules();
  }, [client]);

  const getFilteredGroups = (rules) => {
    if (!searchTriggered || !searchTerm.trim()) return groupDuplicates(rules);
    return groupDuplicates(rules).filter((group) =>
      group.some(
        (rule) =>
          rule.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
          rule.description?.toLowerCase().includes(searchTerm.toLowerCase())
      )
    );
  };

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

    // Calculate the current page elements
    const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
    const selectedGroups = groups.slice(startIndex, startIndex + ITEMS_PER_PAGE);

    return selectedGroups.length > 0 ? (
      selectedGroups.map((group, index) => (
        <div key={index} className="fw-card-1 fw-py-16" style={{ border: "1px solid #ddd", borderRadius: "8px", marginBottom: "20px", marginTop: "20px", padding: "10px 16px", boxShadow: "0 4px 8px rgba(0, 0, 0, 0.1)", width: "80%", marginLeft: "auto", marginRight: "auto" }}>
          {group.map((rule, idx) => (
            <AutomationCard key={idx} rule={rule} index={idx + 1} isFirstInGroup={idx === 0} />
          ))}
        </div>
      ))
    ) : (
      <p style={{ textAlign: "center", marginTop: "20px" }}>No Rules Found Matched Your Search: {searchTerm}</p>
    );
  };

  const getRulesByTab = () => {
    switch (activeTab) {
      case "ticketcreate":
        return ticketCreationRules;
      case "ticketupdate":
        return ticketUpdateRules;
      case "hourly":
        return hourlyTriggerRules;
      default:
        return [];
    }
  };

  const groups = getFilteredGroups(getRulesByTab());
  const totalPages = Math.ceil(groups.length / ITEMS_PER_PAGE); // Total pages based on items per page

  return (
    <>
      <h2>Automations - Rules</h2>
      <input
        type="text"
        placeholder="Search by name or description"
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
      />
      <button onClick={() => { setSearchTriggered(true); setCurrentPage(1); }}>Search</button>

      <FwTabs onFwChange={(e) => setActiveTab(e.target.panel)}>
        <FwTab slot="tab" panel="ticketcreate">Ticket Create</FwTab>
        <FwTab slot="tab" panel="ticketupdate">Ticket Update</FwTab>
        <FwTab slot="tab" panel="hourly">Hourly Triggers</FwTab>

        <FwTabPanel name="ticketcreate">
          {renderGroupedRules(groups)}
        </FwTabPanel>

        <FwTabPanel name="ticketupdate">
          {renderGroupedRules(groups)}
        </FwTabPanel>

        <FwTabPanel name="hourly">
          {renderGroupedRules(groups)}
        </FwTabPanel>
      </FwTabs>

      {totalPages > 1 && (
        <FwPagination
          per-page={ITEMS_PER_PAGE}
          total={groups.length}
          onFwChange={(event) => setCurrentPage(event.detail.page)}
        />
      )}
    </>
  );
};

export default AutomationTabs;



how search works in this code?