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

      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),
    ]);
    setLoading(false);
  };

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

  const deleteRule = async (ruleId) => {
    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("Deleting Rule ID:", ruleId);
    console.log("From Tab:", activeTab);
    console.log("Automation Type ID:", automationTypeId);

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

      if (response.status === 204) {
        console.log("Rule deleted successfully!");
        const updatedRules = ticketCreationRules.filter(rule => rule.id !== ruleId);
        setTicketCreationRules(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;