"use client";
import { cmsHtml } from "@/utils/cms-html";
import axios from "axios";
import { Link, useParams } from "react-router-dom";
import { ArrowLeft, CalendarRange, PersonStanding, CalendarHeart, RefreshCcw } from 'lucide-react';

import Image from "@/ui/image";
import Breadcrumb from "@/ui/breadcrumb";

import Swiper from "@/ui/swiper";
import { SwiperSlide } from 'swiper/react';

import useHomeSection from "@/hooks/use-home-section";
import { useQuery } from "@tanstack/react-query";
import { useLanguage } from "@/store/language-context";
import { useTranslation } from "react-i18next";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";

const AnotherAchievments = () => {
    const { data: achievements, isLoading } = useHomeSection({ sectionName: 'ivory_Achievements' });
    const { t } = useTranslation();
    const swiperProps = {
        loop: true,
        spaceBetween: 30,
        slidesPerView: 4,
        breakpoints: {
            0: { slidesPerView: 1 },
            680: { slidesPerView: 2 },
            1000: { slidesPerView: 3 },
            1200: { slidesPerView: 4 }
        },
        autoplay: { delay: 3000, disableOnInteraction: true },
        draggable: true,
        className: "w-full"
    };

    if (isLoading) {
        return (
            <div className="w-full my-8">
                <div className="grid grid-cols-4 gap-4 max-2xl:grid-cols-2 max-lg:grid-cols-1">
                    {[...Array(4)].map((_, i) => (
                        <div key={i} className={
                            cn(`relative items-center justify-center flex-col`,
                                `${i <= 0 ? 'flex' : 'hidden lg:flex'}`)}>
                            <div className="l-load w-96 h-60 rounded-md max-lg:w-full"></div>
                            <div className="absolute z-20 bottom-3 flex flex-col items-center w-full px-2 space-y-1">
                                <div className="l-load-dt w-3/4 h-5 rounded"></div>
                                <div className="l-load-dt w-40 h-8 rounded-md"></div>
                            </div>
                        </div>
                    ))}
                </div>
            </div>
        )
    };

    return (
        <section className="">
            <div className="flex justify-center my-6">
                <h2 className="services-header after:w-16 flex justify-center">
                    {t('home.another-achievements')}
                </h2>
            </div>
            <Swiper id={'new'} props={swiperProps} showButtons>
                {achievements.map((item, i: number) => (
                    <SwiperSlide key={item.id || i}>
                        <div className='relative flex justify-center flex-col'>
                            <div className="relative z-0">
                                <Image
                                    src={item.image}
                                    alt={item.title}
                                    className="w-full h-60 rounded-md z-0"
                                />
                            </div>
                            <div className="w-full z-10 absolute bg-primary-tw/80 h-full rounded-md"></div>
                            <div className="absolute z-20 bottom-3 flex flex-col items-center w-full !px-2 space-y-1">
                                <p className='text-white truncate my-2'>{item.title}</p>
                                <span className='flex items-center gap-2 bg-secondary-tw px-2 py-1 !text-white w-fit rounded-md'>
                                    <Link to={`/achievements/${item?.id}`} className='!text-white'>
                                        {t('custom.more-details')}
                                    </Link>
                                    <span>
                                        <ArrowLeft size={18} />
                                    </span>
                                </span>
                            </div>
                        </div>
                    </SwiperSlide>
                ))}
            </Swiper>
        </section>
    )
};

const AchievementDetails = () => {
    const { t } = useTranslation();
    const { id } = useParams();
    const { URL } = useLanguage();

    const { data: achievement, error, isLoading, refetch } = useQuery({
        queryKey: ['achievement-details', id],
        queryFn: async () => {
            try {
                const response = await axios.get(`${URL}/home-pages/${id}`);
                return response?.data?.data;
            } catch (error) {
                throw new Error(t('custom.err'));
            }
        },
        staleTime: 15 * 60 * 1000, // 15 min
        gcTime: 30 * 60 * 1000, // 30 min
        refetchOnWindowFocus: false,
        retry: 1
    });

    if (typeof document !== "undefined") document.title = `${achievement?.title || t('routes.achievement-details')}`;

    if (error) {
        return (
            <div className="text-center py-8 flex flex-col items-center justify-center gap-4 layout h-screen">
                <p className="text-red-500 text-xl">{t('custom.err')}</p>
                <div className="grid place-items-center">
                    <Button
                        variant="outline"
                        className="mt-2 bg-secondary-tw text-white px-4 py-2 rounded-md"
                        onClick={() => refetch && refetch()}
                    >
                        {t('custom.try-again')} <RefreshCcw />
                    </Button>
                </div>
            </div>
        )
    };

    if (isLoading) {
        return (
            <>
                <div className="h-10 w-full l-load-dt"></div>
                <div className="l-load-p w-full space-y-2 px-20 py-8 max-lg:px-4">
                    <div className="l-load-dt w-full h-96 rounded-lg"></div>
                    <div className="w-14 h-4 rounded-lg l-load-dt"></div>
                    <div className="w-32 h-4 rounded-lg l-load-dt"></div>
                </div>
                <div className="space-y-2 mt-8 px-20 max-lg:px-4">
                    {
                        [...Array(8)].map((_, i) => (
                            <div key={i} className="l-load-dt h-4 rounded-md w-full"></div>
                        ))
                    }
                </div>

            </>
        )
    };

    return (
        <>
            <Breadcrumb pages={[{ name: t("routes.achievements"), link: '/achievements' }, `${achievement?.title || t("routes.achievement-details")}`]} />

            <div className="layout">
                <div className="grid lg:grid-cols-[40%_58%]  max-lg:grid-cols-1 gap-8 !mb-16">
                    <div className="w-full h-[24rem] max-lg:h-full relative px-0" >
                        <Image
                            src={achievement?.image}
                            alt={achievement?.title}
                            className={"w-full h-full rounded-lg object-center"}
                        />
                    </div>
                    <section className="space-y-4  p-4" style={{ border: '1px solid #C7C7C7', borderRadius: '10px', padding: '20px' }}>
                        <div className="flex items-center !gap-4 text-secondary-tw flex-wrap">

                            {
                                achievement.days &&
                                <div className="flex items-center !gap-2">
                                    <span>
                                        <CalendarRange size={24} />
                                    </span>
                                    <span className="text-lg">
                                        {achievement.days} {t('achievements.train-day')}
                                    </span>
                                </div>
                            }

                            {achievement.number_trainer &&
                                <div className="flex items-center !gap-2">
                                    <span>
                                        <PersonStanding size={27} />
                                    </span>
                                    <span className="text-lg">
                                        {achievement.number_trainer} {t('achievements.trainer')}
                                    </span>
                                </div>
                            }

                            {
                                achievement?.date &&
                                <div className="flex items-center !gap-2">
                                    <span>
                                        <CalendarHeart size={27} />
                                    </span>
                                    <span className="text-lg">
                                        {achievement?.date}
                                    </span>
                                </div>
                            }

                        </div>
                        <div className="space-y-4 text-start">
                            <h2 className="text-2xl font-black">{achievement?.title}</h2>
                            <article dangerouslySetInnerHTML={{ __html: cmsHtml(achievement?.description, { alt: achievement?.title }) }} />
                        </div>
                    </section>
                </div>
                <AnotherAchievments />
            </div>
        </>
    );
};

export default AchievementDetails;