import { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useNavigate, useParams } from 'react-router-dom';
import { casinoListByCategory } from '../../redux/_reducers/_reducers';


function CasinoListNav({ activeCasinoTab, setActiveCasinoTab }) {
    const navigate = useNavigate();
    const dispatch = useDispatch();
    const [apiData, setApiData] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const isLoggedIn = localStorage.getItem("user") ? true : false;


    useEffect(() => {
        const firstTab = casinoData[0];
        const payload = {
            category: firstTab.label.toLowerCase().replace(/\s+/g, '-'),
            limit: 1000,
        };
        setIsLoading(true);
        dispatch(casinoListByCategory(payload))
            .unwrap()
            .then((response) => {
                if (response) {
                    setApiData(response);
                } else {
                    console.warn('No data found in response:', response);
                    setApiData([]);
                }
            })
            .catch((error) => {
                console.error('API call failed:', error);
                setApiData([]);
                setIsLoading(false);
            });
    }, [dispatch]);


    const handleClick = (id) => {
        setActiveCasinoTab(id);

        const selectedTab = casinoData.find((tab) => tab.id === id);
        if (selectedTab) {
            const payload = {
                category: selectedTab.label.toLowerCase().replace(/\s+/g, '-'),
                limit: 1000,
            };
            dispatch(casinoListByCategory(payload))
                .unwrap()
                .then((response) => {
                    if (response && response) {
                        setApiData(response);
                    } else {
                        console.warn('No data found in response:', response);
                        setApiData([]);
                    }
                })
                .catch((error) => {
                    console.error('API call failed:', error);
                    setApiData([]);
                });
        }
    };
    const handleImageClick = (item) => {
        if (isLoggedIn) {
            const iframeURL = `/iframe/${item?.provider_name}/${item?.game_id}`;
            navigate(iframeURL);
        } else {
            navigate("/login");
        }
    };

    // const handleImageClick = (item) => {
    //     const iframeURL = `/iframe?game_name=${(item?.provider_name)}&id=${(item?.game_id)}`;

    //     navigate(iframeURL);
    // };

    return (
        <>
            <nav className="border-b border-gray-300 px-1 ">
                <div className="flex space-x-4 overflow-x-auto">
                    {casinoData?.map((tab) => (
                        <button
                            key={tab.id}
                            className={`py-2 px-4 lg:w-28 h-[90px] md:text-[13px] text-xs bg-[var(--dark-header)]     rounded-xl font-[600] transition-all duration-200 flex flex-col items-center justify-center ${activeCasinoTab === tab.id
                                ? "border-b-2 border-[var(--dark-header)]     bg-[var(--light-header)]   text-white uppercase"
                                : "text-white uppercase"
                                }`}
                            id={`tab-${tab.id}`}
                            type="button"
                            role="tab"
                            aria-selected={activeCasinoTab === tab.id}
                            onClick={() => handleClick(tab.id)}
                        >
                            <img src={tab.icon} alt={tab.name} className="w-[40px] h-[40px] mb-1" />
                            <p className="text-[13px] font-[600] whitespace-nowrap"> {tab.label}</p>
                        </button>
                    ))}
                </div>
            </nav>
              
            <div className="grid grid-cols-3 sm:grid-cols-3 md:grid-cols-5 gap-4">
                {apiData?.length > 0 ? (
                    apiData?.map((item, index) => (
                        <div key={index} className="p-2">
                            <div className="rounded-lg p-4">
                                {/* <div className="h-24 bg-gray-200 rounded-t-lg"></div> */}
                                <div className="flex justify-center p-2">
                                    <img
                                        onClick={() => handleImageClick(item)}
                                        className="md:w-24 h-24 object-cover rounded-md cursor-pointer"
                                        src={item.Image}
                                        alt={item.game_name}
                                    />
                                </div>
                                <p className="text-center mt-2 text-sm font-medium text-gray-700">{item.game_name}</p>
                            </div>
                        </div>
                    ))
                ) : (
                    <p className="text-center col-span-full text-gray-500">No data available. Click a tab to load content.</p>
                )}
            </div>

        </>
    );
}

export default CasinoListNav;

export const casinoData = [
    {
        id: 5000,
        icon: "/assets/dashboard/icon-lottery.png",
        label: 'baccarat',
    },
    {
        id: 5001,
        icon: "/assets/dashboard/icon-lottery.png",
        label: 'teen-patti',
    },
    {
        id: 5002,
        icon: "/assets/dashboard/icon-lottery.png",
        label: 'lucky7',
    },
    {
        id: 5003,
        icon: "/assets/dashboard/icon-lottery.png",
        label: 'dragon-tiger',
    },
    {
        id: 5004,
        icon: "/assets/dashboard/icon-lottery.png",
        label: 'baccarat',
    },
    {
        id: 5005,
        icon: "/assets/dashboard/icon-lottery.png",
        label: 'andar-bahar',
    },
    {
        id: 5006,
        icon: "/assets/dashboard/icon-lottery.png",
        label: 'poker',
    },
    {
        id: 5007,
        icon: "/assets/dashboard/icon-lottery.png",
        label: 'Bollywood',
    },
    {
        id: 5008,
        icon: "/assets/dashboard/icon-lottery.png",
        label: 'Region',
    },
    {
        id: 5009,
        icon: "/assets/dashboard/icon-lottery.png",
        label: 'holdem',
    },
];