import React, { useState, useEffect, useRef } from "react";
import {
  FwTabs,
  FwTab,
  FwTabPanel,
  FwSpinner,
  ToastController,
  FwToast, FwButton, FwModal, FwPagination
} from "@freshworks/crayons/react";
import AutomationCard from "./AutomationCard";
import SummaryContent from "./SummaryContent";  
import { getTicketCreationRules, getTicketUpdationRules, getHourlyRules, getAgents, pagination } from '../common';

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 getRuleSignature = (rule) => {
  const conditions = rule.summary?.conditions || rule.conditions;
  const actions = rule.summary?.actions || rule.actions;
  return JSON.stringify({
    conditions,
    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,
        rule_id: record.data.rule_id,
        automation_type_id: record.data.automation_type_id,
        id: record.data.rule_id || record.data.id,
      })));

      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 [isRulesDBReady, setIsRulesDBReady] = useState(false); 
  const [loadingBannerVisible, setLoadingBannerVisible] = useState(true); 

  const intervalIdRef = useRef(null); 
  const [showSearchHint, setShowSearchHint] = useState(false);

  const [searchTerm, setSearchTerm] = useState("");
  const [searchQuery, setSearchQuery] = 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 rulesPerPage = 30;

const [currentPage, setCurrentPage] = useState({
  ticketcreate: 1,
  ticketupdate: 1,
  hourly: 1
});


  const toast = useRef(ToastController({ position: "top-right" }));

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

  const [selectedRule, setSelectedRule] = useState(null);

  const newRulePloadDB5 = useRef(null);

  // const rulesPerPage = 5;

  const ticketCreate = 1;
  const ticketUpdate = 4;
  const hourlyTriggers = 3;

  const [fetchFromApi, setFetchFromApi] = useState(true);

  useEffect(() => {
    const initializeDatabase = async () => {
      console.log("🟡 Initializing database and fetching tabs...");
      const entity = await client.db.entity({ version: "v1" });
      newRulePloadDB5.current = entity.get("newRulePloadDB5");

      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(() => {
    setCurrentPage((prev) => ({
      ...prev,
      [activeTab]: 1
    }));
    // Optionally, reset searchTerm/searchQuery too.
  }, [activeTab]);

  const handlePageChange = (tab) => (event) => {
    setCurrentPage((prev) => ({
      ...prev,
      [tab]: event.detail.page
    }));
  };


  const getPaginatedRules = (rules, tab) => {
    const filtered = getFilteredRules(rules);
    // Your pagination utility: expects 1-based page numbers.
    return pagination(filtered, currentPage[tab]);
  };


  useEffect(() => {
    checkAndSetButtonState();

    return () => {
      if (intervalIdRef.current) clearInterval(intervalIdRef.current);
    };
  }, []);

  
  useEffect(() => {
    const fwTabs = document.querySelector("fw-tabs");

    const saveActiveTab = async (e) => {
      const newActiveTab = e.target.panel;
      setActiveTab(newActiveTab);

      try {
        let tabData = await client.db.get("TabDB") || {};
        tabData.LastVisitedTab = newActiveTab;
        await client.db.set("TabDB", tabData);
      } 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 fetchData = async () => {
    setLoading(true);
  
    if (fetchFromApi) {
      await Promise.all([
        getTicketCreationRules(client, (data) => {
          console.log("🎯 Ticket Creation Rules from API:", data[1]);
          setTicketCreationRules(data);
        }),
        getTicketUpdationRules(client, (data) => {
          console.log("🔁 Ticket Update Rules from API:", data[1]);
          setTicketUpdateRules(data);
        }),
        getHourlyRules(client, (data) => {
          console.log("⏰ Hourly Trigger Rules from API:", data[1]);
          setHourlyTriggerRules(data);
        }),
        getAgents(client, (data) => {
          console.log("👥 Agents from API:", data);
          setAgent(data);
        }),
      ]);
    } else {
      if (!newRulePloadDB5.current) {
        console.error("❌ Entity DB reference not initialized.");
        setLoading(false);
        return;
      }
  
      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;
  
      console.log("🎯 Ticket Creation Rules (Filtered):", entticketcreate);
      console.log("🔁 Ticket Update Rules (Filtered):", entticketupdate);
      console.log("⏰ Hourly Trigger Rules (Filtered):", enthourly);
  
      setTicketCreationRules(entticketcreate);
      setTicketUpdateRules(entticketupdate);
      setHourlyTriggerRules(enthourly);
    }
  
    setLoading(false);
    setFetchFromApi(!fetchFromApi);
  };
  
  const checkAndSetButtonState = async () => {
    try {
      const storedvalue1 = await client.db.get("RulesDB");
      const isButtonEnabled = !!storedvalue1.stored;
      if (isButtonEnabled) {
        setIsRulesDBReady(true);
        setLoadingBannerVisible(false);

        if (intervalIdRef.current) {
          clearInterval(intervalIdRef.current);
          intervalIdRef.current = null;
        }
      } else {
        setIsRulesDBReady(true);
        setLoadingBannerVisible(false);
        if (!intervalIdRef.current) {
          intervalIdRef.current = setInterval(checkAndSetButtonState, 60000);
        }
      }
    } catch (error) {
      if (error.status === 404) {
        setIsRulesDBReady(true);
        setLoadingBannerVisible(false);
        if (intervalIdRef.current) {
          clearInterval(intervalIdRef.current);
          intervalIdRef.current = null;
        }
      } else {
        console.error("❌ Error retrieving stored value from RulesDB:", error);
      }
    }
  };

  // --- New simple filtering for single rules ---
  const getFilteredRules = (rules) => {
    if (!searchQuery.trim()) return rules;

    return rules.filter(
      (rule) =>
        rule.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
        rule.description?.toLowerCase().includes(searchQuery.toLowerCase())
    );
  };

  const renderRules = (rules) => {
    const filtered = getFilteredRules(rules);
  
    if (loading) {
      return (
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '200px' }}>
          <FwSpinner size="medium" color="green" />
        </div>
      );
    }
  
    return filtered.length > 0 ? (
      filtered.map((rule, idx) => (
        <div
          key={rule.id || idx}
          className="fw-card-1"
          style={{
            marginBottom: "5px",
            marginTop: "10px",
            padding: "5px 8px",
            width: "80%",
            marginLeft: "auto",
            marginRight: "auto",
          }}
        >
          <AutomationCard
            rule={rule}
            index={idx + 1} // Now just idx + 1
            isFirstInGroup={true}
            onDelete={(rule) => deleteRule(rule, getFilteredRecordsForActiveTab())}
            activeTab={activeTab}
            onSelect={openRuleDetails}
            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;
    const matchedRecord = filteredRecords.find(rec => rec.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;
    }

    const targetDisplayId = matchedRecord ? matchedRecord.display_id : undefined;

    if (targetDisplayId) {
      try {
        const delete_ent_rule = await newRulePloadDB5.current.delete(targetDisplayId);
        console.log("✅ Successfully deleted entity record with display_id:", delete_ent_rule);

      } 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) {
        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 {
        toast.current.trigger({ type: "error", content: "Failed to delete rule." });
      }

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

  const openRuleDetails = (rule) => {
    setSelectedRule(rule);
  };

  const closeRuleDetails = () => {
    setSelectedRule(null);
  };

  return (
    <>
      <h2>Automations - Rules</h2>

      <div>
        {/* <FwButton modalTriggerId='welcome'> Open Modal </FwButton>
        <FwModal id='welcome' submit-text="Delete" submit-color="danger" titleText="Delete message">
        Are you sure you want to delete this Automation Rule?
        </FwModal>     */}
        <FwButton color="secondary"> Filter API (Based on Duplicates (High to Low)) </FwButton>
      </div>

      <input
        type="text"
        placeholder="Search by name or description"
        value={searchTerm}
        onChange={(e) => {
          setSearchTerm(e.target.value);
          if (showSearchHint) setShowSearchHint(false);
        }}
      />
      
      <button
        onClick={() => {
          if (!searchTerm.trim()) {
            setShowSearchHint(true);
            return;
          }
          setShowSearchHint(false);
          setSearchQuery(searchTerm);
          // setCurrentPage(1);
        }}
      >
        Search
      </button>

      {showSearchHint && (
        <p style={{ color: 'red', marginTop: '4px', fontSize: '0.9em' }}>
          Please enter a search term before searching.
        </p>
      )}

      {loadingBannerVisible && !isRulesDBReady && (
        <div style={{ display: "flex", alignItems: "center", margin: "20px 0" }}>
          <FwSpinner size="medium" color="green" />
          <span style={{ marginLeft: "8px" }}>
            Waiting for rules to be ready...
          </span>
        </div>
      )}

<FwButton
  color="secondary"
  onFwClick={fetchData}
  disabled={!isRulesDBReady}
>
  {fetchFromApi ? "Recent API Data" : "Get Entity Data"}
</FwButton>

      {isRulesDBReady && 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">
  {renderRules(getPaginatedRules(ticketCreationRules, "ticketcreate"))}
  <div style={{ display: "flex", justifyContent: "center", marginTop: "10px" }}>
  <FwPagination
    per-page={rulesPerPage}
    total={getFilteredRules(ticketCreationRules).length}
    page={currentPage.ticketcreate}
    onFwChange={handlePageChange("ticketcreate")}
  />
</div>

</FwTabPanel>

<FwTabPanel name="ticketupdate">
  {renderRules(getPaginatedRules(ticketUpdateRules, "ticketupdate"))}
  <div style={{ display: "flex", justifyContent: "center", marginTop: "10px" }}>
  <FwPagination
    per-page={rulesPerPage}
    total={getFilteredRules(ticketUpdateRules).length}
    page={currentPage.ticketupdate}
    onFwChange={handlePageChange("ticketupdate")}
  />
</div>

</FwTabPanel>

<FwTabPanel name="hourly">
  {renderRules(getPaginatedRules(hourlyTriggerRules, "hourly"))}
  <div style={{ display: "flex", justifyContent: "center", marginTop: "10px" }}>
  <FwPagination
    per-page={rulesPerPage}
    total={getFilteredRules(hourlyTriggerRules).length}
    page={currentPage.hourly}
    onFwChange={handlePageChange("hourly")}
  />
</div>
</FwTabPanel>

        </FwTabs>
      )}

      <FwToast />
    </>
  );
};

export default AutomationTabs;

groupduclicate work in this code when user click filter api