import React, { useEffect, useRef, useState } from 'react'
import { RiCheckboxCircleFill, RiCustomerService2Line } from "react-icons/ri";
import { TfiAngleDown } from "react-icons/tfi";
import pic from '../ChatBot/here.png'
import { v4 as uuidv4 } from 'uuid';
import EmojiPicker from 'emoji-picker-react';
import tone from "../ChatBot/mixkit-software-interface-back-2575.wav"
import send from "../ChatBot/mixkit-interface-option-select-2573.wav"
import { CiMail, CiSearch } from "react-icons/ci";
import { IoMdArrowDropup, IoMdSend } from "react-icons/io";
import { GoHome, GoMute } from "react-icons/go";
import { IoChatbubbleEllipsesOutline, IoCloseSharp, IoMailOutline } from "react-icons/io5";
import { useNavigate } from 'react-router-dom';
import { FaAngleLeft, FaAngleRight, FaArrowLeftLong, FaMicrophone, FaPen, FaTrash, FaUser } from "react-icons/fa6";
import { IoMdArrowDropdown } from "react-icons/io";
import { LuMenu, LuSendHorizontal } from "react-icons/lu";
import moment from 'moment';
import { GoPencil } from "react-icons/go";
import { MdMailOutline, MdOutlineMail } from "react-icons/md";
import { AiOutlineClose, AiOutlineSound } from "react-icons/ai";
import { IoIosCloseCircleOutline } from "react-icons/io";
import { FcCustomerSupport } from "react-icons/fc";
import { GoPaperclip } from "react-icons/go";
import { FiUser, FiVideo } from 'react-icons/fi';
import { FaTrashAlt } from 'react-icons/fa';
import { MdOutlinePhoneEnabled } from "react-icons/md";
import { Spinner,Bounce } from 'react-activity';
import { connectSocket,socketConnection } from './socket';

let isMobile = window.innerWidth <= 768 ? true : false;
let selectedColor;
const ChatBot = ({ accessToken }) => {
    const [isOnline, setIsOnline] = useState(false);
    const id = JSON.parse(localStorage.getItem('userId'));
    let [count,setCount]=useState(0)
    useEffect(() => {
        connectSocket(id);
        sessionStorage.setItem("isAi", JSON.stringify(true));
    }, []);

    useEffect(() => {

        const alertAgent = JSON.parse(sessionStorage.getItem("alertAgent"));
          let intervalId;
        if (alertAgent) {
          
          intervalId=  setInterval(() => {
                setCount(count + 1);
              socketConnection.emit("chatRequest", { message: "This customer wants to chat!.", agentId: agentData?.agentId, id });
            }, 5000)
            
        }

        return () => {
            clearInterval(intervalId);
        }
    }, [count]);
    

    const [showContainer, setShowContainer] = useState(false);
    const chatRef = useRef(null);
    const [isNotification, setIsNotification] = useState(true);
    const [agentData, setAgentData] = useState(null);
    const[isPending,setIsPending]=useState(true);

    useEffect(() => {
        socketConnection?.on("onlineUsers", (users) => {
            if (users.includes(agentData?.agentId)) {
                setIsOnline(true);
            } else {
                setIsOnline(false);
            }
        })
    }, [id, socketConnection]);

    


     useEffect(() => {
         const fetchData = async () => {
          const url=`https://konversaserver.onrender.com/get_agent_data/${accessToken}`
        try {
          const response = await fetch(url); 
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }
            const jsonData = await response.json();
            setAgentData(jsonData);
            selectedColor = jsonData.selectedColor || "#2563EB";
            setIsPending(false);
             const id = JSON.parse(localStorage.getItem('userId'));
        if (id) {
            console.log('User ID exists:', id);
            connectSocket(id);
        } else {
    
                let userId = uuidv4().split("-").join("").substring(0,24);

            localStorage.setItem('userId', JSON.stringify(userId));
    }
        } catch (error) {
          console.error("Error fetching data:", error);
        }
      };

      fetchData();
    }, [showContainer]);
    

   

    

    useEffect(() => {
        const notified = sessionStorage.getItem("notified");
         
        if (!notified) {
                setTimeout(() => {
                   chatRef.current.click()
                sessionStorage.setItem('notified', JSON.stringify(true)) 
               },2000)
            } else {
                return;
            }
    },[])
    const notify = () => {
        const isNotification = JSON.parse(localStorage.getItem('isNotification'));
        
        if (isNotification) {
            const audio = new Audio(tone);
             audio.play();
        }
       
       
    }




    
  const [isDragging, setIsDragging] = useState(false);
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const dragRef = useRef(null);
  const initialTouch = useRef({ x: 0, y: 0 });

  const handleTouchStart = (event) => {
   event.preventDefault();
    initialTouch.current = {
      x: event.touches[0].clientX,
      y: event.touches[0].clientY,
    };
  };

  const handleTouchMove = (event) => {
    event.preventDefault();
    const touch = event.touches[0];
    const dx = touch.clientX - initialTouch.current.x;
    const dy = touch.clientY - initialTouch.current.y;

    setPosition((prevPosition) => ({
      x: prevPosition.x + dx,
      y: prevPosition.y + dy,
    }));
    initialTouch.current = {
      x: touch.clientX,
      y: touch.clientY,
    };
  };
 
  const handleMouseDown = (e) => {
   !isMobile&& setIsDragging(true);
    dragRef.current = {
      startX: e.clientX - position.x,
      startY: e.clientY - position.y,
    };
  };

  const handleMouseMove = (e) => {
    if (!isDragging) return;
    setPosition({
      x: e.clientX - dragRef.current.startX,
      y: e.clientY - dragRef.current.startY,
    });
  };

  const handleMouseUp = () => {
    setIsDragging(false);
    };
    
    
   
    useEffect(() => {
        
        const isNotificationSound = JSON.parse(localStorage.getItem("isNotification"));
      
        if (isNotificationSound === null) {
            localStorage.setItem('isNotification', JSON.stringify(true));
            setIsNotification(true)
        } else {
            setIsNotification(isNotificationSound)
        }
    }, [isNotification])
    
    
    const isFree = agentData?.currentPlan === "freemium" ? true : false;
    

    const [message1, setMessage1] = useState("")
    const [message2, setMessage2] = useState("")
    const [showMsg, setShowMsg] = useState(false);
    useEffect(() => {
        const time = moment(Date.now()).format("HH");
        const currentTime = Number(time);
        setTimeout(() => {
            setShowMsg(true) 
        },4000)
        if (currentTime < 12) {
            setMessage2('Good Morning!');
            setMessage1("Hi, how can we assist you this beautiful morning?")
        } else if (currentTime > 12 && currentTime < 16) {
            setMessage2('Good day!');
            setMessage1("Hello there, how can i spice up your day?, i'm here to assist you.")
        } else {
            setMessage2('Howddy!');
            setMessage1(`Great evening to you; ${agentData?.agentName} at your service, how may i be of help?`)
        }
    }, []);
    
    

  return (
      <>
           {!isPending&&<div  style={{
        position: isDragging  ? "absolute" : "fixed",
        cursor: isDragging?"move":"pointer",
        transform:!isMobile&& `translate(${position.x}px, ${position.y}px)`,
          userSelect: "none",
          width: 60,
          height: 60,
          borderRadius: "100%",
          zIndex: 9000000000000000,
          
          bottom: 16,
          right: isMobile ? 8 : 32,
          display: "flex",
          background: "white",
          borderStyle: "solid",
          borderColor:'white'
        
      }}
          onTouchStart={handleTouchStart}
      onTouchMove={handleTouchMove}
      onMouseDown={handleMouseDown}
      onMouseMove={handleMouseMove}
      onMouseUp={handleMouseUp}
          ref={dragRef}
          
          >
         
              <div style={{ width: "100%", height: "100%", borderRadius: "100%", position: "relative" }}>
                 {showContainer&& isFree&&<div style={{width:isMobile?"80%":"260px",height:30,background:"rgba(255, 255, 255, 0.2)",borderRadius:16, borderWidth:2,position:"absolute",left:-270,top:8,borderColor:"#E5E7EB",paddingLeft:16,fontSize:12,display:"flex",alignItems:"center",justifyContent:"start",boxShadow:"0 4px 30px rgba(0, 0, 0, 0.1)",backdropFilter:"blur(5px)",WebkitBackdropFilter:"blur(5px)"}}>&#128170; Powered by Konversa</div>}
             
                  {showMsg&&!showContainer&&<>
                         <div style={{ width:"260px",  position: "absolute",  left: isMobile?-255:-255, top: -40, height: 50, color: "black", borderRadius: "12px", display: "flex", alignItems: "center", paddingLeft:16, justifyContent: "center",fontSize:14,boxShadow:"0 4px 30px rgba(0, 0, 0, 0.1)",backdropFilter:"blur(5px)",WebkitBackdropFilter:"blur(5px)",background:"rgba(255, 255, 255, 0.2)",borderWidth:2,borderColor:"#E5E7Ef"}}>{ message1}</div>
                  
                      <div style={{ width: "100px", position: "absolute", background:"rgba(255, 255, 255, 0.2)", fontSize: 14,  left: -255, top: -90, height: "30px", color: "black", borderRadius: "12px", display: "flex", alignItems: "center", justifyContent: "center",boxShadow:"0 4px 30px rgba(0, 0, 0, 0.1)",backdropFilter:"blur(5px)",WebkitBackdropFilter:"blur(5px)",borderWidth:2,borderColor:"#E5E7Ef" }}>{message2}</div>
                      
                      <AiOutlineClose onClick={()=>setShowMsg(false)} style={{color:"gray",position:"absolute", top:-150,cursor:"pointer",}}/>
                  </>}
              
              <div ref={chatRef} onClick={() => {
                          setShowContainer(!showContainer)
                          notify()
                    
                      }} style={{width:"120px",height:"120px",position:"absolute",borderRadius:"100%",right:-28,top:-32}}>
                   {!showContainer && !showMsg&&<img src={pic} style={{ width: "100%", marginTop: -16, marginRight: -16, display: isMobile ? 'none' : "flex", position: "absolute" }} />} 
              </div>
             {showContainer&& <div  style={{ width: isMobile ? window.innerWidth-8 : "360px", height: isMobile ? window.innerHeight-8 : "85vh", background: selectedColor, position: "absolute", bottom: isMobile?-12:70, right:isMobile?-4:-16,  borderRadius: "10px", display: "flex", alignItems: "center",borderWidth:2,borderColor:"#E5E7EB", justifyContent: "center" }}>
                      <ChatBotComponent isNotification={isNotification} setIsNotification={setIsNotification} showContainer={showContainer} setShowContainer={setShowContainer} agentData={agentData} accessToken={accessToken} isOnline={isOnline } />
              </div>}

              

              <div  style={{ width: "100%", height: "100%", borderRadius: "100%", background: selectedColor,display:"flex",alignItems:"center",justifyContent:"center",borderStyle:'solid',borderWidth:2,borderColor:'white' }}>
                                          {!showContainer && <RiCustomerService2Line size={40} style={{color:"white"}} />}
                  {showContainer && <TfiAngleDown size={30} style={{ color: "white" }} />}
                  
              </div>
       </div>
    </div>}
      </>
  )
}

export default ChatBot

//-bottom-2 instead of 24 image @container


export const ChatBotComponent = ({isNotification,setIsNotification,setShowContainer,showContainer,agentData,accessToken,isOnline}) => {
    const [isHome, setIsHome] = useState(true);
    const [isChat, setIsChat] = useState(false);

    const handleChat = () => {
        setIsChat(true);
        setIsHome(false);
    }
    return <div style={{width:"100%",height:"100%"}}>
        {isHome && !isChat && <Home isHome={isHome} setIsHome={setIsHome} handleChat={handleChat} showContainer={showContainer} setShowContainer={setShowContainer} agentData={agentData} accessToken={ accessToken} />}
        {!isHome && !isChat && <Message isHome={isHome} setIsHome={setIsHome} handleChat={handleChat} setIsChat={setIsChat} agentData={agentData} accessToken={ accessToken} />}
        {isChat && <Chat setIsChat={setIsChat} isNotification={isNotification} setIsNotification={setIsNotification} agentData={agentData} accessToken={ accessToken} isOnline={isOnline}/>}
    </div>
}

const Home = ({isHome,setIsHome,handleChat,setShowContainer,agentData,accessToken}) => {
    const [highlight, setHighlight] = useState(false);
    
  
    const [animate, setAnimate] = useState(false);


    useEffect(() => {
        let intervalId;
       intervalId= setInterval(() => {
            setAnimate(!animate);
       }, 2000)
        
        return () => {
            clearInterval(intervalId)
        }
    }, [animate])
    
    
    return <div style={{ width: "100%", height: "100%", background: selectedColor, borderRadius: "10px", paddingTop: "48px", position: "relative" }} >
        
        <button onClick={()=>setShowContainer(false)} style={{color:"white",display:isMobile?"flex":"none",position:"absolute",top:4,left:4,translate:animate?"16px":"0px",transitionDuration:"1.5s"}}>
            <FaArrowLeftLong  />
        </button>
      

        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", paddingLeft: "16px", paddingRight: "16px", gap: "16px" }}>
            <div style={{width:"100%",height:"50px"}} >
              <p style={{color:"white",fontWeight:'bold',fontSize:"32px",textAlign:"start"}} >Hello there &#128075;</p>
        </div>

       

        <div style={{width:"100%",height:"85px"}} >
                <p style={{ color: "white", textAlign: "start", marginBottom: "8px", fontWeight: "bold" }}>Welcome to { agentData.websiteName}</p>
            <p style={{color:"white",textWrap:"wrap",textAlign:"start"}} >Need help? Search our support center for answers or start a conversation</p>
            </div>
            
             <div style={{width:"100%",height:"100px",borderRadius:"12px",background:"white",padding:"16px",display:"flex"}} >
                <div style={{width:"90%",display:"flex",flexDirection:"column",height:"100%"}} >
                     <p style={{fontWeight:"bold",fontSize:"16px",textAlign:"start"}} >Start a conversation</p>
                <p style={{color:"#9CA3AF",textWrap:"wrap",textAlign:"start",fontSize:"14px"}} >We typically reply in a few minutes</p>
                </div>
                <button onClick={handleChat} style={{width:"10%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center"}}>
<IoMdSend size={30} style={{color:selectedColor,cursor:"pointer"}} />
                </button>
             </div>

            <div style={{ width: "100%", height:"120px",borderRadius:"12px",background:"white",display:"flex",flexDirection:"column", gap:"8px",padding:"16px"}} >
                <p style={{fontWeight:"bold",fontSize:"16px",textAlign:"start"}}>Support center</p>
                <div
                    onMouseLeave={()=>setHighlight(false)}
                    onMouseEnter={() => setHighlight(true)} style={{width:"100%",display:"flex",flexDirection:"column",alignItems:"start",justifyContent:"center",padding:"16px",gap:"4px",height:"50px",borderWidth:"1px",borderRadius:"8px",borderColor:highlight?selectedColor:"#9CA3AF"}} >
                    <p style={{ fontSize: "12px", color: "#9CA3AF", textAlign: "start" }} >Make Enquiries</p>
                     <p style={{fontSize:"12px",color:"#9CA3AF",textAlign:"start"}} >Chat with an Agent</p>
                   
                    
                    </div>
            </div>
           
        </div>
        



 <div style={{width:"100%",height:"50px",position:"absolute",bottom:0}} >
            <div style={{width:"100%",height:"50px",position:"relative",background:"white",display:"flex",alignItems:"center",justifyContent:"space-around",borderBottomRightRadius:"12px",borderBottomLeftRadius:"12px"}} >
                 <GoHome onClick={()=>setIsHome(true)} size={25} style={{color:isHome&&selectedColor}} />
            <IoChatbubbleEllipsesOutline onClick={()=>setIsHome(false)} size={25} />
            <IoMdArrowDropdown size={30} style={{color:"white",position:"absolute",bottom:-16,right:32,display:isMobile?"none":"flex"}} />
           </div>
        </div>
    </div>
}

const Message = ({ isHome, setIsHome, handleChat,setIsChat,agentData,accessToken }) => {
    const msgs = JSON.parse(localStorage.getItem('chatexMessages'));
    const recentMsgs = msgs?.slice(-2); 
    const messages = recentMsgs
    
  
    const [animate, setAnimate] = useState(false);
   

    useEffect(() => {
        let intervalId;
       intervalId= setInterval(() => {
            setAnimate(!animate);
       }, 2000)
        
        return () => {
            clearInterval(intervalId)
        }
    },[animate])
    return <div style={{width:"100%",height:"100%",background:selectedColor,borderRadius:"12px",paddingTop:48,position:"relative"}}>
        <button onClick={() => {
            setIsChat(false)
            setIsHome(true)

        }} style={{ color: "white", display: isMobile ? "flex" : "none", position: "absolute", top: 4, left: 4, translate: animate ? "16px" : "0px", transitionDuration: "1.5s" }}>
            <FaArrowLeftLong  />
        </button>

        <div style={{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",paddingLeft:"16px",paddingRight:"16px",gap:16}} >
            <div style={{width:"100%",height:"50px"}} className='w-[100%] h-[50px] '>
              <p style={{color:"white",fontSize:"32px",fontWeight:"bold",textAlign:"start"}}>Hi &#128075;</p>
        </div>

       

      
            
             <div style={{width:"100%",height:"100px",borderRadius:"12px",background:"white",padding:16,display:"flex"}}>
                <div style={{width:"90%",display:"flex",flexDirection:"column",height:"100%"}}>
                     <p style={{fontWeight:"bold",fontSize:"16px",textAlign:"start"}} >Start a conversation</p>
                <p style={{color:"#9CA3AF",textWrap:"wrap",textAlign:"start",text:"15px"}}>We typically reply in a few minutes</p>
                </div>
                <button onClick={handleChat} style={{width:"10%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center"}} >
<IoMdSend size={30} style={{color:selectedColor,cursor:"pointer"}} />
                </button>
             </div>

            <div style={{width:"100%",height:"20px"}} >
                {messages?.length>0&&<p style={{fontWeight:"bold",textAlign:"start",color:"white"}} >Recent Messages</p>}
               {messages?.length<1&& <p style={{fontSize:"10px",color:"white",textAlign:"start"}}>You do not have any messages yet!</p>}
            </div>

            
            
           {messages?.length>0&& <div style={{width:"100%",height:"180px",background:"white",borderRadius:"12px",display:"flex",flexDirection:"column",gap:"16"}}>
                {
                    messages.map((message,index) => {
                        return  <div key={index} style={{width:"100%",height:"60px"}} >
                    <div style={{width:"100%",height:"40%",display:"flex",alignItems:"center",justifyContent:"space-between",paddingLeft:8,paddingRight:8,marginTop:16}}>
                                <p style={{color:" #6B7280",fontSize:"12px",textAlign:"start",fontWeight:"bold"}} >{ message.firstName}</p><p style={{fontSize:"12px",color:"#9CA3AF"}} >{ moment(message.createdAt).from()}</p>
                    </div>
                            <div style={{width:"100%",height:"60%",display:"flex",alignItems:"center",justifyContent:"space-between",paddingLeft:8,paddingRight:8}} >
                                <div style={{width:"80%",borderBottom:8,height:"100%",borderColor:" #F3F4F6",fontSize:"12px",display:"flex",alignItems:"center",justifyContent:"start"}}><p style={{textAlign:"start",lineClamp:1,color:"gray",Top:4}}>{ message?.message}</p></div>
                        <div style={{width:"20%", height:"100%",borderBottom:8,borderColor:" #F3F4F6",display:"flex",alignItems:"center",justifyContent:"end",color:"#9CA3AF",marginTop:16}}>
                            <FaAngleRight onClick={handleChat}/>
                         </div>
                    </div>
                </div>
                    })
               }
            </div>}
           
        </div>
        



 <div style={{width:"100%",height:"50px",position:"absolute",bottom:0}}>
            <div style={{width:"100%",height:"50px",position:"relative",background:"white",borderBottomRightRadius:"12px",borderBottomLeftRadius:"12px",display:"flex",alignItems:"center",justifyContent:"space-around"}} >
                 <GoHome onClick={()=>setIsHome(true)} size={25} style={{color:isHome&&selectedColor}}/>
            <IoChatbubbleEllipsesOutline onClick={()=>setIsHome(false)} size={25} style={{color:!isHome&&selectedColor}}/>
            <IoMdArrowDropdown style={{color:"white",position:"absolute",bottom:-16,right:32,display:isMobile?"none":"flex"}} />
           </div>
        </div>
    </div>
}

const Chat = ({ setIsChat,isNotification,setIsNotification,agentData,accessToken,isOnline }) => {
    const [isDropDown, setIsDropDown] = useState(false);
    const [hide, setHide] = useState(false);
    const [message, setMessage] = useState('');
    const [messages, setMessages] = useState([]);
    const [isDisplayName, setIsDisplayName] = useState(false);
    const [isEmailTranscript, setIsEmailTranscript] = useState(false);
    const [isPending, setIsPending] = useState(false);
    const [agentMessage, setAgentMessage] = useState("");
    const inputRef = useRef(null);
    const typingRef = useRef(null);

    useEffect(() => {
        if (!isDropDown) {
             setHide(true);
        }else{setHide(false)}
    }, [isDropDown])
    

    const handleEmoji = () => {
        alert('emoji')
    }

    const handleFile = () => {
        inputRef.current.click();
    }

    const isAi = JSON.parse(sessionStorage.getItem("isAi"));
    const handleSend = () => {
        const id = JSON.parse(localStorage.getItem('userId'));
        if (id) {
            console.log('User ID exists:', id);
        } else {
    
                let userId = uuidv4().split("-").join("").substring(0,24);
            
            
            localStorage.setItem('userId', JSON.stringify(userId));
    }
        
        const userId = JSON.parse(localStorage.getItem('userId'));
        const threadId = userId;
        const agentId = agentData?.agentId;
        
         
        const url = `https://konversaserver.onrender.com/chat/${threadId}`;
        const displayName = JSON.parse(localStorage.getItem("displayName"));
        
        if (message.trim()) {
             const newMessage = {
            firstName:displayName,
            message: message,
            senderId: userId,
            receiverId: agentId,
            createdAt: Date.now(),
            type: 'text',
                 isAgent: false,
                 accessToken: accessToken,
                 threadId
        
            
        };
        setMessages([...messages, newMessage]);
        localStorage.setItem('chatexMessages', JSON.stringify([...messages, newMessage]));
            setMessage('');
            
    
                
            
            
            
            if (isAi) {
                setIsPending(true);
                const requestOptions = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(newMessage),
            };
                 fetch(url, requestOptions)
          .then(response => {
          
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
          }

        return response.json();
      })
          .then(responseData => {
              setAgentMessage(responseData)
              setIsPending(false);
      })
      .catch(error => {
        console.error('Error:', error); 
      });  
            } else {
                socketConnection.emit("newMessage", newMessage);
            }

    


        }

    }

    useEffect(() => {
        if (agentMessage !== "") {
            setMessages([...messages, agentMessage]);
            localStorage.setItem('chatexMessages', JSON.stringify([...messages, agentMessage]));
        
        }
    }, [agentMessage]);

    useEffect(() => {
        socketConnection.on("messages", (data) => {
            
            setMessages(data);
            sessionStorage.setItem("alertAgent", JSON.stringify(false));
            localStorage.setItem('chatexMessages', JSON.stringify(data));
           
        });

        socketConnection.on("requestMessageAccepted", () => {
        sessionStorage.setItem("alertAgent", JSON.stringify(false));
        })
    },[messages,socketConnection,isOnline,agentData,accessToken])

   const handleKeyDown = (e) => {
      if (e.key === 'Enter') {
        e.preventDefault();
        if (message.trim() !== '') {
          handleSend()
        }
      }
    };
   
    

     useEffect(() => {
    const messages = JSON.parse(localStorage.getItem("chatexMessages")) || [];
    if (messages !== undefined) {
      setMessages(messages);
    }
  }, []);

    const handleVoiceCall = () => {
        alert('calling')
    }

    const handleVideo = () => {
        alert('video call')
    }

    const isDropDownStyle = {
       width:"220px",height:"200px",background:"#F3F4F6",position:"absolute",zIndex:50,top:isMobile?"56px":"48px",opacity:1,right:12,borderRadius:"12px",transitionDuration:".5s"
    }
    
      const notIsDropDownStyle = {
       width:"220px",height:"0px",background:"#F3F4F6",position:"absolute",zIndex:50,top:isMobile?"56px":"48px",opacity:1,right:12,borderRadius:"12px",transitionDuration:".5s",display:hide&&"none"
   }

    const isFileUpload = agentData.isFileUpload;
    const isEmoji = agentData.isEmoji;
    const[callEmoji,setCallEmoji]=useState(false);

    const onEmojiClick = (emojiData, event) => {
        setMessage(message + emojiData.emoji);
        setCallEmoji(false);
    };
   
    const [selectedFile, setSelectedFile] = useState(null);
    const handleFileChange = (event) => {
    setSelectedFile(event.target.files[0]); 
    };
    
const handleRecord=()=>{
    alert('recording')
}


    useEffect(() => {
        const agentId = agentData?.agentId;
        if (message.length > 0) {
          const message = "typing"
          const user = agentId;
          const data = {
            message, user
          }
          socketConnection.emit("isTyping", data);
        } else {
           const message = "notTyping"
          const user = agentId;
          const data = {
            message, user
          }
          socketConnection.emit("isTyping", data);
        }
    }, [message]);
    

    useEffect(() => {
        socketConnection.on("typing", (data) => {
            const agentId = agentData?.agentId;
            if (data.includes(agentId)) {
                setIsPending(true)
                 typingRef?.current?.scrollIntoView({
        behavior: "smooth",
      });
            } else {
                setIsPending(false)
            }
        }
        )
    }, [messages, socketConnection]);
    const currentPlan = agentData?.currentPlan;
    
    return <div style={{ width: "100%", height: "100%", borderRadius: "12px", position: "relative" }} >
        {callEmoji&&<div style={{ width: "100%", height: "85%", position: "absolute", zIndex: 50,borderRadius:12 }}>
            <EmojiPicker onEmojiClick={onEmojiClick} />
        </div>}
        <div style={{width:"100%",height:"100%",borderRadius:"12px",position:"absolute",zIndex:50,transitionDuration:"1s",top:isDisplayName?0:"10000000px"}} >
            <DisplayNameComponent setIsDisplayName={setIsDisplayName} agentData={ agentData} />
        </div>

        <input
            type='file'
            onChange={handleFileChange}
            ref={inputRef} style={{ display: "none" }} />
        
         <div style={{width:"100%",height:"100%",borderRadius:"12px",position:"absolute",zIndex:50,top:isEmailTranscript?0:"10000000px",transitionDuration:"1s"}} >
            <EmailTransacriptComponent setIsEmailTranscript={setIsEmailTranscript} agentData={ agentData} />
        </div>
        <div style={{ width: "100%", height: "12%", background: selectedColor, position: "relative", borderTopLeftRadius: "12px", borderTopRightRadius: "12px", display: "flex" }} >
            
            <div style={isDropDown?isDropDownStyle:notIsDropDownStyle}>
                <div style={{width:"100%",height:"100%",background:"#F3F4F6",borderRadius:"12px",position:"relative"}} >
                    <IoMdArrowDropup size={30} style={{color:"white",position:"absolute", top:-16,right:0,display:"flex"}}  />
                    <MenuComponent setIsDropDown={setIsDropDown} setMessages={ setMessages} setIsDisplayName={setIsDisplayName} isNotification={isNotification} setIsNotification={setIsNotification} setIsEmailTranscript={setIsEmailTranscript}/>
                </div>

               
                   </div>
            <div style={{width:"10%",height:"100%",color:"white",display:"flex",alignItems:"center",justifyContent:"center"}} >
                <FaAngleLeft onClick={()=>setIsChat(false)}/>
            </div>
            <div style={{width:"75%",height:"100%",display:"flex"}} >
                <div style={{width:"20%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center"}} >
                    <div style={{ width: "35px", height: "35px", background: "white", borderRadius: "100%", display: "flex", alignItems: "center", justifyContent: "center" }} >
                        

                        <div style={{width:"90%",height:"90%",borderRadius:"100%",color:"white",background:selectedColor,display:"flex",alignItems:"center",justifyContent:"center"}} ><RiCustomerService2Line size={22}/></div>
                    </div>
                </div>
                <div style={{width:"55%",height:"100%",display:"flex", flexDirection:"column",justifyContent:"center"}} >
                    <p style={{ fontWeight: "bold", color: "white", textAlign: "start" }} >{agentData.agentName }</p>
                    <p style={{ color: "white", textAlign: "start", fontSize: "12px" }} >{isOnline?"Agent":"AI Assistant"} <span className={isOnline?"text-orange-500 ml-2":"text-gray-500 ml-2"}>
                    -{isOnline?" Online": "AI Assistant active"}
                    </span></p>
                    </div>
            </div>
            <div style={{width:"15%",height:"100%",color:"white",display:"flex",alignItems:"center",justifyContent:"center",gap:14}} >
         
              { currentPlan==="silver"||currentPlan==="gold"&& <MdOutlinePhoneEnabled onClick={handleVoiceCall} size={20} />}
                {currentPlan==="gold"&&<FiVideo onClick={handleVideo}/>}
             </div>
            <div style={{width:"15%",height:"100%",color:"white",display:"flex",alignItems:"center",justifyContent:"center"}} >
         
                {!isDropDown && <LuMenu onClick={() => setIsDropDown(true)} size={20} />}
                {isDropDown&& <IoCloseSharp onClick={()=>setIsDropDown(false)} size={20}/>}
             </div>
        </div>
        <div style={{width:"100%",height:"78%"}} >
            <MessageBody messages={messages} isNotification={isNotification} isPending={isPending} typingRef={ typingRef} />
        </div>
        <div style={{ width: "100%", height: "10%", display: "flex", alignItems: "center", justifyContent: "center", borderBottomRightRadius: "8px", background: "#F3F4F6", borderBottomLeftRadius: "8px", }} >
             {/* <EmojiPicker onEmojiClick={onEmojiClick} /> */}
            <div style={{ width: "90%", height: "80%", display: "flex" }} >
                  {isEmoji&&<div onClick={()=>setCallEmoji(!callEmoji)} style={{width:"5%",height:"90%",display:isMobile?"none":"flex",alignItems:"center",justifyContent:"center"}} >&#128522;</div>}
                <input
                    style={{width:"94%",height:"90%",paddingLeft:"16px",outline:"none",background:"transparent",border:"none",fontSize:"14px"}}
                    onKeyDown={handleKeyDown}
                    placeholder='Write your message'
                    value={message}
                    onChange={((e)=>setMessage(e.target.value))}
                    
                />


              
                <div style={{width:"15%",height:"90%",display:"flex",alignItems:"center",justifyContent:"space-between"}} >
                    <> {message?.length < 1 && currentPlan==="silver"||currentPlan==="gold"&& <GoPaperclip onClick={handleFile} />}
                        {message?.length < 1 && currentPlan==="silver"||currentPlan==="gold"&& <FaMicrophone onClick={handleRecord} style={{color:selectedColor,cursor:"pointer"}} />}
                    </>
                   {message?.length>0&& <IoMdSend onClick={handleSend} size={25} style={{marginLeft:"16px",color:selectedColor}} />}
                </div>
                

            </div>
        </div>
    </div>
}

const DisplayNameComponent = ({setIsDisplayName,agentData}) => {
    const [name, setName] = useState('');
    const[named,setNamed]=useState('')
    const handleCancel = () => { 
        setIsDisplayName(false)
    }
    const handleSubmit = () => {
    
        if (name.trim()) {
            localStorage.setItem("displayName", JSON.stringify(name));
            setNamed(true);
            setTimeout(() => {
                setIsDisplayName(false)
                setName('')
      },2000)
        }
    }
    
    useEffect(() => {
        if (named) {
            setTimeout(() => {
                setNamed(false);
           },3000)
       } 
    },[named])
    const [highlight,setHighlight]=useState(false)
    return <div style={{width:"100%",height:"100%",background:"white",borderRadius:"16px"}} >
        <div style={{width:"100%",height:"12%",background:selectedColor,borderTopRightRadius:"16px",borderTopLeftRadius:"16px",display:"flex",alignItems:"center",paddingLeft:"16px",color:"white"}} >
            <FaAngleLeft onClick={handleCancel}/>
        </div>

        <div style={{width:"100%",height:"100px",display:"flex"}} >
            <div style={{width:"30%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center"}} >
                <div style={{width:"50px",height:"50px",background:selectedColor,color:"white",borderRadius:"16px",display:"flex",alignItems:"center",justifyContent:"center"}} >
                    <FaPen/>
                </div>
            </div>

            <div style={{width:"70%",height:"100%",display:"flex",alignItems:"center",paddingRight:16}} >
                <p>Please change your name so we can recognize you the next time.</p>
            </div>
        </div>

        <div style={{width:"100%",height:'50px',display:"flex",alignItems:"center",justifyContent:"center",paddingRight:16,paddingLeft:16}} >
            <div style={{width:"95%",height:45,borderRadius:16,borderWidth:"1px",borderColor:highlight?selectedColor:"gray",borderStyle:"solid",position:"relative",padding:4}} >

                <label style={{fontSize:highlight||name.length>0?"12px":"16px",position:"absolute",background:"white",color:highlight||name.length>0?selectedColor:"gray",top:highlight||name.length>0?-12:10,left:12,transitionDuration:'.5s'}} >* Name</label>
                






                <input
                    onFocus={() => setHighlight(true)}
                    onBlur={() => setHighlight(false)}
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    style={{width:"100%",height:"100%",paddingLeft:16,outline:"none"}}
               
                />
            </div>
        </div>


        <div style={{width:'100%',height:"80px",display:'flex',alignItems:"center",justifyContent:"space-between",paddingRight:16,paddingLeft:16,marginTop:16}} >
            <div style={{width:"95%",height:"100%",padding:16,borderRadius:"16px",display:"flex",alignItems:"center",justifyContent:"space-between",boxShadow:"5px 5px 10px #88888869"}} >
                <button style={{width:"120px", height:'45px',background:"#D1D5DB",borderRadius:12,cursor:"pointer"}} onClick={handleCancel} >Cancel</button>

                <button onClick={handleSubmit} style={{width:"120px", height:'45px',background:selectedColor,borderRadius:12,display:"flex",alignItems:"center",justifyContent:"center",color:"white",gap:4,cursor:"pointer"}} >Submit {!named&&<LuSendHorizontal />}
               {named&& <RiCheckboxCircleFill/>}
                </button>
            </div>
        </div>
    </div>
}

const MenuComponent = ({ setIsDropDown, setMessages, setIsDisplayName, setIsEmailTranscript,isNotification,setIsNotification,agentData }) => {
    
    

    const menuItems = [
        {
            icon: <GoPencil />,
            title: "Change Display Name"
        },
        {
            icon: <MdOutlineMail />,
            title: "Email Transcript"
        },
        {
            icon: isNotification?<GoMute/>:<AiOutlineSound />,
            title: isNotification?"Mute Sound":"Unmute Sound"
        },
         {
            icon: <FaTrashAlt size={12} />,
            title: "Clear Chat"
        },
       
        {
            icon: <FcCustomerSupport />,
            title: "Transfer to a Human Agent"
        },
    ];

    const [isActive, setIsActive] = useState(false);
    const handleAction = (action) => {
        setIsActive(true)
        if (action === "Clear Chat") {
            localStorage.removeItem("chatexMessages");
            setIsDropDown(false)
            setMessages([])
        }
       else if (action === "Change Display Name") {
            setIsDisplayName(true)
            setIsDropDown(false)
        }

        else if (action === "Email Transcript") {
            setIsDropDown(false);
            setIsEmailTranscript(true)
        }
        else if (action === "Unmute Sound") {
            localStorage.setItem('isNotification', JSON.stringify(true));
            setIsNotification(true)
            const audio = new Audio(tone);
             audio.play();
            
        
        }
         else if (action === "Mute Sound") {
            localStorage.setItem('isNotification', JSON.stringify(false));
            setIsNotification(false)
            
        }
        else if (action === "Transfer to a Human Agent") {
            sessionStorage.setItem("isAi", JSON.stringify(false));
            sessionStorage.setItem("alertAgent", JSON.stringify(true));
            setIsDropDown(false)
        }
    
    }

    useEffect(() => {
        if (isActive) {
            setTimeout(() => {
               setIsActive(false) 
            },1000)
        }
    },[isActive])
    return <div style={{width:"100%",height:"95%",padding:16,gap:4}}>
        {
            menuItems.map((data,index) => {
             return <div onClick={()=>handleAction(data.title)} key={index} style={{width:"100%",height:"35px",display:"flex",alignItems:"center",justifyContent:"start",gap:4,cursor:"pointer",}} >
                 <p>{data.icon}</p>
                 <p style={{fontSize:"12px"}} >{ data.title}</p>
                </div>
            })
        }
    </div>
}





const MessageBody = ({messages,isNotification,agentData,isPending,typingRef}) => {
    
    const msgs = messages || [];

   
    
    const currentMessage = useRef(null);
  useEffect(() => {
    if (currentMessage.current) {
      currentMessage.current.scrollIntoView({
        behavior: "smooth",
      });
      }
      
        if (isNotification) {
            const audio = new Audio(send);
        audio.play();
        
        }
  }, [messages]);
    
    
   
    return <div style={{width:"100%",height:"100%",background:"white",overflowY:"scroll",paddingLeft:4,paddingTop:16,scrollbarWidth:"thin",scrollbarColor:selectedColor}} >
        {
            msgs.map((data, index) => {
            
                return <div ref={currentMessage} key={index} style={{ width: "100%", position: "relative", display: "flex", alignItems: "center", marginTop: 64, justifyContent: !data.isAgent ? "end" : "start", paddingLeft: 16, paddingRight: 16 }} >
                    
                    <div style={{ width: '30px', height: 30, position: 'absolute', background: !data.isAgent ? "#E5E7EB" : selectedColor, color: !data.isAgent ? selectedColor : "white", top: -32, borderRadius: "100%", display: "flex", alignItems: "center", justifyContent: "center" }} >
                        
                        {!data.isAgent?<FiUser/>:<RiCustomerService2Line/>}
                    </div>


                    <div style={{minWidth:50,maxWidth:"70%",height:"fit",padding:8,color:!data.isAgent?"black":"white",background:!data.isAgent?"#E5E7EB":selectedColor,borderRadius:16,fontSize:12}} >
                        



                        <p style={{textAlign:"justify"}} >{data.message}</p>
                        <p style={{color:"#9CA3AF",position:"absolute",fontSize:10,bottom:-16}} >{ moment(data.createdAt).format("HH:mm")}</p>
                        
            </div>
        </div>
            })
        }
       {isPending&& <div ref={typingRef} style={{ width: "100%", height: "30px", marginTop:20,paddingLeft:20,color:"gray" }}>
            <Bounce/>
        </div>}
    </div>
}


const EmailTransacriptComponent = ({setIsEmailTranscript,agentData}) => {
   
    const agentId = agentData?.agentId;
    const [email, setEmail] = useState('')
    const userId = JSON.parse(localStorage.getItem('userId'));
        const threadId = userId;

    const handleCancel = () => { 
        setIsEmailTranscript(false);
    }


    const [isPending, setIsPending] = useState(false);
    const [isFulfilled, setIsFulfilled] = useState(false);
    const handleSubmit = () => {
        const data = { email, agentData };
        if (email.trim()) {

            const url = `https://konversaserver.onrender.com/transcript/${threadId}`;
            const requestOptions = {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
            };


            setIsPending(true);
            fetch(url, requestOptions)
                .then(response => {
          
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }

                    return response.json();
                })
                .then(responseData => {
                    setIsPending(false);
                    setIsFulfilled(true);
                    setTimeout(() => {
                        setIsEmailTranscript(false);
                        setIsFulfilled(false);
                    }, 4000);
                })
                .catch(error => {
                    console.error('Error:', error);
                });

        }
    }
    

    useEffect(() => {
        if (isPending&&setIsEmailTranscript) {
            setTimeout(() => {
                setIsPending(false);
                setIsFulfilled(true);
            }, 3000);

            
        }
    },[isPending])
   
    const [highlight,setHighlight]=useState(false)
    return <div style={{ width: "100%", height: '100%', background: 'white', borderRadius: 16 }} >
        
        <div style={{width:"100%",height:"12%",background:selectedColor,borderTopRightRadius:16,borderTopLeftRadius:16,display:"flex",alignItems:"center",padding:16,color:"white"}} >
            <FaAngleLeft onClick={handleCancel}/>
        </div>

        <div style={{width:'100%',height:"100px",display:'flex'}} >
            <div style={{width:"30%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center"}} >
                <div style={{width:'50px',height:'50px',bg:selectedColor,color:"white",borderRadius:16,display:"flex",alignItems:"center",justifyContent:"center"}} >
                    <MdMailOutline size={25}/>
                </div>
            </div>

            <div style={{width:"70%",height:"100%",display:"flex",alignItems:"center",paddingRight:16}} >
                <p>Send Email Transcript to:</p>
            </div>
        </div>

        <div style={{width:"100%",height:"50px",paddingRight:16,paddingLeft:16,display:"flex",alignItems:"center",justifyContent:"center"}} >
            <div style={{width:"95%",height:"45px",borderRadius:16,borderWidth:1,borderColor:highlight?selectedColor:"#D1D5DB",position:'relative',padding:8,}} >
                


                <label style={{fontSize:highlight||email.length>0?"12px":"16px",position:"absolute",background:"white",color:highlight||email.length>0?selectedColor:"gray",top:highlight||email.length>0?-12:10,left:12,transitionDuration:'.5s'}} >* Email</label>
                <input
                    onFocus={() => setHighlight(true)}
                    onBlur={() => setHighlight(false)}
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    style={{width:"100%",height:"100%",paddingLeft:16,outline:"none"}}
               
                />
            </div>
        </div>


        <div style={{ width: "100%", height: "80px", display: "flex", alignItems: "center", justifyContent: "space-between", paddingRight: 0, paddingLeft: 6, marginTop: 16 }} >
            
            <div style={{ width: "95%", padding: 16, height: "100%", borderRadius: "16px", display: "flex", alignItems: "center", justifyContent: "space-between", boxShadow: "5px 5px 10px #88888869" }} >
                

                <button style={{width:"120px",height:"45px",background:"#D1D5DB",borderRadius:10,cursor:"pointer"}} onClick={handleCancel}>Cancel</button>

                <button onClick={handleSubmit} style={{width:"120px",height:"45px",background:selectedColor,color:"white",borderRadius:10,cursor:"pointer",display:"flex",alignItems:"center",gap:8,justifyContent:"center"}}>Submit {!isPending&&!isFulfilled&&<LuSendHorizontal />}
                    {isFulfilled && <RiCheckboxCircleFill />}
                     {isPending && !isFulfilled&&<Spinner size={ 10} />}
                </button>
            </div>
        </div>
    </div>
}



