'use client'
import { useEffect, useState } from "react"
import { useSelector } from "react-redux"
import { useRouter } from "next/navigation"
import { useQuery } from "@tanstack/react-query"
import SearchInput from "@/Component/Common/Forms/SearchInput"
import { CampaignAPI } from "@/Utils/APIRequest/Endpoints"
import CustomFetch from "@/Utils/APIRequest/AxiosInstance"
import GradientButton from "@/Component/Common/Forms/GradientButton"
import BorderButton from "@/Component/Common/Forms/BorderButton"
import { AppStore } from "@/lib/store"
import CampaignListingBox from "./CampaignListingBox"
import { useLoading } from "@/Utils/Hooks/useLoading"
import Image from "next/image"
import Link from "next/link"
import CampaignListingBoxSkeleton from "./CampaignListingBoxSkeleton"
import { useTranslation } from "@/Utils/Hooks/useTranslate"
import CreatorPreviewModal from "../CreatorPreview/CreatorPreviewModal"

const CampaignListing = () => {
  const router = useRouter();
  const { translations } = useTranslation();
  const [search, setSearch] = useState("")
  const [params, setParams] = useState<any>({ page: 1, per_page: 12, sort_by: "", sort: "DESC", });
  const [creatorPreviewOpen, setCreatorPreviewOpen] = useState(false);
  const userDetails: any = useSelector((state: AppStore) => state.userDetailSlice?.userDetails);
  const { skeletonLoading, startSkeletonLoading, stopSkeletonLoading } = useLoading();

  // API GET
  const { data: boxData, isPending, fetchStatus, refetch } = useQuery({ queryKey: [CampaignAPI, search, params], queryFn: () => CustomFetch({ url: CampaignAPI, params: { search: search, ...params } }, null, false), refetchOnWindowFocus: false, select: (data) => data?.data?.data })
  const { data: runningCampaignCount } = useQuery({
    queryKey: [`${CampaignAPI}/list`, search, 'running-count'],
    queryFn: () => CustomFetch({ url: `${CampaignAPI}/list`, params: { search, page: 1, per_page: 1, sort_by: "", sort: "DESC", status: "running" } }, null, false),
    refetchOnWindowFocus: false,
    select: (data) => data?.data?.total
  })
  const runningCampaignTotal = runningCampaignCount ?? boxData?.running?.length;

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

  const SectionHeading = ({ icon, label, count, viewAllHref }: { icon: string; label: string; count?: number; viewAllHref?: string }) => (
    <div className="flex items-center justify-between mb-5">
      <div className="flex items-center gap-3">
        <div className="h-9 w-9 rounded-xl bg-gradient-to-br from-primary/15 to-accent/15 flex items-center justify-center">
          <Image src={icon} alt={label} width={18} height={18} />
        </div>
        <div className="flex items-center gap-2.5">
          <h3 className="text-display text-lg font-bold text-neutral-900">{label}</h3>
          {count !== undefined && count > 0 && (
            <span className="inline-flex items-center justify-center h-6 min-w-6 px-2 rounded-full bg-primary/10 text-primary text-xs font-bold">
              {count}
            </span>
          )}
        </div>
      </div>
      {viewAllHref && (
        <Link href={viewAllHref} 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">
          {translations?.viewAll}
          <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>
      )}
    </div>
  );

  return (
    <>
      {/* ── Header bar ── */}
      <div className='flex md:items-center justify-between mb-6 border-b border-neutral-100 max-md:flex-col gap-3'>
        <SearchInput customInputMainClass="md:w-96" setSearch={setSearch} setParams={setParams} customClass="!bg-white" />
        <div className="flex items-center gap-2">
          <BorderButton title={translations?.viewAsCreator} buttonType='button' onClick={() => setCreatorPreviewOpen(true)} />
          <GradientButton title={translations?.createCampaign} buttonType='button' onClick={() => { router.push('/brand/my-campaigns/create-campaign') }} />
        </div>
      </div>

      {skeletonLoading ? (
        <div className="space-y-10">
          {/* Running skeleton section */}
          <div>
            <div className="flex items-center gap-3 mb-5">
              <div className="h-9 w-9 rounded-xl bg-neutral-200 animate-pulse" />
              <div className="h-6 w-24 rounded-lg bg-neutral-200 animate-pulse" />
            </div>
            <div className="grid grid-cols-1 gap-4 stagger-children">
              <CampaignListingBoxSkeleton />
              <CampaignListingBoxSkeleton />
              <CampaignListingBoxSkeleton />
            </div>
          </div>
          {/* Completed skeleton section */}
          <div>
            <div className="flex items-center gap-3 mb-5">
              <div className="h-9 w-9 rounded-xl bg-neutral-200 animate-pulse" />
              <div className="h-6 w-28 rounded-lg bg-neutral-200 animate-pulse" />
            </div>
            <div className="grid grid-cols-1 gap-4">
              <CampaignListingBoxSkeleton />
            </div>
          </div>
        </div>
      ) : (
        <>
          {((boxData !== undefined && boxData !== null) || userDetails !== undefined) ? (
            <div className="space-y-10">
              {/* ── Running section ── */}
              <section>
                <SectionHeading
                  icon="/assets/images/running.svg"
                  label={translations?.running || 'Running'}
                  count={runningCampaignTotal}
                  viewAllHref={runningCampaignTotal > (boxData?.running?.length ?? 0) ? "/brand/my-campaigns/list?status=running" : undefined}
                />
                {boxData?.running?.length > 0 ? (
                  <div className='grid grid-cols-1 gap-4 stagger-children'>
                    {boxData?.running?.map((item, index) => (
                      <CampaignListingBox itemData={item} userDetails={userDetails} key={index} refetch={refetch} translations={translations} />
                    ))}
                  </div>
                ) : (
                  <>
                    {!isPending && boxData?.running?.length == 0 && (
                      <div className='relative overflow-hidden w-full bg-gradient-to-br from-primary/5 via-white to-accent/5 border border-neutral-100 shadow-soft p-8 rounded-card flex items-center justify-center'>
                        <span aria-hidden className="pointer-events-none absolute -top-10 -right-10 h-40 w-40 rounded-full bg-primary/10 blur-3xl" />
                        <span aria-hidden className="pointer-events-none absolute -bottom-10 -left-10 h-40 w-40 rounded-full bg-accent/10 blur-3xl" />
                        <span className="relative text-neutral-500 text-sm font-medium">{translations?.noDataFound}</span>
                      </div>
                    )}
                  </>
                )}
              </section>

              {/* ── Completed section ── */}
              <section>
                <SectionHeading
                  icon="/assets/images/completed.svg"
                  label={translations?.completed || 'Completed'}
                  count={boxData?.completed?.length}
                  viewAllHref={boxData?.completed?.length > 2 ? "/brand/my-campaigns/list?status=completed" : undefined}
                />
                {boxData?.completed?.length > 0 ? (
                  <div className='grid grid-cols-1 gap-4 stagger-children'>
                    {boxData?.completed?.map((item, index) => (
                      <CampaignListingBox itemData={item} userDetails={userDetails} key={index} refetch={refetch} translations={translations} />
                    ))}
                  </div>
                ) : (
                  <>
                    {!isPending && boxData?.completed?.length == 0 && (
                      <div className='relative overflow-hidden w-full bg-gradient-to-br from-primary/5 via-white to-accent/5 border border-neutral-100 shadow-soft p-8 rounded-card flex items-center justify-center'>
                        <span aria-hidden className="pointer-events-none absolute -top-10 -right-10 h-40 w-40 rounded-full bg-primary/10 blur-3xl" />
                        <span aria-hidden className="pointer-events-none absolute -bottom-10 -left-10 h-40 w-40 rounded-full bg-accent/10 blur-3xl" />
                        <span className="relative text-neutral-500 text-sm font-medium">{translations?.noDataFound}</span>
                      </div>
                    )}
                  </>
                )}
              </section>
            </div>
          ) : (
            <div className='relative overflow-hidden text-center flex flex-col gap-4 items-center justify-center py-16 rounded-card bg-gradient-to-br from-primary/5 via-white to-accent/5 border border-neutral-100 shadow-soft'>
              <span aria-hidden className="pointer-events-none absolute -top-16 -right-10 h-56 w-56 rounded-full bg-primary/15 blur-3xl" />
              <span aria-hidden className="pointer-events-none absolute -bottom-16 -left-10 h-56 w-56 rounded-full bg-accent/15 blur-3xl" />
              <div className="relative h-14 w-14 rounded-2xl bg-gradient-to-br from-primary to-accent text-white flex items-center justify-center shadow-float text-2xl">✨</div>
              <span className='relative text-display text-xl font-bold text-neutral-900'>{userDetails?.role === 'influencer' || userDetails?.role === 'admin' ? 'No campaigns' : 'Create your first campaign now'}</span>
              {userDetails?.role === 'brand' &&
                <GradientButton title='Create Campaign' customClass={"relative !rounded-full !px-6"} onClick={() => { router.push('/brand/my-campaigns/create-campaign') }} />
              }
            </div>
          )}
        </>
      )}
      {creatorPreviewOpen && (
        <CreatorPreviewModal
          source="listing"
          search={search}
          setModal={() => setCreatorPreviewOpen(false)}
          userDetails={userDetails}
          translations={translations}
        />
      )}
    </>
  )
}

export default CampaignListing
