import React, { useState, useEffect, useRef } from "react";
import { FwTabs, FwTab, FwTabPanel, FwProgressLoader, FwSpinner } 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 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 loaderRef = useRef(null);

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

    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="large" color="green" />
        </div>
      );
    }
    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", 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} />
          ))}
        </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 [];
    };
  };

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

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

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

export default AutomationTabs;


import React from "react";
import { FwToggle } from "@freshworks/crayons/react";

const AutomationCard = ({ rule = {}, index }) => {
  const {
    name = "Default Rule Name",
    description = "Default Rule Description",
    updated_at = "N/A",
    last_updated_by = "Unknown",
    affected_tickets_count = "--",
    active = false,
    position = position
  } = rule;

  return (
    <div
      className="fw-card-1 fw-py-16 fw-flex fw-flex-column"
      style={{
        borderRadius: "8px",
        width: "80%",
        overflow: "hidden",
        border: "1px solid #ddd",
        margin: "0 auto",
        marginBottom: "16px"
      }}
    >
      <section
        className="fw-flex-grow fw-px-16 fw-flex fw-flex-row"
        style={{ justifyContent: "space-between", alignItems: "center" }}
      >
       <div style={{ paddingLeft: "16px" }}> 
       <h5 className="fw-type-h5 fw-mt-0 fw-mb-8">
  {position}. {name}
</h5>

  <p className="fw-type-xs fw-mt-0 fw-mb-20">
    {description}
  </p>
</div>

        <div style={{ padding: "8px 16px" }}>
          <FwToggle size="medium" checked={active} />
        </div>
      </section>

      <section
  className="fw-type-xs fw-flex fw-flex-row fw-items-center options"
  style={{ width: "100%", background: "#f5f5f5", 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>{updated_at}</strong></span>
    <span>|</span>
    <span>By: {last_updated_by}</span>
    <span>|</span>
    <span>Impacted tickets (Last 7 days): {affected_tickets_count}</span>
  </div>
</section>

    </div>
  );
};

export default AutomationCard;



in this, in automation card, create another div that holds everything, when grouping duplicates, it should show inside one div which look like one group remove whole div from AutomationTab.js