import { CampaignAPI } from '@/Utils/APIRequest/Endpoints';
import usePost from '@/Utils/Hooks/usePost';
import React, { useEffect, useState } from 'react'
import { ArchiveFillSVG, ArchiveSVG, ArchiveWhiteFillSVG, ArchiveWhiteSVG } from '../SVGs/CommonSVG';
import { useDispatch, useSelector } from 'react-redux';
import { AppStore } from '@/lib/store';
import { setIsBookMarkedList } from '@/lib/Features/UserDetailSidebar/userDetailSidebar';
import { useSearchParams } from 'next/navigation';
import { ImageLoaderSVG } from '../SVGs/AuthSVG';

const BookmarkToggle = (props) => {
    const { data, campaignDetailData, bookmarkId } = props;

    const dispatch = useDispatch()
    const searchQuery = useSearchParams()
    const campaignIDQuery = searchQuery.get("id")
    const isBookMarkedList: any = useSelector((state: AppStore) => state.userDetailSidebar.isBookMarkedList);
    const currentSidebarTab: Boolean = useSelector((state: AppStore) => state.userDetailSidebar.currentSidebarTab);
    const [bookMarkState, setBookMarkState] = useState()

    useEffect(() => {
        setBookMarkState(bookmarkId ? bookmarkId : null)
    }, [bookmarkId])
    const { isPending, mutate } = usePost(`${CampaignAPI}/add-bookmark`, null, (response) => {
        if (response?.data?.id) {
            setBookMarkState(response?.data?.id)
            setUnsetToBookmark(response?.data?.id)
        }
    }, null);

    const setUnsetToBookmark = (bookmarkID) => {
        let tempData = [...isBookMarkedList]
        if (tempData.length > 0) {
            tempData.includes(bookmarkID)
                ? (tempData = tempData.filter((elem) => elem !== bookmarkID))
                : tempData.push(bookmarkID);
        } else {
            tempData.push(bookmarkID);
        }
        dispatch(setIsBookMarkedList(tempData))
    }

    const handleToggle = () => {
        // Prefer campaign from sidebar context — Messages has no ?id= on the URL
        let obj: any = {
            campaign_id: campaignDetailData?.id || campaignIDQuery,
            influencer_id: data?.id
        }
        mutate(obj)
    }

    return (
        <>
            {isPending
                ?
                <ImageLoaderSVG />
                :
                currentSidebarTab
                    ?
                    <button type='button' disabled={campaignDetailData?.status == 'completed'} onClick={handleToggle}>{isBookMarkedList?.includes(bookMarkState) ? <ArchiveWhiteFillSVG customClass="h-8" /> : <ArchiveWhiteSVG customClass="h-8" />}</button>
                    :
                    <button type='button' disabled={campaignDetailData?.status == 'completed'} onClick={handleToggle}>{isBookMarkedList?.includes(bookMarkState) ? <ArchiveFillSVG customClass="h-8" /> : <ArchiveSVG customClass="h-8" />}</button>
            }
        </>
    );
}

export default BookmarkToggle
