import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useParams } from "next/navigation";
import Link from "next/link";
import { AppStore } from "@/lib/store";
import ImageWithFallback from "@/Component/Common/ImageWithFallback";
import { FacebookSVG, InstagramSVG, TiktokSVG, YoutubeSVG } from "@/Component/Common/SVGs/AuthSVG";
import { InfoCircleSVG, LoaderSVG, WhiteCheckSVG, XiaohongshuSVG } from "@/Component/Common/SVGs/CommonSVG";
import { formatNumber } from "@/Utils/Other/FormateNumbers";
import PrimaryButton from "@/Component/Common/Forms/PrimaryButton";
import BorderButton from "@/Component/Common/Forms/BorderButton";
import usePost from "@/Utils/Hooks/usePost";
import { CampaignAPI, InfluencerArchiveAPI } from "@/Utils/APIRequest/Endpoints";
import BookmarkToggle from "@/Component/Common/InfluencerBox/BookmarkToggle";
import InfluencerDetailSkeleton from "@/Component/Common/InfluencerDetail/InfluencerDetailSkeleton";
import { setInfluencerToCampaign } from "@/lib/Features/UserDetailSidebar/userDetailSidebar";
import ConfirmationModal from "@/Component/Common/Modal/ConfirmationModal";

const InfluencerPoolBox = (props) => {
    const { data, skeletonLoading, listingData, index, setOpenSideModal, openSideModal, poolActiveTab, campaignDetailData, setButtonText, buttonText, campaignId, setOpenQuoteSideModal, params, setParams, listMutate, setOnCheckBox, onCheckBox, lengthValue, translations, isMock, setModal, setAddModal, filteredValue, setRestrictModalOpen } = props;
    const linkParams = useParams();
    const userDetails: any = useSelector((state: AppStore) => state.userDetailSlice?.userDetails);
    const [hoveredIndex, setHoveredIndex] = useState(null);
    const dispatch = useDispatch()
    const addedInfluencer = useSelector((state: AppStore) => state.userDetailSidebar.AddedInfluencer);
    const unReadCount = useSelector((state: AppStore) => state.unreadCountSlice.counts[data?.campaignInfluencer?.[0]?.id] || 0);
    const [sortedCategories, setSortedCategories] = useState<any>([]);
    const [archivedOpenModal, setArchivedOpenModal] = useState<String>('');

    useEffect(() => {
        if (data?.influencerCategories?.length > 0) {
            // Extract skills values from filteredValue (from your API request)
            const selectedSkillsValues = filteredValue?.skills?.length ? filteredValue?.skills?.map((skill) => skill.value) : campaignDetailData?.campaignCategory?.map((category) => category?.category != null && category?.category?.id);

            // Sort the categories based on whether they are in the selected skills
            const filteredCategories = data?.influencerCategories?.filter(cat => cat?.category !== null) || [];

            const sortedInfluencerCategories = filteredCategories.sort((a, b) => {
                const aIsSelected = selectedSkillsValues?.includes(a?.category?.id);
                const bIsSelected = selectedSkillsValues?.includes(b?.category?.id);

                if (aIsSelected && !bIsSelected) return -1;
                if (!aIsSelected && bIsSelected) return 1;
                return 0;
            });

            setSortedCategories(sortedInfluencerCategories);
        }
    }, [data?.influencerCategories, filteredValue?.skills?.length, campaignDetailData?.campaignCategory]);


    const isAdded = addedInfluencer.some(
        (influencer) => influencer.id === data.id && influencer.isCampaignAdded
    );


    useEffect(() => {
        // When sidebar modal is opened, we check Redux state for influencer status
        if (openSideModal) {
            const influencerData = addedInfluencer.find(influencer => influencer.id === openSideModal?.id);
            if (influencerData) {
                // Update the modal's state to reflect the correct campaign added status
                setOpenSideModal(prevState => ({
                    ...prevState,
                    isCampaignAdded: influencerData.isCampaignAdded,  // Set the correct status
                }));
            }
        }
    }, [addedInfluencer]);

    // Add to Campaign Post API
    const { isPending, mutate } = usePost(`${CampaignAPI}/add-influencer`, null, (response) => {
        if (response?.status == 200 || response?.status == 201) {
            dispatch(setInfluencerToCampaign({ influencerId: data?.id, isAddedToCampaign: isAdded == 1 ? 0 : 1 }));
            if (response?.data?.is_show_campaign_popup) {
                setAddModal(campaignDetailData);
            }
            setOnCheckBox((prev) => {
                let tempValue: any = [...prev?.influencerIds]

                if (tempValue?.includes(data?.id)) {
                    tempValue = tempValue?.filter((elem) => elem !== data?.id)
                }
                return { isChecked: prev.isChecked, influencerIds: tempValue, isVisible: true }
            })
            setButtonText((prev) => ({
                ...prev,
                [data.id]: "Added to Campaign",
            }));
        }
    }, null);

    const handleAddToCampaign = () => {
        if (!campaignDetailData?.is_active) {
            setRestrictModalOpen(true);
            return
        }
        let arr: any = []
        arr.push(data?.id);
        let obj: any = {
            campaign_id: campaignDetailData?.id,
            influencer_id: arr,
        }
        mutate(obj);
    }

    const handleBoxClick = (event) => {
        if (isMock) {
            setModal(true)
            return;
        }
        if (event.target.tagName === 'BUTTON' || event.target.tagName === 'A' || event.target.closest('button') || event.target.closest('a')) {
            return;
        }
        event.stopPropagation();
        setOpenSideModal(data);
    };

    const handleCheckUncheck = () => {
        if (buttonText == 'Added to Campaign') return
        setOnCheckBox((prev) => {
            let tempValue: any = [...prev?.influencerIds]

            if (tempValue?.includes(data?.id)) {
                tempValue = tempValue?.filter((elem) => elem !== data?.id)
            } else {
                tempValue.push(data?.id)
            }

            return { isChecked: prev.isChecked, influencerIds: tempValue, isVisible: true }
        })
    }

    const buttonTextEnum = {
        "Add to Campaign": translations?.addToCampaign,
        "Added to Campaign": translations?.addedToCampaign
    }

    const getSocialMediaLink = (type: string) => {
        const media = data?.social_medias?.find((m) => m?.social_type === type);
        if (!media) return '#';

        switch (type) {
            case 'instagram':
                return `https://www.instagram.com/${media.social_user_name}`;
            case 'facebook':
                return `https://www.facebook.com/${media.social_user_name}`;
            case 'tiktok':
                return `https://www.tiktok.com/@${media.social_user_name}`;
            case 'youtube':
                return `https://www.youtube.com/@${media.social_user_name}`;
            case 'xiaohongshu':
                return `https://www.xiaohongshu.com/user/profile/${media.social_user_name}`;
            default:
                return '#';
        }
    };

    const confirmationMessage = data?.campaignInfluencer?.[0]?.is_archived ? translations?.unarchiveMessage : translations?.archiveMessage

    // Patch  API
    const { isPending: archivedPending, mutate: archivedMutate } = usePost(`${InfluencerArchiveAPI}/${data?.campaignInfluencer?.[0]?.id}`, null, (response) => {
        if (response?.status == 200 || response?.status == 201) {
            listMutate(params);
        }
    }, 'patch');


    const handleArchive = () => {
        setArchivedOpenModal(data?.campaignInfluencer?.[0]?.id)
    }

    const callbackFunctionArchive = () => {
        archivedMutate();
    }

    return (
        <>
            {skeletonLoading ?
                <InfluencerDetailSkeleton /> :
                <div key={index} data-sidebar-trigger className={`${listingData ? 'justify-between max-lg:flex-col md:p-3.5' : 'flex-col'} relative border border-lightGray rounded-2xl flex 2xl:gap-5 gap-3 cursor-pointer hover:bg-primary/5 h-full bg-white shadow ${isMock ? 'bg-white shadow blur-sm' : ''}`} onClick={handleBoxClick}>

                    {data?.isArchived == 1 && <div className='rounded-full overflow-hidden text-white bg-gradient-to-br from-secondary to-primary py-0.5 px-3 font-medium absolute -top-3 text-xs left-3.5'>Archived</div>}
                    <div className={`flex items-center gap-2.5 ${listingData ? 'max-md:bg-lightGray/25 max-md:p-4 max-md:rounded-tl-2xl max-md:rounded-tr-2xl max-md:justify-between' : 'justify-between p-4  rounded-tl-2xl rounded-tr-2xl'}`}>
                        {!onCheckBox?.isChecked ? <div className={`4xl:min-w-32 4xl:w-32 4xl:h-32 3xl:min-w-20 3xl:w-20 3xl:h-20 min-w-16 w-16 h-16 rounded-full overflow-hidden bg-gray relative ${listingData ? 'max-md:order-1' : 'order-1'}`}>
                            <ImageWithFallback src={data?.image} alt='Profile' className='w-full h-full object-cover' height={500} width={500} />
                            {data?.campaignInfluencer?.[0]?.is_profile_seen && <div className='absolute top-0 right-0 w-full h-full bg-black/65 rounded-full flex items-center justify-center'>
                                <span className='text-white text-sm font-medium'>Seen</span>
                            </div>}
                        </div>
                            :
                            <button type="button" className={`relative 4xl:min-w-32 4xl:w-32 4xl:h-32 3xl:min-w-20 3xl:w-20 3xl:h-20 min-w-16 w-16 h-16 rounded-full overflow-hidden bg-gray ${listingData ? 'max-md:order-1' : 'order-1'}`} onClick={handleCheckUncheck}>
                                <ImageWithFallback src={data?.image} alt='Profile' className='w-full h-full object-cover' height={500} width={500} />
                                {onCheckBox?.influencerIds.includes(data?.id) && <div className="absolute top-0 right-0 w-full h-full bg-black/50 rounded-full flex items-center justify-center">
                                    <WhiteCheckSVG />
                                </div>}
                            </button>
                        }
                        <div className='flex flex-col'>
                            <h5 className='font-semibold text-base leading-6 cursor-pointer hover:text-primary line-clamp-1'>{data?.display_name}</h5>
                            <div className='flex items-center gap-2'>
                                <span className='text-xs leading-6'>{data?.country}</span>
                                {data?.influencerCategories?.length > 0 && <div className='w-1 h-1 bg-gray rounded-full'></div>}
                                {sortedCategories.length > 0 && (
                                    <>
                                        <span className={`${sortedCategories.length > 1 ? '2xl:line-clamp-1 2xl:max-w-52 xl:max-w-28' : 'whitespace-nowrap'} text-xs`}>
                                            {sortedCategories.slice(0, 1).map((category) => category?.category?.translations?.[0]?.title)}
                                        </span>
                                        {sortedCategories.length > 1 && (
                                            <span
                                                className='relative text-primary underline cursor-pointer whitespace-nowrap text-xs'
                                                onMouseEnter={() => setHoveredIndex(index)}
                                                onMouseLeave={() => setHoveredIndex(null)}
                                            >
                                                {` +${sortedCategories.length - 1} more`}
                                                {hoveredIndex === index && (
                                                    <div className="absolute top-full right-0 bg-white text-black p-2 rounded shadow-lg w-max z-[61]">
                                                        {sortedCategories.slice(1).map((category, idx) => (
                                                            <div key={idx} className="text-xs">{category?.category?.translations?.[0]?.title}</div>
                                                        ))}
                                                    </div>
                                                )}
                                            </span>
                                        )}
                                    </>
                                )}

                            </div>
                        </div>
                    </div>
                    <div className={`flex items-center px-4 ${listingData ? 'md:gap-14 gap-7 md:hidden' : 'gap-7'}`}>
                        <div className='flex flex-col'>
                            <label className='font-semibold text-sm'>{formatNumber(data?.total_followers)}</label>
                            {!listingData && <span className='text-xs'>{translations?.followers}</span>}
                        </div>
                        <div className='flex flex-col'>
                            <label className='font-semibold text-sm'>{data?.engagement_ratio == '0.00' ? '--' : Number(data?.engagement_ratio).toFixed(1)} %</label>
                            {!listingData && <span className='text-xs'>{translations?.engagementRatio}</span>}
                        </div>
                    </div>
                    <div className={`flex ${listingData ? 'flex-row gap-4 items-center max-lg:justify-between' : 'flex-col px-4 pb-4 flex-1'} `}>
                        {poolActiveTab == 'Applicants' && listingData &&
                            <div className={` bg-primary/10 py-2 px-3 rounded justify-center shrink-0`}>
                                <span className={`${listingData ? 'text-sm' : 'text-lg'}`}><span className="font-bold">{data?.campaignInfluencer?.[0]?.currency} ${data?.campaignInfluencer?.[0].influencer_budget}</span></span>
                            </div>
                        }
                        <div className={`flex items-center justify-between ${listingData ? '2xl:gap-10 gap-5 max-md:pb-3' : 'pb-3'}`}>
                            <div className={`flex items-center flex-wrap justify-end gap-5 ${listingData ? 'max-md:mb-2 max-xl:hidden' : ''}`}>
                                {data?.platforms?.map((socialMedia, index) => {
                                    switch (socialMedia) {
                                        case "instagram":
                                            return <Link target='_blank' href={getSocialMediaLink('instagram')}><InstagramSVG key={index} /></Link>;
                                        case "tiktok":
                                            return <Link target='_blank' href={getSocialMediaLink('tiktok')}><TiktokSVG key={index} /></Link>;
                                        case "facebook":
                                            return <Link target='_blank' href={getSocialMediaLink('facebook')}><FacebookSVG key={index} /></Link>;
                                        case "youtube":
                                            return <Link target='_blank' href={getSocialMediaLink('youtube')}><YoutubeSVG key={index} /></Link>;
                                        case "xiaohongshu":
                                            return <Link target='_blank' href={getSocialMediaLink('xiaohongshu')}><XiaohongshuSVG key={index} /></Link>;
                                        default:
                                            return null;
                                    }
                                })}
                            </div>
                            <div className={`flex items-center ${listingData ? '2xl:gap-10 gap-3 max-md:hidden' : 'gap-7 hidden'}`}>
                                <div className='flex flex-col'>
                                    <label className='font-semibold text-sm'>{formatNumber(data?.total_followers)}</label>
                                    <span className='text-xs max-2xl:hidden max-lg:block'>{translations?.followers}</span>
                                </div>
                                <div className='flex flex-col'>
                                    <label className='font-semibold text-sm'>{data?.engagement_ratio == '0.00' ? '--' : Number(data?.engagement_ratio).toFixed(1)}%</label>
                                    <span className='text-xs max-2xl:hidden max-lg:block'>{translations?.engagementRatio}</span>
                                </div>
                            </div>
                            <span className="flex items-center gap-3">
                                <BookmarkToggle data={data} campaignDetailData={campaignDetailData} bookmarkId={data?.campaignBookmarks?.[0]?.id} />
                            </span>
                        </div>
                        {poolActiveTab == 'Applicants' && !listingData &&
                            <div className={`${listingData ? 'justify-center shrink-0' : 'w-full mb-3 flex-1 justify-center'} bg-primary/10 py-2.5 px-3 rounded flex flex-col`}>
                                <span className={`${listingData ? 'text-sm' : 'text-lg'}`}><span className="font-bold">{data?.campaignInfluencer?.[0]?.currency} ${data?.campaignInfluencer?.[0].influencer_budget}</span></span>
                                {data?.campaignInfluencer?.[0]?.message && <p className="text-sm">{data?.campaignInfluencer?.[0].message}</p>}
                            </div>
                        }
                        <div className={`flex 2xl:gap-3 gap-1.5 ${listingData ? "items-center" : 'flex-1 items-end'}`}>
                            {poolActiveTab == 'Applicants' ?
                                <>
                                    <PrimaryButton buttonType="button" customClass="!text-xs w-full whitespace-nowrap max-lg:!px-3.5" onClick={() => setOpenQuoteSideModal({ slug: linkParams?.slug, status: data?.campaignInfluencer?.[0]?.status, campaignDetailId: campaignId, influencerData: { influencer: data }, refetch: listMutate, showApproveModal: true })}>{translations?.acceptQuote}</PrimaryButton>
                                    <div className="relative w-full">
                                        <BorderButton buttonType="button" customClass="!text-xs w-full" onClick={() => setOpenQuoteSideModal({ slug: linkParams?.slug, status: data?.campaignInfluencer?.[0]?.status, campaignDetailId: campaignId, influencerData: { influencer: data }, refetch: listMutate })}>{translations?.message}</BorderButton>
                                        {unReadCount > 0 && (
                                            <span className="absolute -top-0.5 -right-0.5 h-3 w-3 rounded-full bg-red-500 border border-white"></span>
                                        )}
                                    </div>
                                    {!data?.campaignInfluencer?.[0]?.is_archived &&
                                        <BorderButton customClass='!text-xs w-full flex items-center justify-center gap-1.5' onClick={handleArchive} >
                                            {translations?.archive}
                                        </BorderButton>
                                    }
                                </>
                                :
                                <PrimaryButton buttonType="button" customClass={`${(onCheckBox?.isChecked || isPending || buttonText == 'Added to Campaign' || data?.isCampaignAdded || campaignDetailData?.status == 'completed') ? "!bg-gray !border-gray" : ""} ${listingData ? 'min-w-[165px]' : 'w-full'} flex items-center justify-center !text-xs`} onClick={handleAddToCampaign} disabled={onCheckBox?.isChecked || isPending || buttonText == 'Added to Campaign' || data?.isCampaignAdded || campaignDetailData?.status == 'completed'}>
                                    {/* {buttonTextEnum[buttonText]} */}
                                    {buttonTextEnum[data?.isCampaignAdded ? "Added to Campaign" : buttonText]}
                                    {isPending && <LoaderSVG customClass="ml-2" />}
                                </PrimaryButton>
                            }
                        </div>
                    </div>

                </div>
            }
            {archivedOpenModal && <ConfirmationModal loader={archivedPending} modal={archivedOpenModal} args={{ message: confirmationMessage, icon: <InfoCircleSVG customClass="h-14 w-14 text-yellow-400" /> }} setModal={setArchivedOpenModal} callbackFunction={callbackFunctionArchive} />}
        </>
    )
}

export default InfluencerPoolBox
