import React, { useState, useEffect } from "react";
import { FwTabs, FwTab, FwTabPanel, FwSpinner } from "@freshworks/crayons/react";
import AutomationCard from "./AutomationCard";

// 🔹 Helper: Generate unique signature for duplicate detection
const getRuleSignature = (rule) => JSON.stringify({
  conditions: rule.conditions,
  actions: rule.actions,
});

// 🔹 Helper: Group duplicate rules
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);
};

// 🔹 Fetch filtered records based on automation type
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 AutomationTabs = ({ client }) => {
  const [searchTerm, setSearchTerm] = useState("");
  const [searchTriggered, setSearchTriggered] = useState(false);
  const [activeTab, setActiveTab] = useState("ticketcreate");
  const [rules, setRules] = useState({ ticketcreate: [], hourly: [], ticketupdate: [] });
  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const rulesPerPage = 5;

  // ✅ Fetch and categorize rules
  useEffect(() => {
    const fetchRules = async () => {
      setLoading(true);
      try {
        const entity = await client.db.entity({ version: "v1" });
        const newRulePloadDB3 = entity.get("newRulePloadDB3");

        const ticketcreate = await Filterrecords(1, newRulePloadDB3);
        const hourly = await Filterrecords(3, newRulePloadDB3);
        const ticketupdate = await Filterrecords(4, newRulePloadDB3);

        console.log("Ticket Create :", ticketcreate);
        console.log("Ticket Update :", ticketupdate);
        console.log("Ticket Hourly Triggers :", hourly);

        setRules({ ticketcreate, hourly, ticketupdate });

        console.log("🚀 Updated Rules State:", { ticketcreate, hourly, ticketupdate });
      } catch (error) {
        console.error("❌ Error fetching rules:", error);
      }
      setLoading(false);
    };

    fetchRules();
  }, [client]);

  // ✅ Reset pagination when switching tabs
  useEffect(() => {
    setCurrentPage(1);
  }, [activeTab]);

  // ✅ Filter & group rules based on active tab
  const getFilteredGroups = () => {
    const activeRules = rules[activeTab] || [];
    const groupedRules = groupDuplicates(activeRules);

    console.log(`📌 Active Tab: ${activeTab}, Grouped Rules:`, groupedRules);

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

  // ✅ Render grouped rules with pagination
  const renderGroupedRules = (groups) => {
    console.log("🔹 Rendering Groups:", groups);

    if (loading) {
      return (
        <div style={{ display: "flex", justifyContent: "center", alignItems: "center", height: "200px" }}>
          <FwSpinner size="medium" color="green" />
        </div>
      );
    }

    const startIndex = (currentPage - 1) * rulesPerPage;
    const paginatedGroups = groups.slice(startIndex, startIndex + rulesPerPage);

    return paginatedGroups.length > 0 ? (
      paginatedGroups.map((group, index) => (
        <div
          key={index}
          className="fw-card-1"
          style={{
            border: "1px solid #ddd",
            borderRadius: "8px",
            marginBottom: "20px",
            padding: "10px 16px",
            boxShadow: "0 4px 8px rgba(0, 0, 0, 0.1)",
            width: "80%",
            marginLeft: "auto",
            marginRight: "auto",
          }}
        >
          {group.map((rule, idx) => {
            console.log(`📌 Rule for AutomationCard (Tab: ${activeTab}):`, rule);
            return <AutomationCard key={idx} rule={rule} index={idx + 1} isFirstInGroup={idx === 0} />;
          })}
        </div>
      ))
    ) : (
      <p style={{ textAlign: "center", marginTop: "20px" }}>
        No Rules Found Matching Your Search: {searchTerm}
      </p>
    );
  };

  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)}>Search</button>

      <FwTabs
        onFwChange={(e) => {
          console.log("🔄 Tab Changed:", e.target.panel);
          setActiveTab(e.target.panel);
        }}
      >
        <FwTab slot="tab" panel="ticketcreate">Ticket Create</FwTab>
        <FwTab slot="tab" panel="ticketupdate">Ticket Update</FwTab>
        <FwTab slot="tab" panel="hourly">Hourly Triggers</FwTab>

        <FwTabPanel name="ticketcreate">{renderGroupedRules(getFilteredGroups())}</FwTabPanel>
        <FwTabPanel name="ticketupdate">{renderGroupedRules(getFilteredGroups())}</FwTabPanel>
        <FwTabPanel name="hourly">{renderGroupedRules(getFilteredGroups())}</FwTabPanel>
      </FwTabs>
    </>
  );
};

export default AutomationTabs;


why ticketcreate, ticketupdate and hourlytrigger not creating card after grouping