import React, { useState, useEffect } from "react";
import { FwTabs, FwTab, FwTabPanel } 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).filter((group) => group.length > 1); // Only include duplicates
};

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

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

  useEffect(() => {
    const fetchTicketCreationRules = async () => {
      await getTicketCreationRules(client, setTicketCreationRules);
    };

    const fetchTicketUpdateRules = async () => {
      await getTicketUpdationRules(client, setTicketUpdateRules);
    };

    const fetchHourlyTriggerRules = async () => {
      await getHourlyRules(client, setHourlyTriggerRules);
    };

    fetchTicketCreationRules();
    fetchTicketUpdateRules();
    fetchHourlyTriggerRules();
  }, [client]);

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

  const renderGroupedRules = (groups) => {
    return groups.length > 0 ? (
      groups.map((group, index) => (
        <div key={index} className="fw-card-1 fw-py-16" style={{ border: "1px solid #ddd", marginBottom: "16px", padding: "10px 16px" }}>
          {group.map((rule, idx) => (
            <AutomationCard key={idx} rule={rule} index={idx + 1} />
          ))}
        </div>
      ))
    ) : (
      <p>No duplicate rules found.</p>
    );
  };

  return (
    <>
      <h2>Automations - Duplicate Rules</h2>
      <input
        type="text"
        placeholder="Search by name or description"
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
      />

      <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(getFilteredGroups(ticketCreationRules))}
        </FwTabPanel>

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

        <FwTabPanel name="hourly">
          {renderGroupedRules(getFilteredGroups(hourlyTriggerRules))}
        </FwTabPanel>
      </FwTabs>
    </>
  );
};

export default AutomationTabs;



why grouping is not working for ticket update and hourlytrigger rles