'use client'
import { useSelector } from "react-redux";
import moment from "moment";
import { useQuery } from "@tanstack/react-query";
import OverviewLeft from "@/Component/Common/CampaignOverview/OverviewLeft";
import OverviewRight from "@/Component/Common/CampaignOverview/OverviewRight";
import ImageWithFallback from "@/Component/Common/ImageWithFallback";
import { FacebookSVG, InstagramSVG, TiktokSVG, VerticalDotsSVG } from "@/Component/Common/SVGs/CommonSVG";
import Loader from "@/Layout/Loader";
import { AppStore } from "@/lib/store";
import CustomFetch from "@/Utils/APIRequest/AxiosInstance";
import { AdminCampaignDetailAPI } from "@/Utils/APIRequest/Endpoints";
import { formatNumber } from "@/Utils/Other/FormateNumbers";
import { YoutubeSVG } from "@/Component/Common/SVGs/AuthSVG";
import Image from "next/image";
import { useTranslation } from "@/Utils/Hooks/useTranslate";
import CampaignStatus from "@/Component/Brand/MyCampaigns/CampaignListing/CampaignStatus";
import SidebarModal from "@/Component/Brand/BrowseInfluencer/SidebarModal";
import { useState } from "react";
import CampaignInfluencer from "./CampaignInfluencer";
import RecommendInfluencer from "./RecommendInfluencer";
import { translateJobRequirements } from "@/Utils/Other/TranslateJobRequirement";
import CampaignManagementDetail from "@/Component/Brand/MyCampaigns/CampaignDetail/CampaignDetailsTabs/CampaignManagement/CampaignManagementDetail";
import CopyCampaignLinkButton from "@/Component/Common/CopyCampaignLinkButton";

const CampaignSlugDetail = (props) => {
    const { slug } = props;
    const { translations } = useTranslation();
    const userDetails: any = useSelector((state: AppStore) => state.userDetailSlice?.userDetails);
    const [openSideModal, setOpenSideModal] = useState<any>(null)
    const [openCampaignSideModal, setOpenCampaignSideModal] = useState<any>(null)
    const [activeTab, setActiveTab] = useState('campaign-influencer');

    // Get API
    const { data: CampaignDetailData, isPending, refetch } = useQuery({ queryKey: [AdminCampaignDetailAPI, slug], queryFn: () => CustomFetch({ url: `${AdminCampaignDetailAPI}/${slug}` }, null, false), refetchOnWindowFocus: false, select: (data) => data?.data?.data });

    const handleBoxClick = (event, influencer) => {
        if (event.target.tagName === 'BUTTON' || event.target.tagName === 'A' || event.target.closest('button') || event.target.closest('a')) {
            return;
        }
        setOpenSideModal(influencer);
    };

    const handleViewMoreDetails = (event, influencer) => {
        if (event.target.tagName === 'BUTTON' || event.target.tagName === 'A' || event.target.closest('button') || event.target.closest('a')) {
            return;
        }

        const sectionInfluencer = CampaignDetailData?.campaignInfluencer?.campaignInfluencers || [];
        const currentIndex = sectionInfluencer?.findIndex((item) => item?.id === influencer?.id);

        setOpenCampaignSideModal({
            slug: CampaignDetailData?.campaign?.slug,
            status: influencer?.influencer_status,
            campaignDetailId: CampaignDetailData?.campaign?.id,
            influencerData: influencer,
            sectionInfluencer,
            currentIndex: currentIndex >= 0 ? currentIndex : 0,
        });
    };

    if (isPending) {
        return <Loader />
    }

    return (
        <>
            <div className='bg-gradient-to-br from-secondary to-primary rounded-2xl md:px-6 px-4 md:py-5 py-3 text-white mb-5 relative'>
                <div className='flex items-center justify-between gap-4'>
                    <div className='flex flex-col'>
                        <span className='text-base font-medium'>{moment(CampaignDetailData?.campaign?.posting_start_date).format('DD MMM YYYY')} - {moment(CampaignDetailData?.campaign?.posting_end_date).format('DD MMM YYYY')}</span>
                        <h2 className='md:text-2xl text-xl font-semibold md:mt-4 mt-2 mb-1.5 text-white'>{CampaignDetailData?.campaign?.campaign_name}</h2>
                        <div className='flex items-center gap-2'>
                            <span className='text-sm'>{translateJobRequirements(CampaignDetailData?.campaign?.job_requirement, translations)}</span>
                            {/* <span className="rounded-full overflow-hidden">•</span>
                            <span>{Array.isArray(CampaignDetailData?.campaign?.content_type) ? CampaignDetailData?.campaign?.content_type.join(', ') : CampaignDetailData?.campaign?.content_type}</span> */}
                        </div>
                    </div>
                    {CampaignDetailData?.campaign?.slug && (
                        <CopyCampaignLinkButton
                            slug={CampaignDetailData.campaign.slug}
                            // customClass="!border-white !text-white shrink-0"
                        />
                    )}
                </div>
            </div>
            <div className='grid grid-cols-12 gap-4'>
                <div className='md:col-span-9 col-span-12'>
                    <OverviewLeft data={CampaignDetailData?.campaign} translations={translations} />
                    <div className="flex items-center justify-between gap-2.5 mt-5 mb-5">
                        <div className="flex items-center justify-between gap-5">
                            <span className={`md:text-lg font-bold cursor-pointer ${activeTab === 'campaign-influencer' ? 'text-primary' : 'text-gray'}`} onClick={() => setActiveTab('campaign-influencer')} >Campaign Influencer ({CampaignDetailData?.campaignInfluencer?.campaignInfluencers?.length})</span>
                            <span className={`md:text-lg font-bold cursor-pointer ${activeTab === 'recommend-influencer' ? 'text-primary' : 'text-gray'}`} onClick={() => setActiveTab('recommend-influencer')} >Recommend Influencer</span>
                        </div>
                    </div>
                    {activeTab === 'campaign-influencer' && <CampaignInfluencer CampaignDetailData={CampaignDetailData} userDetails={userDetails} isPending={isPending} handleBoxClick={handleBoxClick} handleViewMoreDetails={handleViewMoreDetails} />}
                    {activeTab === 'recommend-influencer' && <RecommendInfluencer campaignId={CampaignDetailData?.campaign?.id} userDetails={userDetails} translations={translations} />}
                </div>
                <div className='md:col-span-3 col-span-12 max-md:-order-1'>
                    <OverviewRight data={CampaignDetailData?.campaign} translations={translations} isPending={isPending} />
                    <div className="border border-lightGray rounded-2xl overflow-hidden mt-5 bg-white shadow">
                        <div className='py-4 px-3 bg-gradient-to-br from-secondary to-primary flex md:items-center justify-between max-md:flex-col max-md:gap-5'>
                            <div className='flex items-center gap-3 text-white'>
                                <div className='min-w-12 w-12 h-12 rounded-full overflow-hidden bg-gray'>
                                    <ImageWithFallback src={CampaignDetailData?.brandDetails?.image} alt='Profile' className='w-full h-full object-cover' height={70} width={70} />
                                </div>
                                <div className='flex flex-col gap-1.5'>
                                    <h5 className='font-semibold text-xl leading-7 text-white'>{CampaignDetailData?.brandDetails?.first_name} {CampaignDetailData?.brandDetails?.last_name}</h5>
                                    <div className='flex items-center gap-2 text-xs'>
                                        <span>{CampaignDetailData?.brandDetails?.country}</span>
                                        <span className="rounded-full overflow-hidden">•</span>
                                        <span>{CampaignDetailData?.brandDetails?.business_type}</span>
                                        <span className="rounded-full overflow-hidden">•</span>
                                        <span>{CampaignDetailData?.brandDetails?.working_people} people</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className='flex items-center lg:gap-16 gap-8 my-5 px-5'>
                            <div className='flex flex-col gap-0.5'>
                                <h6 className='font-semibold leading-5 text-base'>{CampaignDetailData?.brandDetails?.campaignCount?.[0]?.count}</h6>
                                <span className='md:text-sm text-xs'>Total Campaign</span>
                            </div>
                            <div className='flex flex-col gap-0.5'>
                                <h6 className='font-semibold leading-5 text-base'>${formatNumber(CampaignDetailData?.brandDetails?.campaignCount?.[0]?.total_budget)}</h6>
                                <span className='md:text-sm text-xs'>Total Amount Spent</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div >
            {openSideModal && <SidebarModal openSideModal={openSideModal} setOpenSideModal={setOpenSideModal} setIsComponentVisible={() => { }} translations={translations} />}
            {openCampaignSideModal && <CampaignManagementDetail openSideModal={openCampaignSideModal} setOpenSideModal={setOpenCampaignSideModal} MainListRefetch={refetch} setIsComponentVisible={() => { }} translations={translations} />}
        </>
    );
}

export default CampaignSlugDetail;
