import React, { useState, useEffect, useRef  } from "react";
import { FwTabs, FwTab, FwTabPanel, FwSpinner, ToastController, FwToast } 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,
        display_id: record.display_id,              // add this line
        rule_id: record.data.rule_id,                // ensure rule_id included
        automation_type_id: record.data.automation_type_id,
        id: record.data.rule_id || record.data.id,  // make sure id is always set
      })));

      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 toast = useRef(ToastController({ position: "top-right" }));

  const ticketCreateFilteredRecords = useRef([]);
const ticketUpdateFilteredRecords = useRef([]);
const hourlyFilteredRecords = useRef([]);

  const newRulePloadDB5 = useRef(null);

  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" });
      newRulePloadDB5.current = entity.get("newRulePloadDB5");

// Use newRulePloadDB5.current for all further usage inside initializeDatabase
const entticketcreate = await Filterrecords(ticketCreate, newRulePloadDB5.current);
const enthourly = await Filterrecords(hourlyTriggers, newRulePloadDB5.current);
const entticketupdate = await Filterrecords(ticketUpdate, newRulePloadDB5.current);

ticketCreateFilteredRecords.current = entticketcreate;
hourlyFilteredRecords.current = enthourly;
ticketUpdateFilteredRecords.current = entticketupdate;

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

  const getFilteredRecordsForActiveTab = () => {
    switch(activeTab) {
      case "ticketcreate": return ticketCreateFilteredRecords.current;
      case "ticketupdate": return ticketUpdateFilteredRecords.current;
      case "hourly": return hourlyFilteredRecords.current;
      default: return [];
    }
  }

const deleteRule = async (rule, filteredRecords) => {
  const { id, display_id, rule_id, automation_type_id } = rule;

  console.log("Entire filtered records from this tab at initialization:", filteredRecords);

  // Find matching filteredRecord by comparing rule.id (API ruleid) with filteredRecords ids
  const matchedRecord = filteredRecords.find(rec => rec.id === id);

  if (matchedRecord) {
    console.log("✅ Matched filtered record:", matchedRecord);
    console.log("Matched record's display_id:", matchedRecord.display_id);
  } else {
    console.warn("⚠️ No matching filtered record found for rule id:", id);
  }

  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 - display_id:", rule.display_id);
  console.log("Entity - rule_id:", rule_id);
  console.log("Entity - automation_type_id:", automation_type_id);

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

  // Use matchedRecord.display_id if matchedRecord exists, else fallback to rule.display_id or undefined
  const targetDisplayId = matchedRecord.display_id;

  console.log("Record to be deleted :", targetDisplayId);

  if (targetDisplayId && newRulePloadDB5.current) {
    
    try {
      await newRulePloadDB5.current.delete(targetDisplayId);
      console.log("✅ Successfully deleted entity record with display_id:", targetDisplayId);
    } catch (err) {
      console.error("❌ Error deleting entity record:", err);
    }

  } else if (!newRulePloadDB5.current) {
    console.error("❌ Entity DB reference not initialized yet.");
  }

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

    if (response.status === 204) {
      console.log("Rule deleted successfully!");
      if (activeTab === "ticketcreate") {
        setTicketCreationRules(ticketCreationRules.filter(r => r.id !== id));
      } else if (activeTab === "ticketupdate") {
        setTicketUpdateRules(ticketUpdateRules.filter(r => r.id !== id));
      } else if (activeTab === "hourly") {
        setHourlyTriggerRules(hourlyTriggerRules.filter(r => r.id !== id));
      }
    
      toast.current.trigger({ type: "success", content: "Rule deleted successfully!" });
    
    } else {
      console.error("Failed to delete rule.");      
      toast.current.trigger({ type: "error", content: "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>
      )}

<FwToast />

    </>
  );
};

export default AutomationTabs;


import React, { useState, useEffect, useRef } from "react";
import {
  FwToggle,
  FwButton,
  FwModal,
  FwModalTitle,
  FwModalContent,
  FwModalFooter,
} from "@freshworks/crayons/react";

// Calculate time since updated
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";
};

// SummaryContent component — improved to handle empty or incorrect data gracefully
const SummaryContent = ({ ruleObj }) => {
  const [summary, setSummary] = useState(null);

  const SetText = ({ ele }) => {
    const ref = useRef(null);

    useEffect(() => {
      if (ref.current) {
        if (!ele) {
          ref.current.innerHTML = "";
          return;
        }
        if (Array.isArray(ele)) {
          ref.current.innerHTML = ele.join(" ");
        } else if (typeof ele === "string") {
          ref.current.innerHTML = ele;
        } else {
          // fallback for unexpected data type
          ref.current.innerHTML = "";
        }
      }
    }, [ele]);

    return (
      <div
        style={{ display: "flex", gap: "5px", marginLeft: "10px" }}
        ref={ref}
      />
    );
  };

  useEffect(() => {
    if (ruleObj && ruleObj.summary && typeof ruleObj.summary === "object") {
      setSummary(ruleObj.summary);
    } else {
      setSummary(null);
    }
  }, [ruleObj]);

  if (!summary) {
    // show a fallback message if no summary available
    return <div style={{ fontStyle: "italic" }}>Summary not available.</div>;
  }

  return (
    <div className="summary_text" style={{ fontFamily: "Arial, sans-serif" }}>
      <h3>Summary</h3>
      <div
        className="fw-flex fw-flex-column"
        style={{ fontWeight: "600", gap: "15px" }}
      >
        <div
          className="flex-item-border fw-flex-grow"
          style={{ borderBottom: "1px solid #ccc", paddingBottom: "10px" }}
        >
          <div
            style={{
              backgroundColor: "#475867",
              color: "#fff",
              padding: "5px 10px",
              fontWeight: 600,
              borderRadius: "3px",
              marginBottom: "5px",
              fontSize: "14px",
            }}
          >
            Conditions
          </div>
          <div style={{ display: "flex", alignItems: "baseline" }}>
            <span className="list-icon"></span>
            <div style={{ marginLeft: "10px" }}>
              When <span style={{ fontWeight: "600" }}>Ticket</span> is{" "}
              <span style={{ color: "#007958" }}>created</span>
            </div>
          </div>
        </div>
        <div
          className="flex-item-border fw-flex-grow"
          style={{ borderBottom: "1px solid #ccc", paddingBottom: "10px" }}
        >
          <div style={{ display: "flex", alignItems: "baseline" }}>
            <span className="list-icon"></span>
            <SetText ele={summary.conditions?.condition_set_1} />
          </div>
        </div>
        <div className="flex-item-border fw-flex-grow">
          <div
            style={{
              backgroundColor: "#475867",
              color: "#fff",
              padding: "5px 10px",
              fontWeight: 600,
              borderRadius: "3px",
              marginBottom: "5px",
              fontSize: "14px",
            }}
          >
            Actions
          </div>
          <div style={{ display: "flex", alignItems: "baseline" }}>
            <span className="list-icon"></span>{" "}
            <SetText ele={summary.actions} />
          </div>
        </div>
      </div>
    </div>
  );
};

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); // delete confirmation modal
  const [summaryOpen, setSummaryOpen] = useState(false); // summary modal

  const handleConfirmDelete = () => {
    setModalOpen(false);
    onDelete(rule);
  };

  const stopPropagation = (e) => e.stopPropagation();

  const openSummary = () => {
    setSummaryOpen(true);
    setMenuOpen(false);
  };

  const renderAgentName = () => {
    const foundAgent = agent.find((e) => e.value === last_updated_by);
    return foundAgent ? foundAgent.text : last_updated_by || "Unknown";
  };

  return (
    <>
      <div
        className="fw-card-1 fw-flex fw-flex-column"
        style={{
          overflow: "hidden",
          border: "0.5px solid #ddd",
          backgroundColor: isFirstInGroup ? "#fff" : "#e5f2fd",
          cursor: "pointer",
          userSelect: "none",
        }}
        onClick={openSummary}
      >
        <section
          className="fw-flex-grow fw-px-16 fw-flex fw-flex-row"
          style={{ justifyContent: "space-between", alignItems: "center" }}
          onClick={stopPropagation}
        >
          <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",
            }}
            onClick={stopPropagation}
          >
            <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);
                      setMenuOpen(false);
                    }}
                  >
                    Delete
                  </div>
                </div>
              )}
              <div
                className="ember-basic-dropdown-trigger"
                role="button"
                tabIndex="0"
                onClick={(e) => {
                  e.stopPropagation();
                  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",
          }}
          onClick={stopPropagation}
        >
          <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: {renderAgentName()}</span>
            <span>|</span>
            <span>Impacted tickets (Last 7 days): {affected_tickets_count}</span>
          </div>
        </section>
      </div>

      {/* Delete Confirmation */}
      <FwModal open={modalOpen} onFwClose={() => setModalOpen(false)}>
        <FwModalTitle>Confirm Delete</FwModalTitle>
        <FwModalContent>
          Are you sure you want to delete the rule <strong>{name}</strong>?
        </FwModalContent>
        <FwModalFooter>
          <FwButton onClick={() => setModalOpen(false)}>Cancel</FwButton>
          <FwButton variant="danger" onClick={handleConfirmDelete}>
            Delete
          </FwButton>
        </FwModalFooter>
      </FwModal>

      {/* Summary Modal */}
      <FwModal
        open={summaryOpen}
        onFwClose={() => setSummaryOpen(false)}
        style={{ maxWidth: "600px" }}
      >
        <FwModalTitle>{name} - Summary</FwModalTitle>
        <FwModalContent>
          <SummaryContent ruleObj={rule} />
        </FwModalContent>
        <FwModalFooter>
          <FwButton onClick={() => setSummaryOpen(false)}>Close</FwButton>
        </FwModalFooter>
      </FwModal>
    </>
  );
};

export default AutomationCard;




on clicking delete why it is not working?