import React, { useCallback, useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux';
import { useQuery } from '@tanstack/react-query';
import { FaInstagram, FaFacebook, FaTiktok, FaYoutube, FaXingSquare } from "react-icons/fa";
import GradientButton from '@/Component/Common/Forms/GradientButton';
import { InfluencerCloseSVG, LoaderSVG } from '@/Component/Common/SVGs/CommonSVG'
import { AppStore } from '@/lib/store';
import ImageWithFallback from '@/Component/Common/ImageWithFallback';
import { AddPostAPI, GetLatestSocialMediaPost, GetPostFromLinkAPI, SelfAPI } from '@/Utils/APIRequest/Endpoints';
import CustomFetch from '@/Utils/APIRequest/AxiosInstance';
import InstagramPostGrid from './InstagramPostGrid';
import FacebookPostGrid from './FacebookPostGrid';
import YoutubePostGrid from './YoutubePostGrid';
import TiktokPostGrid from './TiktokPostGrid';
import PostSkeleton from './PostSkeleton';
import usePost from '@/Utils/Hooks/usePost';
import { CustomToast } from '@/Utils/CustomToast';
import { RiCloseCircleLine, RiImage2Line } from 'react-icons/ri';
import InstagramLinkPostGrid from './LinkPosts/InstagramLinkPostGrid';
import YoutubeLinkPostGrid from './LinkPosts/YoutubeLinkPostGrid';
import FacebookLinkPostGrid from './LinkPosts/FacebookLinkPostGrid';
import TiktokLinkPostGrid from './LinkPosts/TiktokLinkPostGrid';
import RelinkSocialMediaAccounts from './RelinkSocialMediaAccounts';
import { getUserDetails } from '@/lib/Features/UserDetails/userDetails';
import { useSearchParams } from 'next/navigation';
import Cookies from 'js-cookie';
import PrimaryButton from '@/Component/Common/Forms/PrimaryButton';
import { ImageLoaderSVG } from '@/Component/Common/SVGs/AuthSVG';

const UploadPost = (props) => {
    const { JobDetailData, setUploadPost, JobDetailDataRefetch, translations } = props;
    const userDetails: any = useSelector((state: AppStore) => state.userDetailSlice?.userDetails);
    const searchParams = useSearchParams();
    const [selectedSocialId, setSelectedSocialId] = useState<any>(null);
    const [selectedSocialType, setSelectedSocialType] = useState<any>(null);
    const [loadMoreToken, setLoadMoreToken] = useState<string | undefined>(undefined);
    const [isFirstLoad, setIsFirstLoad] = useState(true);
    const [posts, setPosts] = useState<any>([]);
    const [hasMore, setHasMore] = useState(true);
    const [isLoadingMore, setIsLoadingMore] = useState(false);
    const [selectedPosts, setSelectedPosts] = useState([]);
    const [tokenExpire, setTokenExpire] = useState(false);
    const [linkPosts, setLinkPosts] = useState<any>([]);
    const [inputLink, setInputLink] = useState("");
    const dispatch = useDispatch();
    const observer = useRef<IntersectionObserver | null>(null);

    // Social media icons mapping
    const iconMap = {
        instagram: <FaInstagram className="text-gray text-lg" />,
        facebook: <FaFacebook className="text-gray text-lg" />,
        tiktok: <FaTiktok className="text-gray text-lg" />,
        youtube: <FaYoutube className="text-gray text-lg" />,
        xiaohongshu: <FaXingSquare className="text-gray text-lg" />,
    };

    // Self API
    const { data: selfData, refetch, isPending: SelfLoader, fetchStatus: SelfFetchStatus } = useQuery({ queryKey: [SelfAPI], queryFn: () => CustomFetch({ url: SelfAPI, }, null, false), refetchOnWindowFocus: false, select: (data) => data?.data });

    useEffect(() => {
        if (selfData) {
            dispatch(getUserDetails(selfData));

            const socialMediaEntry = selfData?.social_medias?.find((item) => item.social_type === selectedSocialType);

            let expireToken: boolean = false;

            if (socialMediaEntry) {
                if (socialMediaEntry?.social_type === "facebook") {
                    const facebookPage = socialMediaEntry?.facebookPages?.find((page) => page.id === selectedSocialId);
                    expireToken = facebookPage?.is_token_expire || facebookPage?.is_new_permission;
                    setSelectedSocialId(facebookPage?.id);
                } else {
                    expireToken = socialMediaEntry?.is_token_expire || socialMediaEntry?.is_new_permission;
                    setSelectedSocialId(socialMediaEntry?.id);
                }
            }

            setTokenExpire(expireToken);

        }
    }, [selfData, SelfLoader, SelfFetchStatus, tokenExpire, selectedSocialId, selectedSocialType]);

    // Auto-select first profile on mount
    useEffect(() => {
        if (userDetails?.social_medias && !selectedSocialId && !selectedSocialType) {
            // Find the first available profile
            for (const item of userDetails.social_medias) {
                // Check Instagram Profiles
                if (item.instagramProfiles?.length > 0) {
                    const firstProfile = item.instagramProfiles[0];
                    handleProfileClick({
                        id: item.id,
                        social_type: "instagram",
                        name: firstProfile.name,
                        username: `@${firstProfile.user_name}`,
                        profile_picture: firstProfile.profile_picture_url
                    });
                    return;
                }
                // Check Facebook Pages
                if (item.facebookPages?.length > 0) {
                    const firstPage = item.facebookPages[0];
                    handleProfileClick({
                        id: firstPage.id,
                        social_type: "facebook",
                        name: firstPage.name,
                        username: `@${firstPage.user_name}`,
                        profile_picture: firstPage.page_logo || ""
                    });
                    return;
                }
                // Check TikTok Profiles
                if (item.tikTokProfiles?.length > 0) {
                    const firstProfile = item.tikTokProfiles[0];
                    handleProfileClick({
                        id: item.id,
                        social_type: "tiktok",
                        name: firstProfile.display_name,
                        username: firstProfile.username,
                        profile_picture: firstProfile.avatar_url
                    });
                    return;
                }
                // Check YouTube Channels
                if (item.youtubeChannels?.length > 0) {
                    const firstChannel = item.youtubeChannels[0];
                    handleProfileClick({
                        id: item.id,
                        social_type: "youtube",
                        name: firstChannel.title,
                        username: firstChannel.channel_name,
                        profile_picture: firstChannel.profile_picture_url
                    });
                    return;
                }
            }
        }
    }, [userDetails, selectedSocialId, selectedSocialType]);

    // Get API
    const { data: PostData, fetchStatus, isPending, isFetching, refetch: PostRefetch } = useQuery({ queryKey: [GetLatestSocialMediaPost, selectedSocialId, selectedSocialType], queryFn: () => CustomFetch({ url: `${GetLatestSocialMediaPost}/${selectedSocialId}?platform=${selectedSocialType}&nextPageToken=${loadMoreToken ?? ''}` }, null, false), refetchOnWindowFocus: false, enabled: !!selectedSocialId, select: (data) => data?.data?.data });

    // Get Post From Link API
    const { data: PostLinkData, fetchStatus: PostLinkFetchStatus } = useQuery({ queryKey: [GetPostFromLinkAPI, inputLink], queryFn: () => CustomFetch({ url: `${GetPostFromLinkAPI}?q=${inputLink}` }, null, false), refetchOnWindowFocus: false, enabled: !!inputLink, select: (data) => data?.data });

    useEffect(() => {
        if(fetchStatus === "fetching" || isPending || isFetching) return;
        if (!PostData) {            
            refetch();
            if (isFirstLoad) setIsFirstLoad(false);
            return;
        };

        setIsLoadingMore(false);
        if (isFirstLoad) setIsFirstLoad(false);

        // First load → replace, Load more → append
        setPosts((prev: any) => {
            // First load or after profile change → just set the data
            if (!prev) {
                return PostData;
            }

            // Append based on platform structure
            switch (selectedSocialType) {
                case 'instagram':
                case 'facebook':
                case 'youtube':
                case 'xiaohongshu':
                    return {
                        ...PostData,
                        data: [
                            ...(prev?.data || []),
                            ...(PostData?.data || []),
                        ],
                    };

                case 'tiktok':
                    return {
                        ...PostData,
                        data: {
                            ...prev?.data,
                            ...PostData?.data,
                            videos: [
                                ...(prev?.data?.videos || []),
                                ...(PostData?.data?.videos || []),
                            ],
                        },
                    };

                default:
                    return PostData;
            }
        });

        // Extract next token
        let nextToken: string | undefined = undefined;

        if ((selectedSocialType === 'instagram' || selectedSocialType === 'facebook') && PostData?.paging?.cursors?.after) {
            nextToken = PostData.paging.cursors.after;
        } else if (selectedSocialType === 'youtube' && PostData?.nextPageToken) {
            nextToken = PostData.nextPageToken;
        }

        setLoadMoreToken(nextToken);
        setHasMore(!!nextToken);

    }, [PostData, selectedSocialType, fetchStatus, isPending, isFetching]);

    const lastPostElementRef = useCallback((node: HTMLDivElement | null) => {
        if (isPending || isFetching || isLoadingMore || fetchStatus === "fetching") return;
        if (observer.current) observer.current.disconnect();

        observer.current = new IntersectionObserver(entries => {
            if (entries[0].isIntersecting && hasMore && loadMoreToken) {
                setIsLoadingMore(true);
                PostRefetch(); // Triggers next page
            }
        });

        if (node) observer.current.observe(node);
    }, [isPending, isFetching, isLoadingMore, hasMore, loadMoreToken, fetchStatus]);

    useEffect(() => {
        if (inputLink && PostLinkData) {
            setLinkPosts(PostLinkData?.data);
            setSelectedSocialType(PostLinkData?.platform);
        }
    }, [PostLinkData, inputLink]);

    useEffect(() => {
        const code = searchParams.get('code');
        const state = searchParams.get('state');
        const campaignData = Cookies.get('campaign_data') ? JSON.parse(Cookies.get('campaign_data')) : null;
        if (code && !state && campaignData?.slug && campaignData?.id) {
            const socialMediaEntry = userDetails?.social_medias?.find((item) => item.social_type === 'instagram');
            handleProfileClick(socialMediaEntry);
        }
        if (code && state && campaignData?.slug && campaignData?.id) {
            const socialMediaEntry = userDetails?.social_medias?.find((item) => item.social_type === 'tiktok');
            handleProfileClick(socialMediaEntry);
        }
    }, [searchParams, userDetails]);

    const renderPostComponent = () => {

        if (!selectedSocialType) {
            return <p className="text-gray text-center text-2xl font-medium rounded-md border border-gray/50 h-full flex items-center justify-center">{translations?.profileSeePosts}</p>;
        }

        const getPostsList = () => {
            if (!posts) return [];
            if (selectedSocialType === 'instagram') return posts.data || [];
            if (selectedSocialType === 'facebook') return posts.data || [];
            if (selectedSocialType === 'tiktok') return posts.data.videos || [];
            if (selectedSocialType === 'youtube') return posts?.data || [];
            return [];
        };

        const postsList = getPostsList();

        if (postsList.length === 0 && !isPending) {
            return <div className='flex items-center justify-center h-full flex-1 rounded-md border border-gray/50 text-gray text-center text-2xl'>
                {translations?.noPostFound}
            </div>;
        }

        return (
            <>
                {selectedSocialType === 'instagram' && (
                    <InstagramPostGrid
                        posts={postsList}
                        selectedPosts={selectedPosts}
                        togglePostSelection={togglePostSelection}
                        lastPostRef={postsList.length > 0 ? lastPostElementRef : null}
                    />
                )}
                {selectedSocialType === 'facebook' && (
                    <FacebookPostGrid
                        posts={postsList}
                        selectedPosts={selectedPosts}
                        togglePostSelection={togglePostSelection}
                        lastPostRef={postsList.length > 0 ? lastPostElementRef : null}
                    />
                )}
                {selectedSocialType === 'tiktok' && (
                    <TiktokPostGrid
                        posts={postsList}
                        selectedPosts={selectedPosts}
                        togglePostSelection={togglePostSelection}
                        lastPostRef={postsList.length > 0 ? lastPostElementRef : null}
                    />
                )}
                {selectedSocialType === 'youtube' && (
                    <YoutubePostGrid
                        posts={postsList}
                        selectedPosts={selectedPosts}
                        togglePostSelection={togglePostSelection}
                        lastPostRef={postsList.length > 0 ? lastPostElementRef : null}
                    />
                )}

                {/* Loading more indicator */}
                {isLoadingMore && (
                    <div className="flex justify-center py-8">
                        <ImageLoaderSVG className="w-8 h-8" />
                    </div>
                )}

                {/* End of posts */}
                {!hasMore && postsList.length > 0 && (
                    <p className="text-center text-gray-500 py-6">No more posts</p>
                )}
            </>
        );
    };

    // Function to get correct keys for image & link based on platform
    const extractPostData = (post, platform) => {
        const socialMediaEntry = userDetails?.social_medias?.find((item) => item.social_type === platform);
        const social_media_id = socialMediaEntry?.id || "";

        switch (platform) {
            case "instagram":
                return {
                    image_link: post.media_product_type == 'REELS' ? post.thumbnail_url : post.media_url,
                    post_link: post.permalink,
                    social_post_id: post.id,
                    comment_count: Number(post.comments_count) || 0,
                    like_counts: Number(post.like_count) || 0,
                    view_counts: Number(post.view_count) || 0,
                    social_media_id: social_media_id,
                    platform: platform,
                    media_type: post.media_type
                };
            case "facebook":
                const [userId, postId] = post.id.split("_");
                let link = `https://www.facebook.com/${userId}/posts/${postId}/`;
                return {
                    image_link: post.full_picture,
                    post_link: link,
                    social_post_id: post.id,
                    comment_count: post.comments.summary.total_count || 0,
                    like_counts: post.reactions.summary.total_count || 0,
                    view_counts: 0,
                    social_media_id: social_media_id,
                    platform: platform
                };
            case "tiktok":
                return {
                    image_link: post.cover_image_url,
                    post_link: post.share_url,
                    social_post_id: post.id,
                    comment_count: post.comment_count || 0,
                    like_counts: post.like_count || 0,
                    view_counts: post.view_count || 0,
                    social_media_id: social_media_id,
                    platform: platform
                };
            case "youtube":
                const thumbnails = post?.snippet?.thumbnails;
                const thumbnailUrl =
                    thumbnails?.maxres?.url ||
                    thumbnails?.high?.url ||
                    thumbnails?.medium?.url ||
                    thumbnails?.standard?.url ||
                    thumbnails?.default?.url || '';
                return {
                    image_link: thumbnailUrl,
                    post_link: `https://www.youtube.com/watch?v=${post?.id}`,
                    social_post_id: post.id,
                    comment_count: Number(post?.statistics?.commentCount) || 0,
                    like_counts: Number(post?.statistics?.likeCount) || 0,
                    view_counts: Number(post?.statistics?.viewCount) || 0,
                    social_media_id: social_media_id,
                    platform: platform
                };
            default:
                return { image_link: "", post_link: "" };
        }
    };

    const togglePostSelection = (post) => {
        const normalizedPost = extractPostData(post, selectedSocialType);
        setSelectedPosts((prevSelected: any) => {
            const exists = prevSelected.some((p) => p.post_link === normalizedPost.post_link);
            if (exists) {
                return prevSelected.filter((p) => p.post_link !== normalizedPost.post_link);
            } else {
                return [...prevSelected, normalizedPost];
            }
        });
    };

    const removePostSelection = (post) => {
        if (!post || !post.post_link) {
            console.warn("Invalid post detected, skipping:", post);
            return;
        }

        setSelectedPosts((prevSelected: any) => {
            const exists = prevSelected.some((p) => p.post_link === post.post_link);

            if (exists) {
                return prevSelected.filter((p) => p.post_link !== post.post_link);
            } else {
                return [...prevSelected, post]; // Keep the exact post structure
            }
        });
    };

    // Post API
    const { isPending: isPendingPost, mutate } = usePost(AddPostAPI, null, (response) => {
        if (response.status == 200 || response.status == 201) {
            CustomToast("success", response?.data?.message)
            JobDetailDataRefetch();
            setUploadPost(false)
        }
    }, null);


    const handleProfileClick = (profile) => {
        setLoadMoreToken("");
        setPosts(null);
        setHasMore(true);
        setSelectedPosts([]);

        setInputLink('');
        setSelectedSocialType(profile?.social_type);
        setSelectedSocialId(profile?.id);
    }

    const renderLinkPosts = () => {
        switch (selectedSocialType) {
            case "instagram":
                return linkPosts ?
                    <InstagramLinkPostGrid posts={linkPosts} selectedPosts={selectedPosts} togglePostSelection={togglePostSelection} />
                    : <div className='flex items-center justify-center h-full flex-1 rounded-md border border-gray/50 text-gray text-center text-2xl'>{translations?.noPostFound}</div>;
            case "facebook":
                return linkPosts ? <FacebookLinkPostGrid posts={linkPosts} selectedPosts={selectedPosts} togglePostSelection={togglePostSelection} /> : <div className='flex items-center justify-center h-full flex-1 rounded-md border border-gray/50 text-gray text-center text-2xl'>{translations?.noPostFound}</div>;
            case "tiktok":
                return linkPosts ? <TiktokLinkPostGrid posts={linkPosts} selectedPosts={selectedPosts} togglePostSelection={togglePostSelection} /> : <div className='flex items-center justify-center h-full flex-1 rounded-md border border-gray/50 text-gray text-center text-2xl'>{translations?.noPostFound}</div>;
            case "youtube":
                return linkPosts ? <YoutubeLinkPostGrid posts={linkPosts} selectedPosts={selectedPosts} togglePostSelection={togglePostSelection} /> : <div className='flex items-center justify-center h-full flex-1 rounded-md border border-gray/50 text-gray text-center text-2xl'>{translations?.noPostFound}</div>;
            default:
                return <p className="text-gray text-center text-2xl font-medium rounded-md border border-gray/50 h-full flex items-center justify-center">Select a profile to see posts.</p>;
        }
    };

    const sendPost = () => {
        const combinedPosts = [...selectedPosts];
        let obj: any = {
            campaign_influencer_id: JobDetailData?.campaign?.campaignInfluencers?.[0]?.id,
            posts: combinedPosts
        }
        mutate(obj)
    }

    return (
        <>
            <div className="flex items-center justify-between mb-5 -mt-14">
                <div className="flex items-center gap-5">
                    <div className="text-black font-bold z-10 cursor-pointer" onClick={() => setUploadPost(false)}><InfluencerCloseSVG /></div>
                    <span className='lg:text-2xl md:text-xl text-lg font-bold'>{translations?.uploadPost}</span>
                </div>
                <GradientButton buttonType="button" customClass="flex items-center justify-center gap-1.5 min-w-40" onClick={sendPost} disabled={isPendingPost || selectedPosts?.length == 0} >
                    {translations?.sendPost} {isPendingPost && <LoaderSVG />}
                </GradientButton>
            </div>
            <p className='text-sm md:mb-7 mb-5'>{translations?.uploadYourPublishedPostMessage}</p>
            <div className='grid grid-cols-12 md:gap-6 gap-3 md:divide-x-2 max-md:divide-y-2 divide-lightGray'>
                <div className='xl:col-span-3 md:col-span-4 col-span-12'>
                    <h3 className='font-semibold md:text-xl text-lg md:mb-4 mb-2'>{translations?.allProfiles}</h3>
                    <div className='border border-gray/50 rounded-md overflow-hidden'>
                        {userDetails?.social_medias?.length > 0 ? (
                            userDetails.social_medias.flatMap((item: any, index: number) => {
                                let isTokenExpire = false;
                                isTokenExpire = item.is_token_expire || item.is_new_permission;
                                let profiles: any = [];

                                // Instagram Profiles
                                if (item.instagramProfiles?.length) {
                                    profiles.push(...item.instagramProfiles.map((profile: any) => ({
                                        id: item.id,
                                        social_type: "instagram",
                                        name: profile.name,
                                        username: `@${profile.user_name}`,
                                        profile_picture: profile.profile_picture_url
                                    })));
                                }

                                // Facebook Pages
                                if (item.facebookPages?.length) {
                                    profiles.push(...item.facebookPages.map((page: any) => ({
                                        id: page.id,
                                        social_type: "facebook",
                                        name: page.name,
                                        username: `@${page.user_name}`,
                                        profile_picture: page.page_logo || ""
                                    })));
                                }

                                // TikTok Profiles
                                if (item.tikTokProfiles?.length) {
                                    profiles.push(...item.tikTokProfiles.map((profile: any) => ({
                                        id: item.id,
                                        social_type: "tiktok",
                                        name: profile.display_name,
                                        username: profile.username,
                                        profile_picture: profile.avatar_url
                                    })));
                                }

                                // YouTube Channels
                                if (item.youtubeChannels?.length) {
                                    profiles.push(...item.youtubeChannels.map((channel: any) => ({
                                        id: item.id,
                                        social_type: "youtube",
                                        name: channel.title,
                                        username: channel.channel_name,
                                        profile_picture: channel.profile_picture_url
                                    })));
                                }

                                return profiles.map((profile, i) => (
                                    <>
                                        <div key={`${profile.id}-${i}`} className={`py-4 px-3 flex items-center gap-3 border-l-4 cursor-pointer
                                        ${(selectedSocialId === profile.id && !isTokenExpire)
                                                ? "border-primary bg-primary/10" :
                                                isTokenExpire
                                                    ? "border-red-500 bg-red-500/10"
                                                    : "border-transparent hover:border-primary hover:bg-primary/10"
                                            }`}
                                            onClick={() => handleProfileClick(profile)}
                                        >
                                            {/* Profile Image */}
                                            <div className="min-w-12 w-12 h-12 rounded-full bg-lightGray flex items-center justify-center overflow-hidden">
                                                <ImageWithFallback src={profile.profile_picture} alt="Profile" className="w-full h-full object-cover" width={48} height={48} />
                                            </div>

                                            {/* Username & Platform */}
                                            <div className="flex flex-col">
                                                <span className="text-base font-medium capitalize line-clamp-1">{profile.name}</span>
                                                <span className="text-xs text-gray flex items-center gap-0.5">
                                                    {iconMap[profile.social_type]} {profile.username}
                                                </span>
                                            </div>
                                        </div>
                                    </>
                                ));
                            })
                        ) : (
                            <p className="text-center p-3 text-gray-500">{translations?.profilesFound}</p>
                        )}
                    </div>
                    {selectedPosts?.length > 0 &&
                        <>
                            <h3 className='font-semibold md:text-base text-sm mb-2 mt-2'>{translations?.selectedPosts}</h3>
                            <div className='grid grid-cols-3 gap-1'>
                                {selectedPosts?.map((post: any) => (
                                    <div key={post.id} className="rounded overflow-hidden aspect-square bg-gray/50 relative">
                                        <ImageWithFallback src={post.image_link} alt="Post" width={100} height={100} className="w-full h-full object-contain" />
                                        <div className='absolute z-20 top-2 right-2 w-5 h-5 rounded-full bg-white flex items-center justify-center cursor-pointer' onClick={() => removePostSelection(post)}><RiCloseCircleLine className='text-red-500' /></div>
                                    </div>
                                ))}
                            </div>
                        </>
                    }
                </div>
                <div className='xl:col-span-9 md:col-span-8 col-span-12 md:pl-6 max-md:pt-3 flex flex-col'>
                    {!tokenExpire && !inputLink ? <>
                        {selectedSocialId && <h3 className='font-semibold md:text-xl text-lg md:mb-4 mb-2'>{translations?.postSubmitMaterials}</h3>}
                        {isFirstLoad && selectedSocialType ? <PostSkeleton /> : renderPostComponent()}
                    </>
                        :
                        <>
                            {selectedSocialId && <h3 className='font-semibold md:text-xl text-lg md:mb-4 mb-2'>{translations?.postSubmitMaterials}</h3>}
                            {fetchStatus == "fetching" ? <PostSkeleton /> :
                                <RelinkSocialMediaAccounts selectedSocialType={selectedSocialType} selectedSocialId={selectedSocialId} refetchSelf={refetch} JobDetailData={JobDetailData} />
                            }
                        </>
                    }
                    {inputLink && <>
                        <h3 className='font-semibold md:text-xl text-lg md:mb-4 mb-2'>{translations?.postSubmitMaterials}</h3>
                        {PostLinkFetchStatus == "fetching" ? <PostSkeleton /> : renderLinkPosts()}
                    </>}
                </div>
            </div>
        </>
    )
}

export default UploadPost
