'use client'
import { useEffect, useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { useQuery } from "@tanstack/react-query";
import axios from "axios";
import CustomFetch from "@/Utils/APIRequest/AxiosInstance";
import { BaseURL, WithoutAuthCategoryAPI } from "@/Utils/APIRequest/Endpoints";
import { useTranslation } from "@/Utils/Hooks/useTranslate";
import { useLoading } from "@/Utils/Hooks/useLoading";
import { useRouter, useSearchParams } from "next/navigation";
import ImageWithFallback from "@/Component/Common/ImageWithFallback";
import logo from '@/assets/images/logo.png'
import SkeletonLoader from "@/Layout/SkeletonLoader";
import { CustomToast } from "@/Utils/CustomToast";
import InfluencerBox from "@/Component/Common/InfluencerBox";
import PrimaryButton from "@/Component/Common/Forms/PrimaryButton";

const WithoutAuthCategory = (props) => {
    const { slug } = props;
    const { translations } = useTranslation();
    const { startSkeletonLoading } = useLoading();
    const router = useRouter();
    const [displayData, setDisplayData] = useState([]);

    const [DetailData, setDetailData] = useState<any>(null);
    const [loading, setLoading] = useState(true);

    const fetchDetail = async () => {
        try {
            const response = await axios.get(`${BaseURL}${WithoutAuthCategoryAPI}/${slug}`);
            setDetailData(response?.data);
        } catch (error: any) {

            if (error?.response?.status === 404) {
                // Redirect to 404 page
                router.replace("/not-found");
                return;
            } else {
                CustomToast(
                    "error",
                    error?.response?.data?.message || "Something went wrong, please try again later"
                );
            }
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchDetail();
    }, [slug]);

    useEffect(() => {
        startSkeletonLoading();
    }, []);

    useEffect(() => {
        if (DetailData?.is_blurred) {
            CustomToast('error', "Your limit has been reached please try after sometime")
        }
    }, [DetailData?.is_blurred]);

    useEffect(() => {
        if (!DetailData?.data) return;

        let tempList: any = [...DetailData.data]; // clone

        if (tempList?.length < 12) {
            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++) {
                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)];

                const normalizeEngagement = (value: any) => {
                    if (!value) return 0;
                    if (typeof value === "string") {
                        return parseFloat(value.replace("%", "")) || 0;
                    }
                    return Number(value) || 0;
                };

                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
                });
            }
        }

        setDisplayData(tempList);
    }, [DetailData, loading]);

    return (
        <div className="h-screen overflow-y-auto [&::-webkit-scrollbar]:w-2 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-track]:bg-gray/10 [&::-webkit-scrollbar-thumb]:bg-gray/50 relative sm:p-6 p-4">
            <div className="mx-auto max-w-6xl">

                <div className="flex items-center justify-between mb-5">
                    <Link href="/">
                        <Image src={logo} alt='Logo' className="max-sm:w-32 sm:h-10 w-auto" />
                    </Link>
                    <PrimaryButton title={"Get Started"} onClick={() => router.push('/register')} customClass="sm:mt-0 mt-2" />
                </div>

                {loading ? (
                    <SkeletonLoader width="200" height={36} rows={1} />
                ) : (
                    <h1 className="text-3xl font-bold capitalize mb-3">
                        {DetailData?.category?.title}
                    </h1>
                )}
                {
                    (loading) ?
                        <div className='lg:grid-cols-3 md:grid-cols-2 grid-cols-1 grid gap-2.5 mt-4'>
                            <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>
                        :
                        <div className='lg:grid-cols-3 md:grid-cols-2 grid-cols-1 grid gap-2.5'>
                            {displayData?.map((influencer: any, index) => (
                                <div key={index} className='relative'>
                                    <InfluencerBox data={influencer} translations={translations} isFromWithoutAuth={true} isMock={influencer.isMock} />
                                </div>
                            ))}
                        </div>
                }
                <PrimaryButton title={"Load More"} onClick={() => router.push('/register')} customClass="mt-4" />
            </div>
        </div>

    )
}

export default WithoutAuthCategory
