import React, { useState, useEffect, useRef  } 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 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 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("Entity display_id:", rule.display_id);
  //   console.log("Entity display_id:", display_id);

  //   console.log("Entire filtered records from this tab at initialization:", filteredRecords);
    
  //   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);

  //   // if (display_id) {
  //   //   try {
  //   //     await newRulePloadDB5.delete(display_id);
  //   //     console.log("✅ Successfully deleted entity record with display_id:", display_id);
  //   //   } catch (err) {
  //   //     console.error("❌ Error deleting entity record:", err);
  //   //   }
  //   // } else {
  //   //   console.warn("⚠️ No matching entity display_id found for deletion.");
  //   // }

  //   if (display_id && newRulePloadDB5.current) {
  //     try {
  //       await newRulePloadDB5.current.delete(display_id);
  //       console.log("✅ Successfully deleted entity record with display_id:", display_id);
  //     } 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!");
  //       // Update state based on activeTab
  //       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));
  //       }
  //     } else {
  //       console.error("Failed to delete rule.");
  //     }


      
  //   } catch (error) {
  //     console.error("Error deleting rule:", error);
  //   }


  // };

  // 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);
  //   }
  
  //   // rest of your delete logic unchanged...
    
  //   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);
  
  //   if (display_id && newRulePloadDB5.current) {
  //     try {
  //       await newRulePloadDB5.current.delete(display_id);
  //       console.log("✅ Successfully deleted entity record with display_id:", display_id);
  //     } 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));
  //       }
  //     } else {
  //       console.error("Failed to delete rule.");
  //     }
  //   } catch (error) {
  //     console.error("Error deleting rule:", error);
  //   }
  // };

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

  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));
      }
    } 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, {useRef, useEffect} from "react";
import ReactDOM from "react-dom";
import { FwButton, ToastController, FwToast, FwToastMessage } from "@freshworks/crayons/react";
function App() {
  const el = useRef(null);
  const el1 = useRef(null);
  const toast = ToastController({ position:'top-right'})

  useEffect(() => {
   el1.current.onclick = function() {
     console.log("custom action handled here");
   }
  },[])

  return (<div>

          <FwToastMessage type='success' id="custom-temp">
            <div>
              <FwButton onclick={()=> console.log("custom action here")}>custom action element</FwButton>
              <FwButton ref={el1}>custom action element in Typescript apps</FwButton>
              <p> Please make sure here in the above element, the event handler name is in lowercase. use `onclick` instead of `onClick`. </p>
              <p className="cus-style">custom style element</p>
            </div>
          </FwToastMessage>

          <FwToastMessage
          type='success'
          id='custom-toast1'
          sticky
          action-link-text='Click me'
        >
          <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
            <span
              style={{
                fontStyle: 'normal',
                fontWeight: '700',
                fontSize: '14px',
                lineHeight: '20px',
                color: '#12344D',
              }}
            >
              Test content
            </span>
            <span
              style={{
                fontStyle: 'normal',
                fontWeight: '400',
                fontSize: '12px',
                lineHeight: '16px',
              }}
            >
              custom html contents can be added
            </span>
          </div>
        </FwToastMessage>

          <FwToast id="type_toast" ref={el} timeout={5000}></FwToast>

          <FwButton onClick={()=> toast.trigger({type:'success', content: 'Successfullly triggered'})}>Success</FwButton>
          <FwButton onClick={()=> el.current.trigger({type:'error', content:'something went wrong!'})}>Error</FwButton>
          <FwButton onClick={()=> el.current.trigger({type:'warning', content:'This is a warning!'})}>Warning</FwButton>
          <FwButton onClick={()=> el.current.trigger({type:'inprogress', content:'Request is in progress'})}>Inprogress</FwButton>
          <FwButton onClick={() => toast.trigger({contentref:'#custom-temp'})}>trigger custom </FwButton>

          <FwButton onClick={() => toast.trigger({contentref:'#custom-toast1'})}>trigger custom 1 </FwButton>
    </div>);
}


on deleting successfully, show success toast