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

}
export async function getDomainName() {
    try {
      const { domainName } = await client.data.get("domainName");
      // success operation
      // "data" is {domainName: "sample.myfreshworks.com"}
      return domainName;
    } catch (error) {
      // failure operation
      console.error(error);
      return null;
    }
  }


  export async function getAllTicketFields(client, setState) {

    try{
        console.log("ticket fields triggered");
        
        let response = await client.request.invokeTemplate("getTicketFields", {});
        console.log("response in ticket fields", response);
        
        let ticket_fields = JSON.parse(response.response);
        console.log("ticket_fields", ticket_fields);

        // let arr = ticket_fields.map(e=> ( {
        //     value: e.id,
        //     text: e.label,
        //     type: e.type
        // }));
        // console.log("arr", arr);
        
        setState(ticket_fields);
        
    }
    catch(err){
        console.log("Error in getting ticket fields", err);
        
    }
  }


















  // export async function getAllTicketFields(client, setState) {

  //   try{
  //       console.log("ticket fields triggered");
        
  //       let response = await client.request.invokeTemplate("getTicketFields", {});
  //       console.log("response in ticket fields", response);
        
  //       let ticket_fields = JSON.parse(response.response);
  //       console.log("ticket_fields", ticket_fields);

  //       // let arr = ticket_fields.map(e=> ( {
  //       //     value: e.id,
  //       //     text: e.label,
  //       //     type: e.type
  //       // }));
  //       // console.log("arr", arr);
        
  //       setState(ticket_fields);
        
  //   }catch(err){
  //       console.log("Error in getting ticket fields", err);
        
  //   }
  // }

  export async function getAllContactFields(client, setState) {

    try{
        
        let response = await client.request.invokeTemplate("getContactFields", {});
        console.log("response in contact fields", response);
        
        let contact_fields = JSON.parse(response.response);
        console.log("contact_fields", contact_fields);

        // let arr = contact_fields.map(e=> ( {
        //     value: e.id,
        //     text: e.label,
        //     type: e.type
        // }));
        // console.log("arr", arr);
        
        setState(contact_fields);
        
    }catch(err){
        console.log("Error in getting contact fields", err);
        
    }
  }
  
  export async function getAllCompanyFields(client, setState) {

    try{
        
        let response = await client.request.invokeTemplate("getCompanyFields", {});
        console.log("response in Company fields", response);
        
        let company_fields = JSON.parse(response.response);
        console.log("company_fields", company_fields);

        // let arr = company_fields.map(e=> ( {
        //     value: e.id,
        //     text: e.label,
        //     type: e.type
        // }));
        // console.log("arr", arr);
        
        setState(company_fields);
        
    }catch(err){
        console.log("Error in getting company fields", err);
        
    }
  }

  function getAllRules( requestApi, page, rulesArray = []) {
    console.log(requestApi);
    
    return new Promise(function (resolve, reject) {
      client.request.invokeTemplate(requestApi, {
        context: {
          page: page
        }
      })
        .then(function (body) {
          if (body) {
            let results = JSON.parse(body.response);
            if (page === 10 || results.length === 0) {
              resolve(rulesArray);
            } else {
              let pg = page;
              pg += 1;
              rulesArray.push(...results);
              resolve(getAllRules(requestApi, pg, rulesArray));
            }
          }
        }).catch(err => {
          reject(err);
        })
    })
  }

  export async function getTicketCreationRules(client, setState) {
    try {
      let creation_rules = await getAllRules("getCreationRules", 1, []);
      
      console.log("Fetched Ticket Creation Rules:", creation_rules);
      
      setState(creation_rules);
      // return creation_rules;
  
    } catch (err) {
      console.error("Error in getting Ticket Creation rules:", err);
    }
  }
  

  export function pagination(data, page=1) {
    const endIndex = page * 30;
    const startIndex = endIndex - 30;
    return data.filter((_, i)=> {
      return i < endIndex && startIndex <= i;
    })
  }

  export async function getTicketUpdationRules(client, setState) {

    try{

        let updation_rules = await getAllRules("getUpdationRules", 1, []);

        console.log("updation_rules", updation_rules);
        
        setState(updation_rules);
        
    }catch(err){
        console.log("Error in getting Ticket updation rules", err);
        
    }
  }

  export async function getHourlyRules(client, setState) {

    try{

        let hourly_rules = await getAllRules("getHourlyTriggerRules", 1, []);
        console.log("hourly_rules", hourly_rules);

        
        setState(hourly_rules);
        
    }catch(err){
        console.log("Error in getting Hourly Trigger rules", err);
        
    }
  }

  export async function getAgents(client, setState) {

    try{        
        let agentsList = await getAllRules("getAgentsList", 1, []);

        console.log("agentsList", agentsList);        
        setState(agentsList);
        
    }catch(err){
        console.log("Error in getting list of agents", err);
        
    }
  }


how the pagination is handled?