'use client'
import { useCallback, useEffect, useRef, useState } from 'react'
import BrowseInfluencerHeader from '../BrowseInfluencerHeader'
import { useTranslation } from '@/Utils/Hooks/useTranslate';
import { useQuery } from '@tanstack/react-query';
import { PermissionAPI, RecommendBrowseInfluencerListAPI } from '@/Utils/APIRequest/Endpoints';
import CustomFetch from '@/Utils/APIRequest/AxiosInstance';
import SkeletonLoader from '@/Layout/SkeletonLoader';
import InfluencerBox from '@/Component/Common/InfluencerBox';
import useOutsideDropdown from '@/Utils/Hooks/useOutsideDropdown';
import { useDispatch, useSelector } from 'react-redux';
import { AppStore } from '@/lib/store';
import { setIsFavoriteList } from '@/lib/Features/UserDetailSidebar/userDetailSidebar';
import SidebarModal from '../SidebarModal';
import PrimaryButton from '@/Component/Common/Forms/PrimaryButton';
import { GradientGridViewSVG, GradientListViewSVG, GridViewSVG, ListViewSVG, LoaderSVG } from '@/Component/Common/SVGs/CommonSVG';
import { usePathname, useRouter } from 'next/navigation';
import LimitExceedModal from '@/Component/Common/Modal/LimitExceedModal';
import { CustomToast } from '@/Utils/CustomToast';
import BorderSelect from '@/Component/Common/Forms/BorderSelect';
import { ImageLoaderSVG } from '@/Component/Common/SVGs/AuthSVG';

const RisingFastDetail = () => {
    const router = useRouter();
    const pathName = usePathname();
    const dispatch = useDispatch();
    const { translations } = useTranslation();
    const isFavoriteList: any = useSelector((state: AppStore) => state.userDetailSidebar.isFavoriteList);
    const [searchData, setSearchData] = useState('');
    const [filteredValue, setFilteredValue] = useState<any>({});
    const [openSideModal, setOpenSideModal] = useState(null);
    const [favoriteList, setFavoriteList] = useState<any>([])
    const [params, setParams] = useState<any>({ page: 1, per_page: 12, sort_by: "engagement_rate_percentage", sort: "DESC", });

    const [allInfluencers, setAllInfluencers] = useState<any>([]);
    const [page, setPage] = useState(1);
    const [hasMore, setHasMore] = useState(true);
    const [isLoadingMore, setIsLoadingMore] = useState(false);
    const [limitReached, setLimitReached] = useState(1);
    const [limit, setLimit] = useState('');
    const [displayData, setDisplayData] = useState<any>([]);
    const userDetails: any = useSelector((state: AppStore) => state.userDetailSlice?.userDetails);
    const toastShown = useRef(false);
    const [total, setTotal] = useState('');
    const [modal, setModal] = useState<any>(null);
    const [isSorting, setIsSorting] = useState(false);
    const [listingData, setListingData] = useState(false)
    const scrollRef = useRef(null);
    const loadMoreRef = useRef<HTMLDivElement>(null);
    const [firstLoadDone, setFirstLoadDone] = useState(false);

    // const { data, isFetching } = useQuery({
    //     queryKey: [RecommendBrowseInfluencerListAPI, params],
    //     queryFn: () => {
    //         setIsLoadingMore(true);
    //         const response = CustomFetch({
    //             url: RecommendBrowseInfluencerListAPI,
    //             params: { ...params, }
    //         }, null, false);
    //         setIsLoadingMore(false);
    //     },
    //     refetchOnWindowFocus: false,
    //     select: (data) => data?.data 
    // });

    // Get Permission API
    const { data: PermissionData, isPending: PermissionLoader } = useQuery({ queryKey: [PermissionAPI], queryFn: () => CustomFetch({ url: PermissionAPI }, null, false), refetchOnWindowFocus: false, select: (data) => data?.data?.permissions });

    const { data, isFetching, fetchStatus } = useQuery({ queryKey: [RecommendBrowseInfluencerListAPI, params], queryFn: () => CustomFetch({ url: RecommendBrowseInfluencerListAPI, params: { ...params } }, null, false), refetchOnWindowFocus: false, select: (data) => data?.data })

    const { ref, isComponentVisible, setIsComponentVisible } = useOutsideDropdown();
    useEffect(() => {
        setIsComponentVisible(openSideModal ? true : false)
    }, [openSideModal])

    const hasActiveFilters = (filteredValue) => {
        if (!filteredValue || typeof filteredValue !== 'object') return false;
        const { keywords, skills, platforms, country, gender, maxEngagement, maxFollower, minEngagement, minFollower } = filteredValue;
        if (
            (Array.isArray(keywords) && keywords.length > 0) ||
            (Array.isArray(skills) && skills.length > 0) ||
            (Array.isArray(platforms) && platforms.length > 0) ||
            (Array.isArray(country) && country.length > 0) ||
            (typeof gender === 'string' && gender !== '') ||
            (minFollower && maxFollower) ||
            (minEngagement && maxEngagement)
        ) return true;
        return false;
    }

    useEffect(() => {
        if (typeof window !== "undefined" || pathName == '/brand/browse-influencer') {
            const storedValue = sessionStorage.getItem('filteredValue');
            const searchStoredValue = sessionStorage.getItem('searchValue');
            let parsed = {};
            try {
                parsed = storedValue ? JSON.parse(storedValue) : {};
            } catch {
                parsed = {};
            }

            if ((parsed && hasActiveFilters(parsed)) || (searchStoredValue && searchStoredValue !== '')) {
                router.push('/brand/browse-influencer/search')
            }
        }
    }, [filteredValue]);

    useEffect(() => {
        if (data?.data?.length > 0) {
            let tempFavList = [...isFavoriteList]; // Get the existing Redux state for favorite list

            data?.data?.forEach((list) => {
                list?.category?.influencerCategories1?.forEach((influencer) => {
                    const influencerId = influencer?.id;
                    const favoritesCount = influencer?.favoritesCount;

                    if (favoritesCount === 1) {
                        // Add influencer ID if not already in the list
                        if (!tempFavList.includes(influencerId)) {
                            tempFavList.push(influencerId);
                        }
                    } else {
                        // Remove influencer ID if favoritesCount is 0
                        tempFavList = tempFavList.filter(id => id !== influencerId);
                    }
                });
            });
            setFirstLoadDone(true);

            // Dispatch the updated favorite list to Redux store
            dispatch(setIsFavoriteList(tempFavList));
        }
    }, [data?.data, firstLoadDone]);

    useEffect(() => {
        if (data && Array.isArray(data.data)) {
            console.log('data', data);
            const incomingData = data.data;
            setAllInfluencers((prev) => {
                // If it's page 1, replace; otherwise, append
                return params.page === 1 ? incomingData : [...prev, ...incomingData];
            });
            setHasMore(data?.hasMoreResults !== 0);
            setLimitReached(data?.limitReached);
            setLimit(data?.limit);
            setTotal(data?.total);
        }
    }, [data, params.page]);

    useEffect(() => {
        let tempList: any = [...allInfluencers];

        if (tempList.length < 12 && tempList.length < total) {
            const remainder = tempList.length % 12;
            const placeholdersNeeded = remainder > 0 ? 12 - remainder : 0;

            const firstNames = ['Emma', 'Olivia', 'Liam', 'Noah', 'Sophia', 'Ava', 'Isabella', 'James', 'Lucas', 'Mia'];
            const lastNames = ['Smith', 'Johnson', 'Williams', 'Brown', 'Jones', 'Miller', 'Davis', 'Wilson', 'Moore', 'Taylor'];
            const categories = ['Fashion', 'Fitness', 'Travel', 'Tech', 'Food', 'Beauty', 'Gaming', 'Music'];

            for (let i = 0; i < placeholdersNeeded; i++) {
                // tempList.push({ id: `placeholder-${i}-${tempList.length + i}`, isPlaceholder: true });
                const firstName = firstNames[Math.floor(Math.random() * firstNames.length)];
                const lastName = lastNames[Math.floor(Math.random() * lastNames.length)];
                const category = categories[Math.floor(Math.random() * categories.length)];

                tempList.push({
                    id: `mock-${i}-${tempList.length + i}`,
                    isPlaceholder: false,
                    display_name: `${firstName} ${lastName}`,
                    country: 'HK',
                    influencerCategories: [{ category: { title: category } }],
                    total_followers: Math.floor(Math.random() * 1000000),
                    engagement_ratio: (Math.random() * 10).toFixed(1),
                    image: `https://i.pravatar.cc/150?img=${Math.floor(Math.random() * 70) + 1}`,
                    platforms: ['instagram', 'tiktok', 'facebook', 'youtube', 'xiaohongshu'],
                    social_medias: [{ social_type: 'instagram', social_user_name: `${firstName}_${lastName}` }, { social_type: 'tiktok', social_user_name: `${firstName}_${lastName}` }, { social_type: 'facebook', social_user_name: `${firstName}_${lastName}` }, { social_type: 'youtube', social_user_name: `${firstName}_${lastName}` }, { social_type: 'xiaohongshu', social_user_name: `${firstName}_${lastName}` }],
                    isMock: true // for optional custom styling if needed
                });
            }
        }

        setDisplayData(tempList);

    }, [allInfluencers]);

    // Handle Load More
    const handleLoadMore = useCallback(async () => {
        if (!firstLoadDone) return;
        if (isFetching) return; // Don't trigger while already fetching

        if (displayData.length >= limit) {
            if (userDetails?.subscription?.[0]?.plan?.plan_type == "free") {
                setModal(true)
                return
            } else {
                if (PermissionData?.upgrade_plan) {
                    setModal(true)
                    return
                }
                CustomToast("warning", 'Your browser influencers limit has been reached.');
                return
            }
        }
        if (hasMore) {
            setPage((prev) => prev + 1);
            let tempParams = { ...params, page: params.page + 1 };
            setParams(tempParams);
        }
    }, [isFetching, hasMore, firstLoadDone, params]);

    const handleSortSelection = (value) => {
        setPage(1);
        setParams({
            ...params,
            sort: value,
            page: 1,
        });
        // setAllInfluencers([]);
    };

    const handleGridList = (value) => {
        const isListView = value == "list" ? true : false;
        setListingData(isListView);
        setPage(1);
        setParams({
            ...params,
            is_list_view: isListView,
            page: 1,
        });
        setAllInfluencers([]);
    }

    // Infinite scroll handler using Intersection Observer
    useEffect(() => {
        console.log("Setting up Intersection Observer");

        const observer = new IntersectionObserver(
            (entries) => {
                entries.forEach((entry) => {
                    console.log("Intersection detected:", entry.isIntersecting, "isFetching:", isFetching, "hasMore:", hasMore);
                    if (entry.isIntersecting && !isFetching && hasMore) {
                        console.log("Loading more data...");
                        handleLoadMore();
                    }
                });
            },
            {
                root: null,
                rootMargin: '200px',
                threshold: 0.1
            }
        );

        if (loadMoreRef.current) {
            console.log("Observing loadMoreRef");
            observer.observe(loadMoreRef.current);
        }

        return () => {
            if (loadMoreRef.current) {
                observer.unobserve(loadMoreRef.current);
            }
        };
    }, [firstLoadDone, isFetching, hasMore, handleLoadMore]);

    return (
        <>
            <BrowseInfluencerHeader searchData={searchData} setSearchData={setSearchData} filteredValue={filteredValue} setFilteredValue={setFilteredValue} params={params} setParams={setParams} translations={translations} />
            <div className='flex items-center justify-between mt-6 mb-3 md:gap-5 gap-3'>
                {/* {isFetching && page === 1 ? <SkeletonLoader width="200" height={28} rows={1} /> : <h1 className="text-xl font-bold">{data?.total ? data?.total : 0} {translations?.influencerFound}</h1>} */}

                {isFetching && page === 1 ? <SkeletonLoader width="200" height={28} rows={1} /> : <h1 className="text-xl font-bold"></h1>}

                <div className='flex items-center gap-3 md:justify-end'>
                    <BorderSelect selectProps={{ name: 'sort', defaultValue: 'DESC' }} customClass='!pr-9' onChange={(e) => handleSortSelection(e.target.value)} >
                        <option value='ASC'>{translations?.lowest} {translations?.engagementRate}</option>
                        <option value='DESC'>{translations?.highest} {translations?.engagementRate}</option>
                    </BorderSelect>

                    <div className='border border-lightGray rounded-full divide-x-2 divide-lightGray hidden lg:flex'>
                        <button onClick={() => handleGridList("grid")} className={`text-base px-4 py-1.5 font-semibold flex items-center gap-2 whitespace-nowrap ${!listingData ? 'text-black' : 'text-gray'}`}>
                            {!listingData ? <GradientGridViewSVG /> : <GridViewSVG />}
                            {translations?.grid}
                        </button>
                        <button onClick={() => handleGridList("list")} className={`text-base px-4 py-1.5 font-semibold flex items-center gap-2 whitespace-nowrap ${listingData ? 'text-black' : 'text-gray'}`}>
                            {listingData ? <GradientListViewSVG /> : <ListViewSVG />}
                            {translations?.list}
                        </button>
                    </div>
                </div>
            </div>
            {isFetching && page === 1
                ?
                <div className="mt-5 grid 3xl:grid-cols-4 lg:grid-cols-3 md:grid-cols-2 grid-cols-1 gap-3">
                    <SkeletonLoader width="100%" height={203} rows={1} />
                    <SkeletonLoader width="100%" height={203} rows={1} />
                    <SkeletonLoader width="100%" height={203} rows={1} />
                    <SkeletonLoader width="100%" height={203} rows={1} />
                    <SkeletonLoader width="100%" height={203} rows={1} />
                    <SkeletonLoader width="100%" height={203} rows={1} />
                    <SkeletonLoader width="100%" height={203} rows={1} />
                    <SkeletonLoader width="100%" height={203} rows={1} />
                    <SkeletonLoader width="100%" height={203} rows={1} />
                    <SkeletonLoader width="100%" height={203} rows={1} />
                    <SkeletonLoader width="100%" height={203} rows={1} />
                    <SkeletonLoader width="100%" height={203} rows={1} />
                </div>
                :
                <>
                    {allInfluencers.length > 0 ? (
                        <>
                            {/* <div className="mt-5 grid 2xl:grid-cols-4 lg:grid-cols-3 md:grid-cols-2 grid-cols-1 gap-3"> */}
                            <div className={`${listingData ? 'grid-cols-1 overflow-y-auto overflow-x-hidden' : '3xl:grid-cols-4 lg:grid-cols-3 md:grid-cols-2 grid-cols-1'} grid gap-2.5 mt-5`}>
                                {displayData?.map((influencer, ind) => (
                                    <div key={ind} >
                                        <InfluencerBox setOpenSideModal={setOpenSideModal} data={influencer} favoriteList={favoriteList} setFavoriteList={setFavoriteList} translations={translations} isMock={influencer.isMock} setModal={setModal} listingData={listingData} />
                                    </div>
                                ))}
                            </div>
                            {/* {hasMore && (
                                <div className="mt-4">
                                    <PrimaryButton onClick={handleLoadMore} disabled={fetchStatus === 'fetching'} buttonType="button" customClass="flex items-center justify-center gap-1.5">
                                        {translations?.loadMore}
                                        {fetchStatus === 'fetching' && <LoaderSVG />}
                                    </PrimaryButton>
                                </div>
                            )} */}
                        </>
                    ) :
                        <div className="bg-gray/50 py-4 px-4 flex items-center justify-center text-center p-5 rounded-lg">
                            {translations?.noDataFound}
                        </div>
                    }
                </>
            }
            <div ref={loadMoreRef}>
                {isFetching && hasMore &&
                    <div className="mt-3 grid 3xl:grid-cols-4 lg:grid-cols-3 md:grid-cols-2 grid-cols-1 gap-3">
                        <SkeletonLoader height={203} rows={1} />
                        <div className='max-sm:hidden'><SkeletonLoader height={203} rows={1} /></div>
                        <div className='max-lg:hidden'><SkeletonLoader height={203} rows={1} /></div>
                        <div className='max-2xl:hidden'><SkeletonLoader height={203} rows={1} /></div>
                    </div>
                }
            </div>
            {isComponentVisible && <SidebarModal openSideModal={openSideModal} setOpenSideModal={setOpenSideModal} ref={ref} isComponentVisible={isComponentVisible} setIsComponentVisible={setIsComponentVisible} translations={translations} scrollRef={scrollRef} filteredValue={filteredValue} setFilteredValue={setFilteredValue} />}
            {modal && <LimitExceedModal modal={modal} setModal={setModal} translations={translations} />}
        </>
    )
}

export default RisingFastDetail
