'use client'

import React, { useRef, useState, useEffect } from 'react'
import { useSocket } from '@/components/SocketClient'
import Chat from '../chat/chat'
import { sessionType } from '@/types/userType'
import { PhoneCallIcon } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { ArrowsPointingOutIcon } from '@heroicons/react/24/outline'
import shareScreen from '@/assets/share-screen.svg'
import Image from 'next/image'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import axios from 'axios'
import {
  faMicrophoneSlash,
  faMicrophone,
  faVideo,
  faVideoSlash,
} from '@fortawesome/free-solid-svg-icons'
import Timer from '@/components/videoChat/Timer'
import { appointmentType } from '@/types/calendarTypes'
import { useWindowSize } from '@/hooks/screenSize'

import { ToastContainer, toast } from 'react-toastify'
import 'react-toastify/dist/ReactToastify.css'
import { useRouter } from 'next/navigation'

const VideoCallComponent = ({
  roomId,
  session,
  appointment,
  clientInfo,
  expertInfo,
  messagesFromDB,
}: {
  roomId: string
  session: sessionType
  appointment: appointmentType
  clientInfo: any
  expertInfo: any
  messagesFromDB: any
}) => {
  const localVideoRef = useRef<any>(null)
  const remoteVideoRef = useRef<any>(null)
  const peerConnectionRef = useRef<RTCPeerConnection | null>(null)
  const socketRef = useRef<any>(null)
  const screenShareRef = useRef<any>(null)
  const isSharingOfferRef = useRef(false)
  const router = useRouter()
  const socket = useSocket() // Initialize socket with custom hook

  const [answerModel, setAnswerModel] = useState(false)
  const [callerName, setCallerName] = useState(null)
  const [remainingTime, setRemainingTime] = useState('')
  const [isMicEnabled, setIsMicEnabled] = useState(true)
  const [isCameraEnabled, setIsCameraEnabled] = useState(true)

  const [userRejoined, setUserRejoined] = useState(true)
  const [isLocalVideoEnlarged, setIsLocalVideoEnlarged] = useState(false)
  const [isRemoteVideoEnlarged, setIsRemoteVideoEnlarged] = useState(false)

  const [isCalling, setisCalling] = useState(false)
  const [isAnswerd, setisAnswerd] = useState(false)

  const [isMeetingStart, setisMeetingStarted] = useState(false)

  const [isScreenSharing, setisScreenSharing] = useState(false)

  const [timeLeft, setTimeLeft] = useState()

  const [hideMediaIcons, setHideMediaIcons] = useState(false)

  const [showEmojis, setShowEmojis] = useState(false)
  const [isOnlyChat, setIsOnlyChat] = useState(false)
  const [isChatVisible, setIsChatVisible] = useState(true)

  const { width } = useWindowSize()

  const isLargeScreen = width && width >= 1024 // Tailwind's 'lg' breakpoint
  console.log('From video call component', { messagesFromDB })

  const toggleChatVisibility = () => {
    setIsChatVisible((prevVisibility) => !prevVisibility)

    // if (!isLargeScreen && isMeetingStart && isScreenSharing && isChatVisible) {

    //     screenShareRef.current.display = 'none'

    // } else if (!isLargeScreen && isMeetingStart && isScreenSharing && isChatVisible) {

    //     screenShareRef.current.display = 'flex'

    // }
  }

  // Inside your component that holds the Timer component
  useEffect(() => {
    // Check if timeLeft is exactly 60000 milliseconds (1 minute)
    if (timeLeft === 60000) {
      toast.info('1 minute remaining , Time to say good bye :))', {
        position: 'top-center',
        autoClose: 5000, // Dismiss after 5 seconds
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
      })
    }

    if (timeLeft === 0) {
      // Stop all streams
      stopMediaStream(localVideoRef.current?.srcObject)
      stopMediaStream(remoteVideoRef.current?.srcObject)
      stopMediaStream(screenShareRef.current?.srcObject)

      if (peerConnectionRef.current) {
        peerConnectionRef.current.close()
        peerConnectionRef.current = null
      }

      // router.push(`/reviews/${appointment.videoRoomId}`)
    }
  }, [timeLeft])

  useEffect(() => {
    const appointmentDate: any = new Date(appointment.appointmentKey)
    const currentDate: any = new Date()
    const daysDifference = (currentDate - appointmentDate) / (1000 * 3600 * 24)

    if (appointment.status === 'completed' && daysDifference <= 15) {
      initializePeerConnection(appointment)

      // setIsOnlyChat(true)
    }
  }, [socket])

  const handleReceiveOffer = async ({
    offer,
    negotiationType,
  }: {
    offer: any
    negotiationType: any
  }) => {
    try {
      console.log('from handele receive offer', { negotiationType })

      if (negotiationType === 'screenShare') {
        if (peerConnectionRef.current) {
          isSharingOfferRef.current = true

          setisScreenSharing(true)
          console.log('from offer share type ', { isSharingOfferRef })

          await peerConnectionRef.current.setRemoteDescription(
            new RTCSessionDescription(offer)
          )

          const answer = await peerConnectionRef.current.createAnswer()

          await peerConnectionRef.current.setLocalDescription(answer)

          if (socketRef.current) {
            socketRef.current.emit('answer', {
              roomId,
              answer,
              negotiationType: 'screenShare',
              appointmentId: '',
              appointment,
            }) // Or 'regular' for non-screen-share answers
          }

          // const element = document.getElementById('video-shareRef');
          // if (element) {
          //     element.style.display = 'flex';

          // }
        }
      } else if (negotiationType === 'stopScreenShare') {
        isSharingOfferRef.current = false

        setisScreenSharing(false)

        console.log('from stop offer share type ', { isSharingOfferRef })

        if (peerConnectionRef.current) {
          await peerConnectionRef.current.setRemoteDescription(
            new RTCSessionDescription(offer)
          )

          const answer = await peerConnectionRef.current.createAnswer()

          await peerConnectionRef.current.setLocalDescription(answer)

          if (socketRef.current) {
            socketRef.current.emit('answer', {
              roomId,
              answer,
              negotiationType: 'stopScreenShare',
              appointmentId: '',
              appointment,
            }) // Or 'regular' for non-screen-share answers
          }
          const element = document.getElementById('video-shareRef')
          if (element) {
            element.style.display = 'none'
          }
        }
      } else if (negotiationType === 'appointmentCompleted') {
        setAnswerModel(true)
        console.log(0)
        if (peerConnectionRef.current) {
          await peerConnectionRef.current.setRemoteDescription(
            new RTCSessionDescription(offer)
          )
        }
        console.log(1)
        if (peerConnectionRef.current) {
          const answer = await peerConnectionRef.current.createAnswer()

          console.log(2)

          await peerConnectionRef.current.setLocalDescription(answer)

          console.log('from create answer for appointment completed')

          if (socketRef.current) {
            socketRef.current.emit('answer', {
              roomId,
              answer,
              negotiationType: 'appointmentCompleted',
              appointmentId: appointment.appointmentKey,
              appointment,
            })
          }
        }
      } else {
        // setReceivedOffer(offer);

        if (peerConnectionRef.current) {
          await peerConnectionRef.current.setRemoteDescription(
            new RTCSessionDescription(offer)
          )
        }

        setAnswerModel(true)
        const element = document.getElementById('video-containerRef')
        if (element && remoteVideoRef.current) {
          element.style.display = 'none'
        }
      }
    } catch (error) {
      console.error('Error handling offer: ', error)
      toast.error('There was an issue setting up the call. Please try again.')

      setisCalling(false)
      setAnswerModel(false)
    }
  }

  const handleAnswerCall = async () => {
    try {
      if (isScreenSharing == true) {
        setAnswerModel(false) // Hide the modal

        setisCalling(false)
        // 'offer' should be stored from `handleReceiveOffer`
        if (peerConnectionRef.current) {
          const answer = await peerConnectionRef.current.createAnswer()
          await peerConnectionRef.current.setLocalDescription(answer)

          if (socketRef.current) {
            socketRef.current.emit('answer', {
              roomId,
              answer,
              negotiationType: 'screenShare',
              appointmentId: '',
              appointment,
            }) // Or 'regular' for non-screen-share answers
            const element = document.getElementById('video-shareRef')
            if (element) {
              element.style.display = 'flex'
            }
          }
        }
      } else {
        setAnswerModel(false) // Hide the modal

        setisCalling(false)

        if (peerConnectionRef.current) {
          // 'offer' should be stored from `handleReceiveOffer`
          const answer = await peerConnectionRef.current.createAnswer()
          await peerConnectionRef.current.setLocalDescription(answer)

          if (socketRef.current) {
            socketRef.current.emit('answer', {
              roomId,
              answer,
              negotiationType: '',
              appointmentId: appointment.appointmentKey,
              appointment,
            })
          }

          const element = document.getElementById('video-containerRef')
          if (element && remoteVideoRef.current) {
            element.style.display = 'flex'
          }
        }
      }
    } catch (err) {
      console.log('error handeling answer call ', err)
      toast.error('Failed to answer the call. Please try again.')

      setisCalling(false)
      setAnswerModel(false)
    }
  }

  const stopMediaStream = (stream) => {
    console.log('from media stream')
    if (!stream) return
    console.log('from media stream 2')

    stream.getTracks().forEach((track) => {
      console.log('from media stream 3')

      track.stop()
    })
  }

  const toggleCamera = () => {
    if (localVideoRef.current) {
      // Check if localVideoRef.current is not null

      const stream: MediaStream = localVideoRef.current.srcObject as MediaStream
      if (stream) {
        const videoTracks = stream.getVideoTracks() // Get all video tracks

        videoTracks?.forEach((track) => {
          track.enabled = !track.enabled // Toggle the track's enabled status
        })
      }

      setIsCameraEnabled((isCameraEnabled) => !isCameraEnabled)
    }
  }

  const toggleMic = () => {
    if (localVideoRef.current) {
      // Check if localVideoRef.current is not null

      const stream: MediaStream = localVideoRef.current.srcObject as MediaStream
      const audioTracks = stream.getAudioTracks() // Get all audio tracks

      audioTracks.forEach((track) => {
        track.enabled = !track.enabled // Toggle the track's enabled status
      })

      setIsMicEnabled(!isMicEnabled) // Update the state
    }
  }

  const startScreenShare = async () => {
    if (!isScreenSharing) {
      try {
        const screenStream = await navigator.mediaDevices.getDisplayMedia({
          video: true,
        })
        setisScreenSharing(true)

        const element = document.getElementById('video-shareRef')
        if (element) {
          element.style.display = 'flex'
        }

        if (screenShareRef.current) {
          screenShareRef.current.srcObject = screenStream // Display locally
        }

        const screenTrack = screenStream.getVideoTracks()[0] //

        if (peerConnectionRef.current) {
          // Add screen share track to the peer connection
          peerConnectionRef.current.addTrack(screenTrack, screenStream)

          // Create a new offer due to the change in streams
          const offer = await peerConnectionRef.current.createOffer()

          const screenTrackId = screenTrack.id

          await peerConnectionRef.current.setLocalDescription(offer)
          if (socketRef.current) {
            socketRef.current.emit('offer', {
              type: 'offer',
              offer: offer,
              roomId,
              negotiationType: 'screenShare',
              // Include the screen share track ID
            })
          }

          // Listen for when the user stops sharing their screen
          screenStream
            .getTracks()
            .forEach((track) => (track.onended = () => stopScreenShare()))
        }
      } catch (error) {
        console.error('Error starting screen share: ', error)
        setisScreenSharing(false)
      }
    }
  }

  const renegotiate = async () => {
    try {
    } catch (err) {
      console.log({ err })
    }
    if (peerConnectionRef.current) {
      const offer = await peerConnectionRef.current.createOffer()
      await peerConnectionRef.current.setLocalDescription(offer)

      console.log('sending Offer for stop sharing')
      if (socketRef.current) {
        socketRef.current.emit('offer', {
          type: 'offer',
          offer: offer,
          roomId,
          negotiationType: 'stopScreenShare',
        })
      }
    }
  }

  const stopScreenShare = () => {
    if (screenShareRef.current && screenShareRef.current.srcObject) {
      const mediaStream = screenShareRef.current.srcObject as MediaStream

      mediaStream.getTracks().forEach((track) => {
        track.stop() // Stop each track
        if (peerConnectionRef.current) {
          let sender = peerConnectionRef.current
            .getSenders()
            .find((s) => s.track === track)
          if (sender) {
            peerConnectionRef.current.removeTrack(sender) // Remove track from peer connection
          }
        }
      })
      screenShareRef.current.srcObject = null

      setisScreenSharing(false)

      isSharingOfferRef.current = false

      const element = document.getElementById('video-shareRef')
      if (element) {
        element.style.display = 'none'
      }

      if (screenShareRef.current) {
        screenShareRef.current.srcObject = null // Display locally
      }

      // Optionally, renegotiate to inform the remote peer about the end of screen sharing
      renegotiate()
    }
  }

  // const stopScreenShare = async () => {

  //     try {
  //         // Request to get back the webcam video
  //         const userMediaStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });

  //         // Replace the screen share track with the webcam video track in the peer connection
  //         const sender = peerConnectionRef.current.getSenders().find(s => s.track.kind === userMediaStream.getVideoTracks()[0].kind);
  //         sender.replaceTrack(userMediaStream.getVideoTracks()[0]);

  //         // Display the webcam video in the local video element
  //         localVideoRef.current.srcObject = userMediaStream;
  //     }
  //     catch (err) {

  //         console.log('error stoping screen share', err)
  //     }
  // };

  const toggleFullScreen = (videoElement: any) => {
    if (!document.fullscreenElement) {
      // Try to enter full-screen mode
      if (videoElement.requestFullscreen) {
        videoElement.requestFullscreen()
      } else if ((videoElement as any).mozRequestFullScreen) {
        /* Firefox */
        ;(videoElement as any).mozRequestFullScreen()
      } else if ((videoElement as any).webkitRequestFullscreen) {
        /* Chrome, Safari & Opera */
        ;(videoElement as any).webkitRequestFullscreen()
      } else if ((videoElement as any).msRequestFullscreen) {
        /* IE/Edge */
        ;(videoElement as any).msRequestFullscreen()
      }
    } else {
      // Exit full-screen mode
      if (document.exitFullscreen) {
        document.exitFullscreen()
      } else if ((document as any).mozCancelFullScreen) {
        /* Firefox */
        ;(document as any).mozCancelFullScreen()
      } else if ((document as any).webkitExitFullscreen) {
        /* Chrome, Safari and Opera */
        ;(document as any).webkitExitFullscreen()
      } else if ((document as any).msExitFullscreen) {
        /* IE/Edge */
        ;(document as any).msExitFullscreen()
      }
    }
  }

  useEffect(() => {
    const initializeMediaAndPeerConnection = async () => {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({
          video: true,
          audio: true,
        })
        if (localVideoRef.current) {
          localVideoRef.current.srcObject = stream
        }

        const peerConnection = new RTCPeerConnection({
          iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
        })
        stream
          .getTracks()
          .forEach((track) => peerConnection.addTrack(track, stream))
        peerConnectionRef.current = peerConnection
      } catch (err) {
        console.error('Error accessing media devices:', err)
        // Handle UI notification or error state here
      }
    }

    if (appointment.status !== 'completed') {
      initializeMediaAndPeerConnection()
    }

    return () => {
      stopMediaStream(localVideoRef.current?.srcObject)
      stopMediaStream(remoteVideoRef.current?.srcObject)
      stopMediaStream(screenShareRef.current?.srcObject)
    }
  }, [])

  useEffect(() => {
    if (socket) {
      socketRef.current = socket
      setIsOnlyChat(true) // Indicate that the socket is ready.
    }
    return () => {
      socketRef.current?.disconnect()
    }
  }, [socket]) //

  useEffect(() => {
    // Function to handle receiving start of meeting

    // Function to handle receiving an answer
    const handleReceiveAnswer = async ({
      answer,
      negotiationType,
    }: {
      answer: any
      negotiationType: any
    }) => {
      try {
        console.log('from receive answer', answer, { negotiationType })

        if (
          negotiationType === 'screenShare' ||
          negotiationType === 'appointmentCompleted'
        ) {
          setisCalling(false)

          peerConnectionRef.current &&
            (await peerConnectionRef.current.setRemoteDescription(
              new RTCSessionDescription(answer)
            ))
          return
        }
        console.log('answer', answer)
        setisCalling(false)

        const element = document.getElementById('video-containerRef')

        if (element && remoteVideoRef.current) {
          element.style.display = 'flex'
        }
        peerConnectionRef.current &&
          (await peerConnectionRef.current.setRemoteDescription(
            new RTCSessionDescription(answer)
          ))
      } catch (err) {
        console.log('error handeling receiving answer', err)
      }
    }

    // Function to handle receiving a new ICE candidate
    const handleNewICECandidateMsg = async (candidate: any) => {
      console.log('Receiving ICE candidate:', candidate)
      try {
        setisAnswerd(true)
        if (peerConnectionRef.current) {
          peerConnectionRef.current.ontrack = (event) => {
            console.log(
              'Remote track received:',
              event.streams,
              event.track.label,
              event.track.id,
              {
                isSharingOfferRef,
              }
            )

            // Assuming screen sharing tracks have a label containing "screen"
            const isScreenShareTrack = event.track.label
              .toLowerCase()
              .includes('screen')

            if (isSharingOfferRef.current == true) {
              console.log('yes it is ')
              // Handle screen sharing track
              if (screenShareRef.current) {
                screenShareRef.current.srcObject = event.streams[0]
              }
            } else {
              // Handle camera track
              if (remoteVideoRef.current) {
                console.log('no it is not ')

                remoteVideoRef.current.srcObject = event.streams[0]
              }
            }
          }

          peerConnectionRef.current.onicecandidate = (event) => {
            if (event.candidate) {
              console.log('Sending ICE candidate:', event.candidate)
              if (socketRef.current) {
                socketRef.current.emit('ice-candidate', roomId, event.candidate)
              }
            }
          }

          await peerConnectionRef.current.addIceCandidate(
            new RTCIceCandidate(candidate)
          )
        }
      } catch (err) {
        console.log({ err })
        toast.error('Failed to answer the call. Please try again.')

        setisCalling(false)
        setAnswerModel(false)
      }
    }

    const handleRejoin = async (data: any) => {
      console.log('user rejoined', { data })

      // Initialize peer connection
      peerConnectionRef.current = new RTCPeerConnection({
        iceServers: [
          { urls: 'stun:stun.l.google.com:19302' }, // Google's public STUN server
        ],
      })
    }

    const handleAppointmentCancelation = () => {
      toast.warning(
        'User disconected for mroe than 10 minutes and appointment is canceled'
      )

      setTimeout(() => {
        router.push('/dashboard')
      }, 3000)
    }

    const isExpert =
      appointment.clientId === session?.user?.userId ? false : true
    // Join the room

    if (socketRef.current) {
      socketRef.current.emit('join room', {
        roomId,
        userId: session?.user?.userId,
        isExpert,
        appointmentId: appointment.appointmentKey,
        appointment,
      })

      // socketRef.current.on('meeting started', handleonMeetingStart);

      socketRef.current.on('meeting over', () => {
        console.log('Meeting is over')
      })

      console.log('again')
      socketRef.current.on('offer', handleReceiveOffer)

      console.log('if isANswer')

      socketRef.current.on('answer', handleReceiveAnswer)

      socketRef.current.on(
        'appointment cancelled',
        handleAppointmentCancelation
      )

      socketRef.current.on('joined', (data: any) => {
        console.log({ data })
      })

      socketRef.current.on('ice-candidate', handleNewICECandidateMsg)

      socketRef.current.on('rejoin', () => {
        console.log('Rejoined')
      })

      socketRef.current.on('user disconnected', (data: any) => {
        // Handle the disconnection logic here
        console.log('Disconnected from the server')
        console.log({ data })
        setisAnswerd(false)

        setisCalling(false)

        setisMeetingStarted(false)

        setisScreenSharing(false)

        setHideMediaIcons(false)
        const element = document.getElementById('video-shareRef')
        if (element) {
          element.style.display = 'none'
        }

        // Check if the disconnected user is the remote peer
        if (data.userId !== session?.user.userId) {
          // Close the peer connection if it exists

          // Update the UI to hide the remote video element
          const element = document.getElementById('video-containerRef')
          if (element && remoteVideoRef.current) {
            element.style.display = 'none'

            // Alternatively, you might want to remove the video source
            remoteVideoRef.current.srcObject = null
          }

          // Optionally, display a message to the user or handle UI changes accordingly
        }
      })
    }

    // Cleanup function
    return () => {
      peerConnectionRef.current?.close()
      if (socketRef.current) {
        socketRef.current.disconnect()
      }
    }
  }, [socket])

  useEffect(() => {
    setCallerName(
      (!clientInfo.isExpert &&
        appointment.clientId === session?.user?.userId) ||
        (clientInfo.isExpert && appointment.clientId === session?.user?.userId)
        ? expertInfo.firstName
        : clientInfo.firstName
    )
  }, [])

  useEffect(() => {
    console.log({ hideMediaIcons })
  }, [hideMediaIcons])

  const initializePeerConnection = (appointment: any) => {
    const appointmentDate: any = new Date(appointment.appointmentKey)
    const currentDate: any = new Date()
    const daysDifference = (currentDate - appointmentDate) / (1000 * 3600 * 24)

    if (peerConnectionRef.current) {
      peerConnectionRef.current.close() // Close the existing connection if any
    }

    // Initialize peer connection
    peerConnectionRef.current = new RTCPeerConnection({
      iceServers: [{ urls: 'stun:stun.l.google.com:19302' }], // Google's public STUN server
    })

    // Setup event listener for ICE candidates
    peerConnectionRef.current.onicecandidate = (event) => {
      if (event.candidate) {
        console.log('Sending ICE candidate:', event.candidate)
        if (socketRef.current) {
          socketRef.current.emit('ice-candidate', roomId, event.candidate)
        }
      }
    }

    if (appointment.status === 'completed' && daysDifference <= 15) {
      // Scenario for chat-only connection
      console.log('from chat initilazisation')

      setisCalling(true)
      const createAndSendOffer = async () => {
        try {
          console.log('sending offer . 0.')
          if (peerConnectionRef.current) {
            const offer = await peerConnectionRef.current.createOffer()
            console.log('sending offer . 2.')

            await peerConnectionRef.current.setLocalDescription(offer)
            console.log('sending offer . 3.')

            if (socketRef.current) {
              console.log('sending offer ..')

              socketRef.current.emit('offer', {
                roomId,
                offer,
                negotiationType: 'appointmentCompleted',
              })
            }
            console.log('from chat initilazisation 2')
          }
        } catch (err) {
          console.log({ err })
        }
      }
      createAndSendOffer()
      // setIsOnlyChat(true)
    } else {
      // Scenario for full video and audio chat setup
      navigator.mediaDevices
        .getUserMedia({ video: true, audio: true })
        .then(async (stream) => {
          // Display local stream in the video element
          if (localVideoRef.current) {
            localVideoRef.current.srcObject = stream
            if (isCameraEnabled == false) {
              // setIsCameraEnabled((isCameraEnabled) => !isCameraEnabled)
              const stream: MediaStream = localVideoRef.current
                .srcObject as MediaStream
              if (stream) {
                const videoTracks = stream.getVideoTracks() // Get all video tracks

                videoTracks?.forEach((track) => {
                  track.enabled = !track.enabled // Toggle the track's enabled status
                })
              }
            }

            if (isMicEnabled == false) {
              // Code to disable the microphone
              const stream: MediaStream = localVideoRef.current
                .srcObject as MediaStream
              if (stream) {
                const audioTracks = stream.getAudioTracks() // Get all audio tracks

                audioTracks.forEach((track) => {
                  track.enabled = false // Explicitly set to false to disable
                })
              }
            }
          }

          // Add local stream to peer connection
          stream.getTracks().forEach((track) => {
            if (peerConnectionRef.current) {
              peerConnectionRef.current.addTrack(track, stream)
            }
          })

          if (peerConnectionRef.current) {
            peerConnectionRef.current.ontrack = (event) => {
              console.log('Remote track received:', event.streams[0])
              if (remoteVideoRef.current) {
                remoteVideoRef.current.srcObject = event.streams[0]
              }
            }

            if (appointment.status !== 'completed') {
              setisCalling(true)

              const offer = await peerConnectionRef.current.createOffer()

              await peerConnectionRef.current.setLocalDescription(offer)
              if (socketRef.current) {
                socketRef.current.emit('offer', {
                  roomId,
                  offer,
                  negotiationType: '',
                })
              }
            }
          }
        })
        .catch((err) => {
          console.error('Error getting media devices:', err)
        })
    }

    // Other event listeners and setup...
  }

  // start peerConnection
  const startCall = () => {
    initializePeerConnection(appointment)
  }

  return (
    <>
      {answerModel && appointment.status !== 'completed' && (
        <div className="fixed inset-0 z-10 overflow-y-auto">
          <div className="fixed inset-0 bg-gray-500 bg-opacity-50" />

          <div className="min-h-screen flex justify-center items-center">
            <div className="relative bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6 w-full max-w-md mx-auto">
              <h2 className="text-2xl font-bold text-gray-900 dark:text-gray-50">
                Incoming Call
              </h2>
              <p className="mt-2 text-gray-600 dark:text-gray-400">
                Call from
                <span className="font-medium"> {callerName}</span>
              </p>
              <div className="mt-4 flex justify-end space-x-2">
                <Button variant="outline" className="hidden">
                  Decline
                </Button>
                <Button onClick={handleAnswerCall}>Answer</Button>
              </div>
            </div>
          </div>
        </div>
      )}

      <div
        className="flex flex-col  justify-around  pt-8 "
        style={{ display: appointment.status === 'completed' ? 'none' : '' }}
        onClick={() => {
          if (showEmojis == true) {
            setShowEmojis(!showEmojis)
          }
        }}
      >
        <div
          className={`w-full flex items-center ${
            !isChatVisible && isMeetingStart
              ? 'justify-evenly'
              : isChatVisible && isMeetingStart
              ? 'justify-around'
              : 'justify-center'
          } bg-[#f0f8ff]   `}
        >
          {/* <p className='font-semibold text-lg' >
                                Remaining Time : </p> */}
          <div />

          {socketRef.current && (
            <Timer
              remainingTime={remainingTime}
              setTimeLeft={setTimeLeft}
              timeLeft={timeLeft}
              setHideMediaIcons={setHideMediaIcons}
              setRemainingTime={setRemainingTime}
              socketRef={socketRef}
              setisMeetingStarted={setisMeetingStarted}
            />
          )}
          {isMeetingStart && (
            <button
              onClick={toggleChatVisibility}
              className={`py-2 ml-4 px-4 font-bold rounded-lg text-white transition-colors duration-150 ${
                isChatVisible
                  ? 'bg-red-500 hover:bg-red-700'
                  : 'bg-blue-500 hover:bg-blue-700 ml-16'
              }`}
            >
              {isChatVisible ? 'Hide Chat' : 'Show Chat'}
            </button>
          )}
        </div>

        <div className={`flex  lg:flex-row w-full p-4 max-h-[80vh]  `}>
          <div
            className={`flex flex-col gap-4 ${
              isChatVisible && isMeetingStart && 'hidden lg:flex'
            } ${
              isScreenSharing
                ? ' hidden lg:flex lg:flex-col lg:items-end  w-1/5 '
                : 'lg:flex-row-reverse w-full'
            }  ${
              isMeetingStart ? 'lg:justify-center' : 'justify-around'
            }  p-4 pt-0 max-h-[80vh]  `}
          >
            <div
              className={`video-container flex justify-center w-full border border-black   ${
                isMeetingStart && !isScreenSharing
                  ? 'lg:h-80 lg:w-auto'
                  : isScreenSharing
                  ? 'lg:w-full lg:h-80'
                  : 'lg:w-3/5  '
              } rounded-[5%] `}
              onMouseOver={() => {
                setHideMediaIcons(false)
              }}
              onMouseLeave={() => {
                setHideMediaIcons(true)
              }}
              style={{
                // width: '30%',
                // height: '100%',
                position: 'relative',
                zIndex: isLocalVideoEnlarged ? 10 : 1, // Bring to front if enlarged
              }}
            >
              {isMeetingStart && (
                <div className=" absolute top-[5%] left-[5%] z-40 text-white text-xl bg-black p-2 opacity-70 rounded-[5%] cursor-pointer ">
                  <p>
                    {' '}
                    {session?.user?.userId === appointment?.clientId
                      ? expertInfo?.firstName + ' ' + expertInfo.lastName
                      : clientInfo?.firstName + ' ' + clientInfo.lastName}{' '}
                  </p>
                </div>
              )}

              <video
                ref={localVideoRef}
                autoPlay
                muted
                className="rounded-[5%] shadow-md  w-full h-full object-cover "
                // onClick={toggleLocalVideoSize} // Toggle size on click
              />

              <div
                className="controls"
                style={{
                  position: 'absolute',
                  bottom: '10px',
                  left: '50%',
                  transform: 'translateX(-50%)',
                  display: 'flex',
                  gap: '10px',
                  width: '90%',
                  justifyContent: 'space-between',
                }}
              >
                <div />

                <div
                  className={`${
                    isMeetingStart && hideMediaIcons ? 'hidden' : 'flex'
                  }   gap-4 justify-center items-center`}
                >
                  <button
                    onClick={toggleCamera}
                    className={`rounded-full bg-white  p-1  
                                    ${
                                      isMeetingStart ? 'md:p-2' : 'md:p-4'
                                    }   shadow-sm flex items-center justify-center`}
                  >
                    {isCameraEnabled ? (
                      <FontAwesomeIcon
                        icon={faVideo}
                        className={`w-6 h-6   text-green-500   ${
                          isMeetingStart ? 'md:w-6 md:h-6' : 'md:w-8 md:h-8'
                        }`}
                      />
                    ) : (
                      <FontAwesomeIcon
                        icon={faVideoSlash}
                        className={`w-6 h-6   text-red-500   ${
                          isMeetingStart ? 'md:w-6 md:h-6' : 'md:w-8 md:h-8'
                        }`}
                      />
                    )}
                  </button>
                  <button
                    onClick={toggleMic}
                    className={`rounded-full bg-white  p-1  
                                    ${
                                      isMeetingStart ? 'md:p-2' : 'md:p-4'
                                    }   shadow-sm flex items-center justify-center`}
                  >
                    {isMicEnabled ? (
                      <FontAwesomeIcon
                        icon={faMicrophone}
                        className={`w-6 h-6   text-green-500   ${
                          isMeetingStart ? 'md:w-6 md:h-6' : 'md:w-8 md:h-8'
                        }`}
                      />
                    ) : (
                      <FontAwesomeIcon
                        icon={faMicrophoneSlash}
                        className={`w-6 h-6   text-red-500   ${
                          isMeetingStart ? 'md:w-6 md:h-6' : 'md:w-8 md:h-8'
                        }`}
                      />
                    )}
                  </button>

                  <button
                    onClick={startScreenShare}
                    className={`rounded-full bg-white  p-1  
                                    ${
                                      isMeetingStart
                                        ? 'md:p-2 '
                                        : 'md:p-4  hidden '
                                    }   shadow-sm flex items-center justify-center`}
                  >
                    <Image
                      src={shareScreen}
                      alt=""
                      className={`w-6 h-6     ${
                        isMeetingStart ? 'md:w-6 md:h-6' : 'md:w-8 md:h-8'
                      }`}
                    />
                  </button>
                </div>

                <div
                  className={`rounded-full bg-white  p-1  
                                    ${
                                      isMeetingStart && hideMediaIcons
                                        ? ' hidden md:p-2'
                                        : isMeetingStart
                                        ? 'md:p-2'
                                        : 'md:p-4'
                                    }   shadow-sm flex items-center justify-center`}
                  onClick={() => toggleFullScreen(localVideoRef.current)}
                >
                  <ArrowsPointingOutIcon
                    className={`w-6 h-6     ${
                      isMeetingStart ? 'md:w-6 md:h-6' : 'md:w-8 md:h-8'
                    }`}
                  />
                </div>
              </div>
            </div>

            <div
              id="video-containerRef"
              className={`video-container    rounded-[5%] flex justify-center  border border-black   ${
                isScreenSharing
                  ? 'w-full h-80 '
                  : isMeetingStart
                  ? 'h-[70vh] w-full lg:w-11/12'
                  : 'h-[70vh] w-full lg:w-3/5 md:mt-0'
              }  `}
              style={{
                // width: '80%',
                // height: '100%',
                position: 'relative',
                zIndex: isRemoteVideoEnlarged ? 10 : 1, // Bring to front if enlarged
                display: 'none',
              }}
            >
              <div
                className={`  absolute top-[5%] left-[5%] z-40 text-white text-2xl bg-black p-4 opacity-70 cursor-pointer  rounded-[10px] `}
              >
                <p>
                  {' '}
                  {session?.user?.userId === appointment?.clientId
                    ? expertInfo?.firstName + ' ' + expertInfo.lastName
                    : clientInfo?.firstName + ' ' + clientInfo.lastName}{' '}
                </p>
              </div>
              {/* Adjust display as needed */}
              <video
                ref={remoteVideoRef}
                autoPlay
                className={` ${
                  isScreenSharing ? ' w-full  ' : ' w-full'
                }  h-full object-cover relative rounded-[5%]  `}

                // Ensure display is not 'none' when you want the video to be visible
              />

              <div className="controls absolute bottom-[10px]  left-1/2 -translate-x-1/2 flex gap-6  w-11/12 justify-end">
                <div
                  className="rounded-full bg-white p-1 md:p-4 shadow-sm cursor-pointer "
                  onClick={() => toggleFullScreen(remoteVideoRef.current)}
                >
                  <ArrowsPointingOutIcon
                    className={`w-6 h-6     ${
                      isMeetingStart ? 'md:w-6 md:h-6' : 'md:w-8 md:h-8'
                    }`}
                  />
                </div>
              </div>
            </div>
          </div>

          <div
            id="video-shareRef"
            className={`video-container flex-1 mt-4 md:mt-0 mr-4 border border-blue-400 justify-center  w-full lg:w-3/5 h-[70vh]  rounded-[5%] ${
              isChatVisible ? 'hidden lg:flex flex-col' : ' flex flex-col '
            }  `}
            style={{
              position: 'relative',
              zIndex: isRemoteVideoEnlarged ? 10 : 1, // Bring to front if enlarged
              display:
                isChatVisible && isMeetingStart && isScreenSharing
                  ? isLargeScreen
                    ? 'flex'
                    : 'none'
                  : !isChatVisible && isMeetingStart && isScreenSharing
                  ? 'flex'
                  : 'none',
              flexDirection: isLargeScreen ? 'column' : undefined,
            }}
          >
            {/* Adjust display as needed */}
            <video
              ref={screenShareRef}
              autoPlay
              className="w-11/12 h-full relative object-contain rounded-[5%]"

              // Ensure display is not 'none' when you want the video to be visible
            />

            <div className="controls flex gap-[10px] w-[90%] justify-end ">
              <div
                className="rounded-full bg-white p-1 md:p-4 shadow-sm cursor-pointer "
                onClick={() => toggleFullScreen(screenShareRef.current)}
              >
                <ArrowsPointingOutIcon
                  className={`w-6 h-6     ${
                    isMeetingStart ? 'md:w-6 md:h-6' : 'md:w-8 md:h-8'
                  }`}
                />
              </div>
            </div>
          </div>

          {
            <div
              className={` ${
                isMeetingStart && isChatVisible ? 'block' : 'hidden'
              } 
   ${isScreenSharing ? ' w-full lg:w-1/5' : ' w-full lg:w-1/4'}
    max-h-[70vh] border border-blue-600  rounded-2xl shadow-xl    p-2 pb-1`}
            >
              {socketRef.current && (
                <Chat
                  userId={session?.user?.userId}
                  socketRef={socketRef}
                  roomId={roomId}
                  messagesFromDB={messagesFromDB}
                  showEmojis={showEmojis}
                  setShowEmojis={setShowEmojis}
                  session={session}
                  appointment={appointment}
                  expertInfo={expertInfo}
                  clientInfo={clientInfo}
                />
              )}
            </div>
          }
        </div>

        <div className="w-full flex justify-center items-center py-4 absolute z-20 top-1/2  -translate-y-1/2 ">
          <button
            onClick={startCall}
            disabled={isCalling}
            className={` ${
              isAnswerd && 'hidden'
            } flex  bg-white items-center gap-3 border border-blue-300 rounded-md shadow-md px-3 py-2 md:px-6 md:py-4 mt-6 hover:bg-blue-400 hover:text-white  `}
          >
            <PhoneCallIcon className="w-6 h-6  text-blue-600 " />

            <p className="">{isCalling ? 'Ringing' : ' Start Call'}</p>
          </button>
        </div>
        <ToastContainer />
      </div>
      {appointment.status === 'completed' && isOnlyChat && (
        <Chat
          userId={session?.user?.userId}
          socketRef={socketRef}
          roomId={roomId}
          messagesFromDB={messagesFromDB}
          showEmojis={showEmojis}
          setShowEmojis={setShowEmojis}
          session={session}
          appointment={appointment}
          expertInfo={expertInfo}
          clientInfo={clientInfo}
        />
      )}
    </>
  )
}

export default VideoCallComponent
