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

const getRuleSignature = (rule) => {
    return 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] = [{ ...rule, isFirstInGroup: true }];
        } else {
            grouped[signature].push({ ...rule, isFirstInGroup: false });
        }
    });
    return Object.values(grouped).flat();
};

const ITEMS_PER_PAGE = 30;

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({
        ticketcreate: 1,
        ticketupdate: 1,
        hourly: 1
    });

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

    useEffect(() => {
        fetchRules();
    }, [client]);

    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 renderCards = (groups) => {
        if (loading) {
            return (
                <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '200px' }}>
                    <FwSpinner size="medium" color="green" />
                </div>
            );
        }

        const startIndex = (currentPage[activeTab] - 1) * ITEMS_PER_PAGE;
        const currentRules = groups.slice(startIndex, startIndex + ITEMS_PER_PAGE);

        return currentRules.length > 0 ? (
            currentRules.map((rule, index) => (
                <div key={rule.id} className="fw-card-1 fw-py-16">
                    <AutomationCard rule={rule} index={index + 1 + startIndex} isFirstInGroup={rule.isFirstInGroup} />
                </div>
            ))
        ) : (
            <p style={{ textAlign: "center", marginTop: "20px" }}>No Rules Found Matched Your Search: {searchTerm}</p>
        );
    };

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

    const groups = getFilteredGroups(getRulesByTab());
    const totalPages = Math.ceil(groups.length / ITEMS_PER_PAGE);

    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({ ...currentPage, [activeTab]: 1 }); }}>Search</button>

            <FwButton color="primary" onClick={fetchRules} style={{ marginLeft: "10px" }}>
                Recent Data
            </FwButton>

            <FwTabs onFwChange={(e) => {
                const selectedTab = e.target.panel;
                setActiveTab(selectedTab);
                setCurrentPage((prevState) => ({
                    ...prevState,
                    [selectedTab]: prevState[selectedTab] || 1
                }));
            }}>
                <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">
                    {renderCards(groups)}
                </FwTabPanel>

                <FwTabPanel name="ticketupdate">
                    {renderCards(groups)}
                </FwTabPanel>

                <FwTabPanel name="hourly">
                    {renderCards(groups)}
                </FwTabPanel>
            </FwTabs>

            {totalPages > 1 && (
                <FwPagination
                    per-page={ITEMS_PER_PAGE}
                    total={groups.length}
                    page={currentPage[activeTab]}
                    onFwChange={(event) =>
                        setCurrentPage((prevState) => ({
                            ...prevState,
                            [activeTab]: event.detail.page
                        }))
                    }
                />
            )}
        </>
    );
};

export default AutomationTabs;






when i change tab it removes data in tab inside render why?