import React, { useState, useEffect } from "react";
import { FwTabs, FwTab, FwTabPanel, FwSpinner } from "@freshworks/crayons/react";
import AutomationCard from "./AutomationCard";
import { getTicketCreationRules, getTicketUpdationRules, getHourlyRules, getAgents } 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);
  const [activeTab, setActiveTab] = useState("ticketcreate");
  const [tabsInitialized, setTabsInitialized] = useState(false);

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

  const rulesPerPage = 5;

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

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

      const entticketcreate = await Filterrecords(ticketCreate, newRulePloadDB3);
      const enthourly = await Filterrecords(hourlyTriggers, newRulePloadDB3);
      const entticketupdate = await Filterrecords(ticketUpdate, newRulePloadDB3);



      setTicketCreationRules(entticketcreate);
      setTicketUpdateRules(entticketupdate);
      setHourlyTriggerRules(enthourly);

      const agentdaa = await getAgents(client);
      console.log("Available agent :", agentdaa);

      try {
        const tabData = await client.db.get("TabDB");
        if (!tabData || !tabData.LastVisitedTab) {
          await client.db.set("TabDB", { LastVisitedTab: "ticketcreate" });
          console.log("🟢 No tab stored before. Defaulting to 'ticketcreate'");
          setActiveTab("ticketcreate");
        } else {
          console.log("🟢 Loaded tab from DB:", tabData.LastVisitedTab);
          setActiveTab(tabData.LastVisitedTab);
        }
      } catch (error) {
        console.error("❌ Error retrieving TabDB:", error);
        await client.db.set("TabDB", { LastVisitedTab: "ticketcreate" });
        setActiveTab("ticketcreate");
      } finally {
        setTabsInitialized(true);
      }
    };

    initializeDatabase();
  }, [client]);

  useEffect(() => {

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

    const saveActiveTab = async (e) => {
      const newActiveTab = e.target.panel;
      console.log("🟡 Tab clicked:", newActiveTab);
      setActiveTab(newActiveTab);

      try {
        let tabData = await client.db.get("TabDB") || {};
        tabData.LastVisitedTab = newActiveTab;
        await client.db.set("TabDB", tabData);
        console.log(`💾 Saved active tab to DB:`, newActiveTab);
      } catch (error) {
        console.error(`❌ Error setting active tab in DB:`, error);
      }
    };

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

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

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


  const fetchRecentData = async () => {
    setLoading(true);
    await Promise.all([
      getTicketCreationRules(client, setTicketCreationRules),
      getTicketUpdationRules(client, setTicketUpdateRules),
      getHourlyRules(client, setHourlyTriggerRules),
      getAgents(client, setAgent)    
      
    ]);
    // console.log("Agent in tab :", agent);
    setLoading(false);
  };

  const getFilteredGroups = (rules) => {

    // console.log("Rule Data :", 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"
          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}              
              onDelete={() => deleteRule(rule)}
              activeTab={activeTab}   
              agent={agent}        
            />
          ))}
        </div>
      ))
    ) : (
      <p style={{ textAlign: "center", marginTop: "20px" }}>
        No Rules Found Matched Your Search: {searchTerm}
      </p>
    );
  };

  const deleteRule = async (rule) => {
    const { id, display_id, ruleid } = rule; 

    let automationTypeId;

    switch (activeTab) {
      case "ticketcreate":
        automationTypeId = ticketCreate;
        break;
      case "ticketupdate":
        automationTypeId = ticketUpdate;
        break;
      case "hourly":
        automationTypeId = hourlyTriggers;
        break;
      default:
        console.error("Unknown active tab: ", activeTab);
        return;
    }

    
    console.log(("---------------Entity Data-----------"));
    console.log("Entity - ruleid:", id);    
    console.log("API From Tab:", activeTab);
    console.log("API - Automation id:", automationTypeId);



    console.log(("---------------API Data-----------"));
    console.log("API - ruleid:", id);    
    console.log("API From Tab:", activeTab);
    console.log("API - Automation id:", automationTypeId);
    


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

      if (response.status === 204) {
        console.log("Rule deleted successfully!");

        // Update the state based on the active tab
        if (activeTab === "ticketcreate") {
          const updatedRules = ticketCreationRules.filter(rule => rule.id !== id);
          setTicketCreationRules(updatedRules);
        } else if (activeTab === "ticketupdate") {
          const updatedRules = ticketUpdateRules.filter(rule => rule.id !== id);
          setTicketUpdateRules(updatedRules);
        } else if (activeTab === "hourly") {
          const updatedRules = hourlyTriggerRules.filter(rule => rule.id !== id);
          setHourlyTriggerRules(updatedRules);
        }

      } else {
        console.error("Failed to delete rule.");
      }
    } catch (error) {
      console.error("Error deleting rule:", error);
    }

  };

  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>
    );
  };

  // console.log("🟢 Rendering AutomationTabs with activeTab:", activeTab);

  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>

      {tabsInitialized && (
        <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">
            {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,
  FwModal,
  FwModalTitle,
  FwModalContent,
  FwModalFooter,
} from "@freshworks/crayons/react";
import { getAgents } from '../common';

// Function to calculate the time since the rule was last modified
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  }) => {
  const {
    id,
    name = "Default Rule Name",
    description = "Default Rule Description",
    updated_at = "N/A",
    last_updated_by = "Unknown",
    affected_tickets_count = "--",
    active = false,
    position = index + 1,    
    automation_type_id 
  } = rule;

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

  // Function called to show the delete confirmation modal
  const handleDeleteClick = () => {
    console.log("Choosed Automation Rule ID:", id);
    console.log("Automation Type ID:", automation_type_id);
    
  };
  
  const handleConfirmDelete = () => {
    // Define the automation type ID based on the active tab
    let automationTypeId;
    switch (activeTab) {
      case "ticketcreate":
        automationTypeId = 1; // For Ticket Creation
        break;
      case "ticketupdate":
        automationTypeId = 4; // For Ticket Updates
        break;
      case "hourly":
        automationTypeId = 3; // For Hourly Triggers
        break;
      default:
        console.error("Unknown active tab: ", activeTab);
        return;
    }
    // Pass the rule ID and the explicitly defined automation type ID
    onDelete(rule.id, automationTypeId);  
    setModalOpen(false); // Close the modal
  };

  return (
    <div
      className="fw-card-1 fw-flex fw-flex-column"
      style={{
        overflow: "hidden",
        border: "0.5px solid #ddd",
        backgroundColor: isFirstInGroup ? "#fff" : "#e5f2fd",
      }}
    >
      <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={() => {                  
                    handleConfirmDelete(); 
                  }}
                >
                  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: {agent.map(e => {
                if (e.value === last_updated_by)
                    return e.text
            })}</span>
          <span>|</span>
          <span>
            Impacted tickets (Last 7 days): {affected_tickets_count}
          </span>
        </div>
      </section>
    
    </div>
  );
};

export default AutomationCard;

on deleting rule from entity, show its display id, 

0 { record: { display_id: 'q5ajm-1', created_time: '2025-04-15T07:14:11.474Z', updated_time: '2025-04-15T07:14:11.474Z', data: { summary: 'If Subject contains payment Assign to Group Billing', automation_type_id: 1, performer: null, active: 'true', created_at: '2025-04-15T01:03:32Z', agentName: '', operator: null, rule_id: 157002457857, affected_tickets_count: 0, last_updated_by: null, outdated: false, updated_at: '2025-04-15T01:03:32Z', name: 'Send payments to Billing - Sample Dispatcher rule', position: 1, conditions: 'condition_set_1,any,subject,ticket,contains,payment', actions: 'group_id,157001076501', events: null } } }

i need display id, from data, i need automation_type_id, rule_id from entity

and log 

    console.log(("---------------Entity Data-----------"));
    console.log("Entity - ruleid:", id);    
    console.log("API From Tab:", activeTab);
    console.log("API - Automation id:", automationTypeId);

in this place