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

const getRuleSignature = (rule) => JSON.stringify({
  conditions: rule.summary.conditions,
  actions: rule.summary.actions,
});

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 [ticketCreationRules, setTicketCreationRules] = useState([]);
  const [ticketUpdateRules, setTicketUpdateRules] = useState([]);
  const [hourlyTriggerRules, setHourlyTriggerRules] = useState([]);

  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);

  const rulesPerPage = 5;

  useEffect(() => {
    const fetchRules = async () => {
      console.log("Initializing database...");
      console.log("Hii", client);
      const entity = await client.db.entity({ version: "v1" });
      console.log("Entity Initialized:", entity);

      const newRulePloadDB3 = entity.get("newRulePloadDB3");
      console.log("📌 Entity Reference:", newRulePloadDB3);

      const data1 = await newRulePloadDB3.schema();
      console.log("📄 Schema Data:", data1);

      const entitydata = await newRulePloadDB3.getAll();
      console.log("Stored Data :", entitydata);

      setLoading(true);
      await Promise.all([
        getTicketCreationRules(client, setTicketCreationRules),
        getTicketUpdationRules(client, setTicketUpdateRules),
        getHourlyRules(client, setHourlyTriggerRules),
      ]);
      setLoading(false);
    };
    fetchRules();
  }, [client]);

  useEffect(() => {
    setCurrentPage(1);
  }, [activeTab]);

  const getFilteredGroups = (rules) => {
    const groupedRules = groupDuplicates(rules);
    if (!searchTriggered || !searchTerm.trim()) return groupedRules;

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

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

  const getRulesByTab = () => {
    switch (activeTab) {
      case "ticketcreate":
        return ticketCreationRules;
      case "ticketupdate":
        return ticketUpdateRules;
      case "hourly":
        return hourlyTriggerRules;
      default:
        return [];
    }
  };

  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> {/* Trigger search on click */}

      <FwTabs onFwChange={(e) => 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(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;

why search is not performing correctly it should check name and description it does not please check why and fix the issue