import React, { useState, useEffect } from "react";
import { FwTabs, FwTab, FwTabPanel, FwSpinner, FwPagination } 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] = [];
        }
        grouped[signature].push(rule);
    });
    return Object.values(grouped); 
};

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(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((group) => 
            group.some(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 flatRules = groups.flat(); 
        const startIndex = (currentPage - 1) * ITEMS_PER_PAGE; 
        const currentRules = flatRules.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" style={{ marginBottom: "20px" }}>
                    <AutomationCard rule={rule} index={index + 1 + startIndex} />
                </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.flat().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(1); }}>Search</button>

            <FwTabs onFwChange={(e) => {
                setActiveTab(e.target.panel);
                setCurrentPage(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.flat().length} 
                    onFwChange={(event) => setCurrentPage(event.detail.page)}
                />
            )}
        </>
    );
};

export default AutomationTabs;



in this default by default use state ticketcreate is there. when i change to ticketupdate/hourlytriggers it should make that tab as usestate to show its details