import * as React from 'react';
// import React, { useState, useEffect } from 'react';
import { FwButton, FwTabs, FwTab, FwTabPanel, FwIcon, FwToggle, FwPagination } from "@freshworks/crayons/react";
//import { search } from '@freshworks/crayons-icon';
import { getTicketCreationRules, getTicketUpdationRules, getHourlyRules, getAgents, pagination } from '../common';
import moment from 'moment';

// const DisplayText = ({ text }) => {
//     // Remove HTML tags using a regular expression
//     const removedText = text.replace(/<\/?[^>]+(>|$)/g, "");

//     return <div>{removedText}</div>;
// };

function ShowMenuList() {
    console.log("ShowMenuList", ShowMenuList);
    return (
        <>
            <div></div>
        </>
    )

}

function htmlToText(html) {
    var temp = document.createElement('div');
    temp.innerHTML = html;
    return temp.textContent; // Or return temp.innerText if you need to return only visible text. It's slower.
}


function TicketCreation({ ticketCreationRules, agentsList }) {

    const [data, setData] = React.useState([]);

    const ListConditions = (element) => {

        const valuesOfCondStr = Object.values(element.summary.conditions).map(e => {
            if (Array.isArray(e) && e.length) {
                return htmlToText(e[0]);
            }
            return e;
        }).join(" ");

        const actionsToStr = element.summary.actions.map((action, index) => (
            htmlToText(action)
        )).join(" ")
        return [valuesOfCondStr, actionsToStr].join(" ")
    }

    const changePage = (event) => {
        const res = pagination(ticketCreationRules, event.detail.page);
        setData(res);
    }

    React.useEffect(() => {
        if (ticketCreationRules.length) {
            const res = pagination(ticketCreationRules);
            setData(res);
        }
    }, [ticketCreationRules])

    if (data.length) {

        return (<>
            {data.map(element => {


                return <><div key={element.id} className="rule-top">
                    <div className='semi-bold'><span>{element.position}</span><span>.</span><span>{element.name}</span></div>
                    <div style={{ display: 'flex', alignItems: 'baseline', flexDirection: 'row' }}>
                        {ListConditions(element)}
                        <div style={{ verticalAlign: 'middle', marginLeft: '30px' }}> {element.active ? <FwToggle size="medium" checked></FwToggle> : <FwToggle size="medium"></FwToggle>}
                        </div>

                        <div style={{ verticalAlign: 'middle', margin: '0 0 0 10px' }}>  <FwButton style={{ marginTop: '20px' }} size="icon" color="secondary" onFwClick={() => ShowMenuList()}><FwIcon name="more-vertical" size={18} color="black" ></FwIcon></FwButton>
                        </div>
                    </div>
                    <div className="timeShow" style={{ display: 'flex', alignItems: 'baseline', fontSize: '12px' }}>
                        <div className='date-show'><span className='color-change'>Last Modified:</span>
                            <span className='semi-bold'>{moment(element.updated_at).fromNow()}</span></div>
                        <div className='date-show' style={{ textAlign: 'center' }}><span className='color-change'>By :</span><span className='semi-bold'>{agentsList.map(e => {
                            if (e.value === element.last_updated_by)
                                return e.text
                        })}</span></div>
                        <div className='date-show' style={{ width: '32%', padding: '0 20px 0 0', textAlign: 'center' }}><span className='color-change'>Impacted tickets (Last 7 days):</span><span className='semi-bold'>{(element.affected_tickets_count === 0) ? '--' : element.affected_tickets_count}</span></div>
                    </div>


                </div>

                </>
            })}
            <div>
                <FwPagination per-page="30" total={ticketCreationRules.length} onFwChange={changePage}></FwPagination><br />
            </div>
        </>);
    }
    return null;
}

function TicketUpdation({ ticketUpdaionRules, agentsList }) {

    const [data, setData] = React.useState([]);

    const changePage = (event) => {
        const res = pagination(ticketUpdaionRules, event.detail.page);
        setData(res);
    }

    React.useEffect(() => {
        if (ticketUpdaionRules.length) {
            const res = pagination(ticketUpdaionRules);
            setData(res);
        }
    }, [ticketUpdaionRules])

    if (data.length) {

        // const ListConditions = (element) => {
        //     const typeofObj = element.summary.conditions.condition_set_1;
        //     if (Array.isArray(typeofObj)) {
        //         return typeofObj.map((condition, index) => (
        //             <DisplayText key={index} text={condition} />
        //         ))
        //     }
        //     return null;
        // }
        const ListConditions = (element) => {

            const valuesOfCondStr = Object.values(element.summary.conditions).map(e => {
                if (Array.isArray(e) && e.length) {
                    return htmlToText(e[0]);
                }
                return e;
            }).join(" ");

            const actionsToStr = element.summary.actions.map((action, index) => (
                htmlToText(action)
            )).join(" ")
            return [valuesOfCondStr, actionsToStr].join(" ")
        }

        return (<>
            {data.map(element => {

                return <div key={element.id} className="rule-top">
                    <div className='semi-bold'><span>{element.position}</span><span>.</span><span>{element.name}</span></div>
                    <div style={{ display: 'flex', alignItems: 'baseline' }}>
                        {ListConditions(element)}

                        <div style={{ verticalAlign: 'middle', marginLeft: '30px' }}> {element.active ? <FwToggle size="medium" checked></FwToggle> : <FwToggle size="medium"></FwToggle>}
                        </div>

                        <div style={{ verticalAlign: 'middle', margin: '0 0 0 10px' }}>  <FwButton style={{ marginTop: '20px' }} size="icon" color="secondary" onFwClick={() => ShowMenuList()}><FwIcon name="more-vertical" size={18} color="black" ></FwIcon></FwButton>
                        </div>
                    </div>
                    <div className="timeShow" style={{ display: 'flex', alignItems: 'baseline', fontSize: '12px' }}>
                        <div className='date-show'><span className='color-change'>Last Modified:</span>
                            <span className='semi-bold'>{moment(element.updated_at).fromNow()}</span></div>
                        <div className='date-show' style={{ textAlign: 'center' }}><span className='color-change'>By :</span><span className='semi-bold'>{agentsList.map(e => {
                            if (e.value === element.last_updated_by)
                                return e.text
                        })}</span></div>
                        <div className='date-show' style={{ textAlign: 'center' }}><span className='color-change'>Impacted tickets (Last 7 days):</span><span className='semi-bold'>{(element.affected_tickets_count === 0) ? '--' : element.affected_tickets_count}</span></div>
                    </div>
                </div>
            })}
            <div>
                <FwPagination per-page="30" total={ticketUpdaionRules.length} onFwChange={changePage}></FwPagination><br />
            </div>
        </>);
    }
    return null;
}

function HourlyTriggers({ hourlyTriggerRules, agentsList }) {

    const [data, setData] = React.useState([]);

    const changePage = (event) => {
        const res = pagination(hourlyTriggerRules, event.detail.page);
        setData(res);
    }

    React.useEffect(() => {
        if (hourlyTriggerRules.length) {
            const res = pagination(hourlyTriggerRules);
            setData(res);
        }
    }, [hourlyTriggerRules])


    const ListConditions = (element) => {

        const valuesOfCondStr = Object.values(element.summary.conditions).map(e => {
            if (Array.isArray(e) && e.length) {
                return htmlToText(e[0]);
            }
            return e;
        }).join(" ");

        const actionsToStr = element.summary.actions.map((action, index) => (
            htmlToText(action)
        )).join(" ")
        return [valuesOfCondStr, actionsToStr].join(" ")
    }

    if (data.length) {

        return (<>
            {data.map(element => {

                return <div key={element.id} className="rule-top">
                    <div className='semi-bold'><span>{element.position}</span><span>.</span><span>{element.name}</span></div>
                    <div style={{ display: 'flex', alignItems: 'baseline' }}>
                        {ListConditions(element)}
                        {/* {element.summary.actions.map((action, index) => (
                            <DisplayText key={index} text={action} />
                        ))} */}
                        <div style={{ verticalAlign: 'middle', marginLeft: '30px' }}> {element.active ? <FwToggle size="medium" checked></FwToggle> : <FwToggle size="medium"></FwToggle>}
                        </div>

                        <div style={{ verticalAlign: 'middle', margin: '0 0 0 10px' }}>  <FwButton style={{ marginTop: '20px' }} size="icon" color="secondary" onFwClick={() => ShowMenuList()}><FwIcon name="more-vertical" size={18} color="black" ></FwIcon></FwButton>
                        </div>
                    </div>
                    <div className="timeShow" style={{ display: 'flex', alignItems: 'baseline', fontSize: '12px' }}>
                        <div className='date-show'><span className='color-change'>Last Modified:</span>
                            <span className='semi-bold'>{moment(element.updated_at).fromNow()}</span></div>
                        <div className='date-show' style={{ textAlign: 'center' }}><span className='color-change'>By :</span><span className='semi-bold'>{agentsList.map(e => {
                            if (e.value === element.last_updated_by)
                                return e.text
                        })}</span></div>
                        <div className='date-show' style={{ textAlign: 'center' }}><span className='color-change'>Impacted tickets (Last 7 days):</span><span className='semi-bold'>{(element.affected_tickets_count === 0) ? '--' : element.affected_tickets_count}</span></div>
                    </div>
                </div>
            })}
            <div>
                <FwPagination per-page="30" total={hourlyTriggerRules.length} onFwChange={changePage}></FwPagination><br />
            </div>
        </>);
    }
    return null;
}

function Reorder({ ticketCreationRules }) {
    const [data, setData] = React.useState([]);

    const [isHovered, setIsHovered] = React.useState(true);

    React.useEffect(() => {
        if (ticketCreationRules.length) {
            const res = pagination(ticketCreationRules);
            setData(res);
        }
    }, [ticketCreationRules])//Triggers at every change of ticketCreationRules

    const handleMouseEnter = () => {
        setIsHovered(true);
    }

    const handleMouseLeave = () => {
        setIsHovered(false);
    }

    if (data.length) {
        return (<>
            <FwButton style={{ marginTop: '20px' }} color="primary"> Done reordering </FwButton>
            {/* border: 2px solid #f5f1f1;
            background-color: #fff; */}
            {data.map(element => {
                return <div className='reorder-border' onMouseEnter={handleMouseEnter}  // Triggered when the mouse enters the element
                    onMouseLeave={handleMouseLeave}>
                    <div key={element.id} style={{ padding: '24px 10px', display: 'flex', justifyContent: 'space-between' , border: isHovered ? 'blue': '2px solid #f5f1f1'}}>
                        <div className='semi-bold'><span>{element.position}</span><span>.</span><span>{element.name}</span></div>{isHovered && <span style={{ color: 'blue', border: 'blue'}}>Select</span>}
                    </div>
                </div>

            })}

        </>)

    }
    return null;
}

export default function ThreeTabs({ handlePage, reorderPage }) {
    const [selectedTab, setSelectedTab] = React.useState(0);
    const [ticketUpdaionRules, setTicketUpdaionRules] = React.useState([]);

    React.useEffect(() => {
        getTicketUpdationRules(window.client, setTicketUpdaionRules);
    }, []);

    const [hourlyTriggerRules, setHourlyTriggerRules] = React.useState([]);

    React.useEffect(() => {
        getHourlyRules(window.client, setHourlyTriggerRules);
    }, []);

    const [ticketCreationRules, setTicketCreationRules] = React.useState([]);

    React.useEffect(() => {
        getTicketCreationRules(window.client, setTicketCreationRules);

    }, []);

    const [agents, setAgents] = React.useState([]);
    React.useEffect(() => {
        getAgents(window.client, setAgents);
    }, [])

    const [agent, setAgent] = React.useState([]);

    React.useEffect(() => {
        if (agents) {
            console.log("inside", agents);

            const agentNameList = agents.map(agent => ({
                value: agent.id,
                text: agent.contact.name
            }))
            setAgent(agentNameList);
        }
    }, [agents])

    console.log("agent", agent);

    return (<>
        <h2>Automations:</h2>
        <div style={{ display: 'flex', alignItems: 'baseline', width: '100%' }}><h3>Rules that run on:</h3>
            <FwTabs onFwChange={(e) => { setSelectedTab(e.detail.tabIndex) }} style={{ marginLeft: '10px', fontSize: '14px' }}>
                <FwTab slot="tab" panel="ticketCreation">Ticket Creation</FwTab>
                <FwTab slot="tab" panel="ticketUpdates">Ticket Updates</FwTab>
                <FwTab slot="tab" panel="hourlyTriggers">Hourly Triggers</FwTab>
                <FwTab slot="tab" panel="searchIcon"><FwIcon name="search" size={18} ></FwIcon></FwTab>

                <FwTabPanel name="ticketCreation">
                    <div>
                        <FwButton style={{ marginTop: '20px' }} color="secondary" onFwClick={() => reorderPage()}> Reorder </FwButton>
                        <FwButton style={{ marginTop: '20px' }} color="primary" onFwClick={() => handlePage()}> <FwIcon name="plus" slot="before-label"></FwIcon> New rule </FwButton>
                    </div>
                    {/* {selectedTab === 0 ? <TicketCreation></TicketCreation> : null} */}
                    <TicketCreation ticketCreationRules={ticketCreationRules} agentsList={agent}></TicketCreation>


                </FwTabPanel>
                <FwTabPanel name="ticketUpdates"
                ><FwButton style={{ marginTop: '20px' }} color="primary" onFwClick={() => console.log("fwClick event emitted from button")}> <FwIcon name="plus" slot="before-label"></FwIcon> New rule </FwButton>
                    {/* {selectedTab === 1 ? <TicketUpdation></TicketUpdation> : null} */}
                    <TicketUpdation ticketUpdaionRules={ticketUpdaionRules} agentsList={agent}></TicketUpdation>
                </FwTabPanel>
                <FwTabPanel name="hourlyTriggers"><FwButton style={{ marginTop: '20px' }} color="primary" onFwClick={() => console.log("fwClick event emitted from button")}> <FwIcon name="plus" slot="before-label"></FwIcon> New rule </FwButton>
                    {/* {selectedTab === 2 ? <HourlyTriggers></HourlyTriggers> : null} */}
                    <HourlyTriggers hourlyTriggerRules={hourlyTriggerRules} agentsList={agent}></HourlyTriggers>
                </FwTabPanel>
                <FwTabPanel name="searchIcon"></FwTabPanel>

            </FwTabs>
        </div>
    </>);

}


in this how the pagination are handled?