'use client'

import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import Link from "next/link";
import { useQuery } from "@tanstack/react-query";
import Cookies from 'js-cookie';
import CustomFetch from "@/Utils/APIRequest/AxiosInstance";
import { useLoading } from "@/Utils/Hooks/useLoading";
import ScrollArea from "./ScrollArea";
import SkeletonLoader from "@/Layout/SkeletonLoader";
import SidebarModal from "../BrowseInfluencer/SidebarModal";
import { setIsBookMarkedList, setIsFavoriteList } from "@/lib/Features/UserDetailSidebar/userDetailSidebar";
import { AppStore } from "@/lib/store";
import { BaseURL, CampaignAPI, FavoriteListExportAPI, PermissionAPI, SaveListAPI } from "@/Utils/APIRequest/Endpoints";
import useOutsideDropdown from "@/Utils/Hooks/useOutsideDropdown";
import { useTranslation } from "@/Utils/Hooks/useTranslate";
import { CustomToast } from "@/Utils/CustomToast";
import ExportLoader from "@/Component/Admin/AdminInfluencersListing/ExportLoader";
import LimitExceedModal from "@/Component/Common/Modal/LimitExceedModal";

const SaveListSection = ({ title, count, translations, children, action }: any) => (
    <section className="rounded-card border border-neutral-100 bg-white/80 shadow-soft p-4 md:p-6">
        <div className="flex flex-col gap-3 md:flex-row md:items-end md:justify-between mb-5">
            <div className="flex flex-col gap-1.5">
                <span className="kicker">{translations?.savedCreators || 'Saved creators'}</span>
                <h2 className="text-display font-bold text-xl md:text-2xl text-neutral-900 leading-tight">{title}</h2>
                {typeof count === 'number' && (
                    <p className="text-neutral-500 text-xs md:text-sm">{count} {translations?.influencer}</p>
                )}
            </div>
            {action}
        </div>
        {children}
    </section>
);

const ExportButton = ({ onClick, label }: any) => (
    <button
        type="button"
        onClick={onClick}
        className="inline-flex w-fit items-center justify-center gap-2 rounded-xl h-11 px-5 text-xs font-semibold text-white bg-gradient-to-br from-primary to-accent shadow-float hover:shadow-pop hover:-translate-y-0.5 transition-all duration-200"
    >
        <span>{label}</span>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
            <polyline points="7 10 12 15 17 10" />
            <line x1="12" y1="15" x2="12" y2="3" />
        </svg>
    </button>
);

const ViewAllLink = ({ href, label }: any) => (
    <Link href={href} className="inline-flex items-center gap-1.5 rounded-full bg-white border border-neutral-200 text-neutral-700 hover:text-primary hover:border-primary/40 hover:shadow-soft px-4 h-9 text-xs font-semibold transition-all">
        {label}
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6"></polyline></svg>
    </Link>
);

const GridSkeleton = () => (
    <div className="grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 gap-4">
        <SkeletonLoader width="100%" height={178} rows={1} />
        <SkeletonLoader width="100%" height={178} rows={1} />
        <SkeletonLoader width="100%" height={178} rows={1} />
    </div>
);

const EmptyState = ({ label }: any) => (
    <div className='w-full min-h-[178px] rounded-card border border-neutral-100 bg-gradient-to-br from-primary/5 via-white to-accent/5 p-5 flex items-center justify-center text-center text-neutral-500 shadow-soft'>{label}</div>
);

const SaveList = () => {
    const dispatch = useDispatch();
    const { translations } = useTranslation();
    const isBookMarkedList: any = useSelector((state: AppStore) => state.userDetailSidebar.isBookMarkedList);
    const [params, setParams] = useState({ page: 1, per_page: 1000 });
    const { skeletonLoading, startSkeletonLoading, stopSkeletonLoading } = useLoading();
    const [openSideModal, setOpenSideModal] = useState(null)
    const { ref, isComponentVisible, setIsComponentVisible } = useOutsideDropdown();
    const [exportLoader, setExportLoader] = useState(false);
    const [filteredValue, setFilteredValue] = useState<any>({});
    const [modal, setModal] = useState(false);
    const userDetails: any = useSelector((state: AppStore) => state.userDetailSlice?.userDetails);

    useEffect(() => {
        setIsComponentVisible(openSideModal ? true : false)
    }, [openSideModal])

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

    // Get API
    const { data: SaveListData, fetchStatus, isPending } = useQuery({ queryKey: [SaveListAPI], queryFn: () => CustomFetch({ url: SaveListAPI, params: { ...params } }, null, false), refetchOnWindowFocus: false, select: (data) => data?.data?.data });

    // Get API
    const { data: BookmarkListData, fetchStatus: BookmarkListFetchStatus, isPending: isBookmarkListPending } = useQuery({ queryKey: [CampaignAPI], queryFn: () => CustomFetch({ url: `${CampaignAPI}/bookmarks`, params: { ...params } }, null, false), refetchOnWindowFocus: false, select: (data) => data?.data?.data });

    useEffect(() => {
        if (fetchStatus === "fetching" || BookmarkListFetchStatus == 'fetching' || isPending || isBookmarkListPending) {
            startSkeletonLoading();
        } else {
            stopSkeletonLoading();
        }
    }, [fetchStatus, BookmarkListFetchStatus, isPending, isBookmarkListPending]);

    useEffect(() => {
        if (!SaveListData?.length) {
            dispatch(setIsFavoriteList([]));
            return;
        }
        const ids = SaveListData.map((list) => list?.influencer?.id).filter(Boolean);
        dispatch(setIsFavoriteList([...new Set(ids)]));
    }, [SaveListData, dispatch]);

    useEffect(() => {
        let tempData: any = new Set([...isBookMarkedList]); // Initialize tempData as a Set to avoid duplicates

        let updated = false; // Flag to track if the list has changed

        if (BookmarkListData?.length > 0) {
            BookmarkListData.forEach((item) => {
                if (item?.campaignBookmarks?.length > 0) {
                    item?.campaignBookmarks?.forEach((result) => {
                        let value = result?.id
                        if (!tempData.has(value)) {
                            value && tempData.add(value);
                            updated = true; // Mark that an update was made
                        }
                    })
                }
            });
        }

        // Only dispatch the update if there was a change
        if (updated) {
            dispatch(setIsBookMarkedList([...tempData]));
        }
    }, [BookmarkListData]);

    const exportFavoriteList = async () => {


        if (userDetails?.subscription?.[0]?.plan?.plan_type == 'free') {
            setModal(true);
            return
        }

        setExportLoader(true);
        try {
            const access_token = Cookies.get('bat') || Cookies.get("verifyUAT");
            const url = `${BaseURL}${FavoriteListExportAPI}?access_token=${access_token}`;

            // Fetch the file as a blob
            const response = await fetch(url, { method: 'GET' });

            // Check if it's a JSON error (not a file)
            const contentType = response.headers.get('Content-Type');
            if (!response.ok || (contentType && contentType.includes('application/json'))) {
                let errorMessage = 'Export failed.';
                if (contentType && contentType.includes('application/json')) {
                    const errorData = await response.json();
                    errorMessage = errorData?.message || errorMessage;
                    if (errorData?.statusCode === 400 && PermissionData?.upgrade_plan) {
                        setModal(true);
                        return;
                    }
                } else {
                    errorMessage = await response.text() || errorMessage;
                }
                CustomToast("error", errorMessage);
                return;
            }

            // Get filename from headers or fallback
            let filename = `favorite-influencer-${Date.now()}`;

            const blob = await response.blob();

            // Create a link and trigger download
            const link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.setAttribute('download', filename);
            document.body.appendChild(link);
            link.click();
            link.remove();

            // Optional: revoke the object URL after a delay
            setTimeout(() => window.URL.revokeObjectURL(link.href), 1000);
        } catch (error: any) {
            console.error("Export error:", error);
            if (error?.status === 400 && PermissionData?.upgrade_plan) {
                setModal(true);
                return;
            }
            CustomToast("error", error.message);
        } finally {
            setExportLoader(false);
        }
    };

    const exportBookmarkList = async (slug) => {

        if (userDetails?.subscription?.[0]?.plan?.plan_type == 'free') {
            setModal(true);
            return
        }

        setExportLoader(true);
        try {

            const access_token = Cookies.get('bat') || Cookies.get("verifyUAT");
            const url = `${BaseURL}${CampaignAPI}/bookmarks/export?slug=${slug}&access_token=${access_token}`;

            // Fetch the file as a blob
            const response = await fetch(url, { method: 'GET' });

            // Check if it's a JSON error (not a file)
            const contentType = response.headers.get('Content-Type');
            if (!response.ok || (contentType && contentType.includes('application/json'))) {
                let errorMessage = 'Export failed.';
                if (contentType && contentType.includes('application/json')) {
                    const errorData = await response.json();
                    errorMessage = errorData?.message || errorMessage;
                    if (errorData?.statusCode === 400 && PermissionData?.upgrade_plan) {
                        setModal(true);
                        return;
                    }
                } else {
                    errorMessage = await response.text() || errorMessage;
                }
                CustomToast("error", errorMessage);
                return;
            }

            // Get filename from headers or fallback
            let filename = `bookmark-influencer-${Date.now()}`;

            const blob = await response.blob();

            // Create a link and trigger download
            const link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.setAttribute('download', filename);
            document.body.appendChild(link);
            link.click();
            link.remove();

            // Optional: revoke the object URL after a delay
            setTimeout(() => window.URL.revokeObjectURL(link.href), 1000);

        } catch (error: any) {
            console.error("Export error:", error);
            CustomToast("error", error?.message);
        } finally {
            setExportLoader(false);
        }
    };

    if (exportLoader) return <ExportLoader />

    return (
        <>
            <div className="space-y-6 md:space-y-8">
                <SaveListSection
                    title={translations?.myFavorites}
                    count={!skeletonLoading && SaveListData?.length > 0 ? SaveListData?.length : undefined}
                    translations={translations}
                    action={SaveListData?.length > 0 && (
                        <div className="flex flex-wrap items-center gap-3">
                            <ExportButton onClick={exportFavoriteList} label={translations?.export || 'Export'} />
                            <ViewAllLink href="/brand/save-list/favorites" label={translations?.viewAll || 'View All'} />
                        </div>
                    )}
                >
                {
                    skeletonLoading ?
                        <GridSkeleton /> :
                        SaveListData?.length > 0 ?
                            <ScrollArea items={SaveListData} setOpenSideModal={setOpenSideModal} translations={translations} />
                            : <>
                                {!isPending && SaveListData?.length == 0 &&
                                    <EmptyState label={translations?.noDataFound} />
                                }
                            </>
                }
                </SaveListSection>

                <div className="space-y-6 md:space-y-8">
                    {skeletonLoading ? (
                        <SaveListSection title={translations?.allCampaigns} translations={translations}>
                            <GridSkeleton />
                        </SaveListSection>
                    ) : BookmarkListData?.length > 0 ? (
                        <>
                            {BookmarkListData?.map((campaign) => (
                                <SaveListSection
                                    key={campaign?.id}
                                    title={campaign?.campaign_name}
                                    count={campaign?.campaignBookmarks?.length}
                                    translations={translations}
                                    action={(
                                        <div className="flex flex-wrap items-center gap-3">
                                            <ExportButton onClick={() => exportBookmarkList(campaign?.slug)} label={translations?.export || 'Export'} />
                                            <ViewAllLink href={`/brand/save-list/${campaign?.slug}`} label={translations?.viewAll || 'View All'} />
                                        </div>
                                    )}
                                >
                                    <ScrollArea items={campaign.campaignBookmarks} campaignDetailData={campaign} setOpenSideModal={setOpenSideModal} translations={translations} />
                                </SaveListSection>
                            ))}
                        </>
                    ) : (
                        <>
                            {!isPending && BookmarkListData?.length == 0 &&
                                <SaveListSection title={translations?.allCampaigns} translations={translations}>
                                    <EmptyState label={translations?.noDataFound} />
                                </SaveListSection>
                            }
                        </>
                    )}
                </div>
            </div>

            {isComponentVisible && <SidebarModal openSideModal={openSideModal} setOpenSideModal={setOpenSideModal} ref={ref} isComponentVisible={isComponentVisible} setIsComponentVisible={setIsComponentVisible} translations={translations} filteredValue={filteredValue} setFilteredValue={setFilteredValue} />}
            {modal && <LimitExceedModal setModal={setModal} modal={modal} args={{ message: "You have reached the maximum number of campaigns" }} translations={translations} />}
        </>

    )
}

export default SaveList
