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

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

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;

      allRecords = allRecords.concat(response.records.map(record => record.data));
      nextMarker = response.links?.next?.marker || null;
    } while (nextMarker);

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

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);
  
  // Use sessionStorage to initialize activeTab
  const [activeTab, setActiveTab] = useState(() => {
    return sessionStorage.getItem('activeTab') || "ticketcreate";
  });

  const [ticketCreationRules, setTicketCreationRules] = useState([]);
  const [ticketUpdateRules, setTicketUpdateRules] = useState([]);
  const [hourlyTriggerRules, setHourlyTriggerRules] = useState([]);
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const rulesPerPage = 5;

  useEffect(() => {
    const initializeDatabase = async () => {
      console.log("Initializing database...");
      const entity = await client.db.entity({ version: "v1" });
      const newRulePloadDB3 = entity.get("newRulePloadDB3");

      // Fetch existing rules from entity storage and update state
      const entticketcreate = await Filterrecords(1, newRulePloadDB3);
      const enthourly = await Filterrecords(3, newRulePloadDB3);
      const entticketupdate = await Filterrecords(4, newRulePloadDB3);

      // Update state with fetched records
      setTicketCreationRules(entticketcreate);
      setTicketUpdateRules(entticketupdate);
      setHourlyTriggerRules(enthourly);
    };
    initializeDatabase();
  }, [client]);

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

  useEffect(() => {
    setCurrentPage(1);
  }, [activeTab]);

  // Update sessionStorage whenever the activeTab changes
  useEffect(() => {
    sessionStorage.setItem('activeTab', activeTab);
  }, [activeTab]);

  const getFilteredGroups = (rules) => {
    const groupedRules = groupDuplicates(rules);
    if (!searchTriggered || !searchTerm.trim()) return groupedRules;

    return groupedRules.filter((group) =>
      group.some(
        (rule) =>
          rule.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
          rule.description?.toLowerCase().includes(searchTerm.toLowerCase())
      )
    );
  };

  const renderGroupedRules = (groups) => {
    const startIndex = (currentPage - 1) * rulesPerPage;
    const paginatedGroups = groups.slice(startIndex, startIndex + rulesPerPage);

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

    return paginatedGroups.length > 0 ? (
      paginatedGroups.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 handlePageChange = (pageNumber) => setCurrentPage(pageNumber);

  const renderPagination = (groups) => {
    const totalPages = Math.ceil(groups.length / rulesPerPage);
    return (
      <div style={{ textAlign: "center", marginTop: "20px" }}>
        {Array.from({ length: totalPages }, (_, index) => (
          <button
            key={index + 1}
            onClick={() => handlePageChange(index + 1)}
            style={{ margin: "0 5px", padding: "5px 10px", cursor: "pointer", background: currentPage === index + 1 ? "#4CAF50" : "#ddd" }}
          >
            {index + 1}
          </button>
        ))}
      </div>
    );
  };

  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>
      <button onClick={fetchRecentData} style={{ marginLeft: "10px" }}>Recent API Data</button>

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

        <FwTabPanel name="ticketcreate">
          {renderGroupedRules(getFilteredGroups(ticketCreationRules))}
          {renderPagination(getFilteredGroups(ticketCreationRules))}
        </FwTabPanel>

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

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

export default AutomationTabs;

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

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 }) => {
  const {
    name = "Default Rule Name",
    description = "Default Rule Description",
    updated_at = "N/A",
    last_updated_by = "Unknown",
    affected_tickets_count = "--",
    active = false,
    position = index + 1,
  } = rule;

  const [menuOpen, setMenuOpen] = useState(false);

  return (
    <div
      className="fw-card-1 fw-flex fw-flex-column"
      style={{
        overflow: "hidden",
        border: "0.5px solid #ddd",
        backgroundColor: isFirstInGroup ? "#43e955" : "#ff4d00",
      }}
    >
      <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-h2 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={{ display: "flex", alignItems: "center", gap: "8px", padding: "8px 16px", position: "relative" }}>
          <FwToggle size="medium" checked={active} />
          <div style={{ position: "relative"}}>
            {menuOpen && (
              <div className="dropdown-menu" style={{ position: "absolute", marginTop: "30px", top: "50%", right: "40px", transform: "translateY(-50%)", background: "white", boxShadow: "0px 4px 6px rgba(0,0,0,0.1)", borderRadius: "5px", padding: "8px 0", width: "120px", zIndex: 10 }}>
                <div style={{ padding: "8px 16px", cursor: "pointer", textAlign: "left" }} onClick={() => alert("Edit clicked")}>
                  Edit
                </div>
                <div style={{ padding: "8px 16px", cursor: "pointer", color: "red", textAlign: "left" }} onClick={() => alert("Delete clicked")}>
                  Delete
                </div>
              </div>
            )}
            <div
              className="ember-basic-dropdown-trigger"
              role="button"
              tabIndex="0"
              onClick={() => setMenuOpen(!menuOpen)}
            >
              <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"
                ></path>
              </svg>
            </div>
          </div>
        </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>{calculateLastModified(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;

on clicking Delete 

import React from "react";
import ReactDOM from "react-dom";
import { FwButton, FwModal, FwModalTitle, FwModalContent, FwModalFooter } from "@freshworks/crayons/react";
function App() {
  return (<div>
    <FwButton modal-trigger-id='composition'> Open confirmation Modal </FwButton>
    <FwModal id='composition' size="small" submit-color="danger" submit-text="Delete">
      <FwModalTitle>
        <span>Delete message</span>
      </FwModalTitle>
      <FwModalContent>
        <span>Are you sure you want to delete this Message?</span>
      </FwModalContent>
    </FwModal>
 </div>);
}

add this fw modal react js