Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-mini-2024-07-18· OpenAIAi2 WildChat-4.8M (AI2)

import React, { useState, useEffect } from "react"; import { FwTabs, FwTab, FwTabPanel,…

  1. User

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

    return ( <> Automations - Rules <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 onClick={fetchRecentData} style={{ marginLeft: "10px" }}>Recent API Data

      <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" }}> {position}. {name} {description}

        <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 ( Open confirmation Modal Delete message Are you sure you want to delete this Message?

    add this fw modal react js

  2. Assistant

    To implement a confirmation modal that appears when you click the "Delete" option in your AutomationCard component, you can follow these steps:

    1. Create a state for managing modal visibility in the AutomationCard component.
    2. Handle the visibility of the modal when the "Delete" button is clicked.
    3. Implement the logic for delete action (dummy or real implementation based on your requirements).
    4. Render the FwModal component conditionally based on whether it's open or closed.

    Here’s how you can do this:

    Step 1: Modify the AutomationCard Component

    Update the AutomationCard component to include the modal functionality:

    import React, { useState } from "react";
    import { FwToggle, FwButton, FwModal, FwModalTitle, FwModalContent, FwModalFooter } from "@freshworks/crayons/react";
    
    const calculateLastModified = (updated_at) => {
      // ... existing calculateLastModified function ...
    };
    
    const AutomationCard = ({ rule = {}, index, isFirstInGroup = false, onDelete }) => {
      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);
      const [modalOpen, setModalOpen] = useState(false);
    
      const handleDelete = () => {
        // Call the onDelete function passed from the parent to remove the rule
        onDelete(rule);
        setModalOpen(false); // Close the modal after deletion
      };
    
      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={() => setModalOpen(true)}>
                      Delete
                    </div>
                  </div>
                )}
                <div
                  className="ember-basic-dropdown-trigger"
                  role="button"
                  tabIndex="0"
                  onClick={() => setMenuOpen(!menuOpen)}
                >
                  {/* Dropdown icon */}
                  <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>
    
          {/* Confirmation Modal */}
          <FwModal id={`delete-modal-${position}`} open={modalOpen} size="small" submit-color="danger" submit-text="Delete" onFwRequestClose={() => setModalOpen(false)}>
            <FwModalTitle>
              <span>Delete message</span>
            </FwModalTitle>
            <FwModalContent>
              <span>Are you sure you want to delete this rule?</span>
            </FwModalContent>
            <FwModalFooter>
              <FwButton onClick={() => setModalOpen(false)}>Cancel</FwButton>
              <FwButton onClick={handleDelete} color="danger">Delete</FwButton>
            </FwModalFooter>
          </FwModal>
        </div>
      );
    };
    
    export default AutomationCard;
    

    Step 2: Implement the onDelete Prop

    You need to handle the deletion in the parent component (AutomationTabs) and pass the onDelete prop to the AutomationCard component.

    Update the renderGroupedRules function in AutomationTabs:

    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} onDelete={handleDelete} />
            ))}
          </div>
        ))
      ) : (
        <p style={{ textAlign: "center", marginTop: "20px" }}>No Rules Found Matched Your Search: {searchTerm}</p>
      );
    };
    
    // Handle the delete logic
    const handleDelete = (ruleToDelete) => {
      // Update your rules state to remove the deleted rule
      setTicketCreationRules((prevRules) => prevRules.filter(rule => rule.id !== ruleToDelete.id));
      setTicketUpdateRules((prevRules) => prevRules.filter(rule => rule.id !== ruleToDelete.id));
      setHourlyTriggerRules((prevRules) => prevRules.filter(rule => rule.id !== ruleToDelete.id));
    };
    

    In this case:

    • When the user clicks "Delete", the modal will open prompting the user for confirmation.
    • If the user confirms by clicking "Delete" in the modal, the clicked rule will be removed from the state managed by the AutomationTabs component.

    This implementation gives users feedback and requires them to confirm before performing a destructive action, which is a good practice in UI design.

  3. User

    without removing anything from my code, add this modal when click Delete. 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" }}> {position}. {name} {description}

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

  4. Assistant

    To add a confirmation modal to the AutomationCard component when the user clicks the "Delete" button, I'll integrate the modal functionality without removing anything from your existing code. The modal will prompt the user for confirmation before proceeding with the deletion.

    Here's how to implement it:

    1. Add state variables for managing the modal visibility: We'll add a state variable to control when the modal is open or closed.
    2. Create the modal using FwModal: Render the modal with a confirmation message and buttons for confirming or canceling the deletion.
    3. Handle the delete operation (dummy function): For now, we will just log the action, as you did not specify how you want to handle deletion.

    Updated AutomationCard Component

    Here’s the complete AutomationCard component with the modal functionality added:

    import React, { useState } from "react";
    import { FwToggle, FwButton, FwModal, FwModalTitle, FwModalContent, FwModalFooter } 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, onDelete }) => {
      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);
      const [modalOpen, setModalOpen] = useState(false); // State for modal visibility
    
      const handleDeleteClick = () => {
        setModalOpen(true); // Open modal on delete button click
      };
    
      const handleConfirmDelete = () => {
        onDelete(rule); // Call onDelete prop function with the current rule
        setModalOpen(false); // Close modal after delete confirmation
      };
    
      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={handleDeleteClick}>
                      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>
    
          {/* Confirmation Modal */}
          <FwModal open={modalOpen} onFwRequestClose={() => setModalOpen(false)}>
            <FwModalTitle>
              <span>Delete Rule</span>
            </FwModalTitle>
            <FwModalContent>
              <span>Are you sure you want to delete this rule?</span>
            </FwModalContent>
            <FwModalFooter>
              <FwButton onClick={() => setModalOpen(false)}>Cancel</FwButton>
              <FwButton onClick={handleConfirmDelete} color="danger">Delete</FwButton>
            </FwModalFooter>
          </FwModal>
        </div>
      );
    };
    
    export default AutomationCard;
    

    Explanation of the Changes:

    1. Modal State: Added modalOpen state to manage the visibility of the modal.
    2. Delete Button Behavior: Changed the onClick handler for the "Delete" button in the dropdown to open the modal instead of performing a delete action directly.
    3. Modal Rendering: Included a modal that prompts the user for confirmation with "Cancel" and "Delete" buttons.
    4. On Delete Confirm: When the user confirms deletion, the onDelete function is called with the current rule passed as an argument. This function should be defined in the parent component (AutomationTabs) to handle the actual deletion.

    Note

    Make sure that the onDelete prop is passed properly from the parent component (AutomationTabs) when rendering AutomationCard. This allows deletion logic to be processed appropriately when the user confirms the deletion in the modal.