'use client'
import { useEffect, useRef, useState } from 'react';
import { useSelector } from 'react-redux';
import Link from 'next/link';
import { io } from 'socket.io-client'
import { NotificationAPI, SocketURL } from '@/Utils/APIRequest/Endpoints';
import useOutsideDropdown from '@/Utils/Hooks/useOutsideDropdown';
import { AppStore } from '@/lib/store';
import { NotificationSVG, VerticalDotsSVG } from '@/Component/Common/SVGs/CommonSVG';
import NotificationList from '@/Component/Notifications/NotificationList';
import { useQuery } from '@tanstack/react-query';
import CustomFetch from '@/Utils/APIRequest/AxiosInstance';
import moment from 'moment';
import NotificationSkeleton from '@/Component/Notifications/NotificationSkeleton';
import { useTranslation } from '@/Utils/Hooks/useTranslate';
import usePost from '@/Utils/Hooks/usePost';
import { CustomToast } from '@/Utils/CustomToast';

const HeaderNotification = () => {
    const { ref, isComponentVisible, setIsComponentVisible } = useOutsideDropdown();
    const { ref: notificationOptionRef, isComponentVisible: notificationOptionIsComponentVisible, setIsComponentVisible: notificationOptionSetIsComponentVisible } = useOutsideDropdown();
    const { translations } = useTranslation();
    const [notification, setNotification] = useState<any>(null);
    const userDetails: any = useSelector((state: AppStore) => state.userDetailSlice?.userDetails);
    const [params, setParams] = useState({ page: 1, per_page: 10 });

    const [audioEnabled, setAudioEnabled] = useState(false);

    const enableAudio = () => {
        const audioElement = document.getElementById("notification-audio") as HTMLAudioElement;
        if (audioElement) {
            audioElement.muted = false; // Ensure audio is unmuted
            setAudioEnabled(true)
        }
    };

    const playNotificationSound = () => {
        const audioElement = document.getElementById("notification-audio") as HTMLAudioElement;
        if (audioElement) {
            audioElement
                .play()
                .then(() => console.log("Audio played successfully."))
                .catch((error) => console.error("Audio playback failed:", error));
        }
    };

    // Get API
    const { data: NotificationData, isPending, fetchStatus, refetch } = useQuery({ queryKey: [NotificationAPI, params], queryFn: () => CustomFetch({ url: NotificationAPI, params: { ...params } }, null, false), refetchOnWindowFocus: false, enabled: !!userDetails && isComponentVisible, select: (data) => data?.data });

    // Patch API
    const { isPending: ReadPending, mutate } = usePost(NotificationAPI, null, (response) => {
        if (response.status == 200 || response.status == 201) {
            refetch();
            notificationOptionSetIsComponentVisible((prev) => prev !== true);
        }
    }, 'Patch');

    useEffect(() => {
        if (userDetails) {
            enableAudio();
            const socket = io(SocketURL, {
                withCredentials: true,
                transports: ['websocket'],
                query: {
                    userId: userDetails?.id,
                },
            });

            socket.on("connect", () => {
                // console.log("Connected to Socket.io Server");
            });

            socket.on("data", (data) => {
                console.log("data", data);
                let value = data?.is_notification
                setNotification(value);
                playNotificationSound();
            });

            return () => {
                socket.disconnect();
            };
        }
    }, [userDetails, audioEnabled]);


    useEffect(() => {
        if (NotificationData?.is_unread == true) {
            setNotification(true);
        } else {
            setNotification(false);
        }
    }, [NotificationData?.is_unread]);

    const handleNotification = () => {
        notificationOptionSetIsComponentVisible(false);
        setIsComponentVisible((prev) => prev !== true);
    }

    return (
        <>
            <div className="sm:relative inline-block text-left" ref={ref}>
                <audio id='notification-audio'>
                    <source src={"/assets/audio/notification-ring.wav"} type="audio/mp3" />
                    Your browser does not support the audio element.
                </audio>
                <div>
                    <button onClick={handleNotification} type="button" className="inline-flex w-full justify-center gap-x-1.5 rounded-full bg-white px-3 max-sm:px-2 py-3 max-sm:py-2 text-sm font-semibold shadow-sm ring-1 ring-inset ring-lightGray hover:bg-gray-10 relative">
                        <NotificationSVG customClass='max-sm:w-5 max-sm:h-5' />
                        {notification && <span className='absolute w-3 h-3 bg-red-500 rounded-full right-0.5 top-0.5  border border-white'></span>}
                    </button>
                </div>
                {
                    isComponentVisible &&
                    <div className="absolute right-0 z-60 mt-2 sm:w-[600px] w-full origin-top-right rounded-3xl bg-white shadow-lg border border-lightGray/30 md:p-6 p-4">
                        <div className='flex items-center justify-between sm:mb-7 mb-4 relative' ref={notificationOptionRef}>
                            <h6 className='text-xl font-semibold'>{translations?.notification}</h6>
                            <div className="w-9 h-9 rounded-full flex items-center justify-center bg-white cursor-pointer" onClick={() => notificationOptionSetIsComponentVisible((prev) => prev !== true)}>
                                <VerticalDotsSVG customClass="transform rotate-90" />
                            </div>
                            {/* <Link href={`/${userDetails?.role}/notifications`} className='font-semibold underline hover:text-primary' onClick={() => setIsComponentVisible((prev) => prev !== true)}>{translations?.seeAllNotification}</Link> */}
                            {notificationOptionIsComponentVisible &&

                                <div className="absolute right-0 z-60 top-full w-40 origin-top-right rounded-xl bg-white shadow-lg border border-lightGray/30 p-4">
                                    <div className='flex flex-col gap-3'>
                                        <Link href={`/${userDetails?.role}/notifications`} className='font-semibold text-xs' onClick={() => setIsComponentVisible((prev) => prev !== true)}>{translations?.seeAllNotification}</Link>
                                        <span className='font-semibold cursor-pointer text-xs' onClick={() => mutate()}>{translations?.markAllRead}</span>
                                        {/* <span className='font-semibold'>{translations?.notificationSetting}</span> */}
                                    </div>
                                </div>

                            }
                        </div>


                        <div className='h-[22rem] overflow-y-auto [&::-webkit-scrollbar]:w-2 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-track]:bg-gray-100 [&::-webkit-scrollbar-thumb]:bg-gray-300'>
                            {(isPending || ReadPending || fetchStatus == 'fetching') ?
                                <div className={`*:mb-7 last:mb-0`}>
                                    <NotificationSkeleton />
                                    <NotificationSkeleton />
                                    <NotificationSkeleton />
                                    <NotificationSkeleton />
                                </div>
                                :
                                NotificationData?.data?.length > 0 ?
                                    NotificationData?.data?.map((elem, i) => {
                                        const createdAt = moment.utc(elem?.created_at || elem?.time).local();
                                        let displayTime;

                                        if (createdAt.isSame(moment(), 'day')) {
                                            displayTime = createdAt.fromNow(true) + " ago";
                                        } else if (createdAt.isSame(moment().subtract(1, 'day'), 'day')) {
                                            displayTime = 'Yesterday';
                                        } else {
                                            displayTime = createdAt.format('DD MMM YYYY hh:mm A');
                                        }
                                        return (
                                            <div className={`cursor-pointer mb-7 last:mb-0`} key={i}>
                                                <NotificationList setIsComponentVisible={setIsComponentVisible} item={elem} displayTime={displayTime} refetch={refetch} />
                                            </div>
                                        )
                                    }) :
                                    <div className='text-center font-semibold text-lg p-5 h-full flex items-center justify-center'>{translations?.noDataFound}
                                    </div>}
                        </div>
                    </div>
                }
            </div>
        </>

    )
}

export default HeaderNotification
