"use client";
import { ArrowLeft, CalendarCheck2, ChevronLeft, ChevronRight, ChevronsLeft, RefreshCcw } from "lucide-react";
import axios from "axios";
import { Link } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";

import { Button } from "@/components/ui/button";
import { useLanguage } from "@/store/language-context";
import Image from "@/ui/image";

import { useTranslation } from "react-i18next";

import { Autoplay, Navigation } from "swiper/modules";
import { SwiperSlide, Swiper } from "swiper/react";

export default function IvoryNews() {
    const { URL } = useLanguage();
    const { t } = useTranslation();

    const { data: news, error, isLoading, refetch } = useQuery({
        queryKey: ['news-ivory-home', URL],
        queryFn: async () => {
            try {
                const response = await axios.get(`${URL}/latestNews?per_page=150`);
                return response?.data?.data?.data;
            } catch (error) {
                throw new Error(t('custom.err'))
            }
        },
        staleTime: 1000 * 60 * 60 * 10, // 10HR
        gcTime: 1000 * 60 * 60 * 10,
    });

    const groupedNews = [];
    const newsArray = news as any[];

    for (let i = 0; i < newsArray?.length; i += 4) {
        const smallGroupedNews = newsArray.slice(i, i + 4);
        if (smallGroupedNews.length > 0) {
            groupedNews.push(smallGroupedNews);
        }
    }

    const newsSwiperProps = {
        className: "!w-full",
        loop: groupedNews?.length > 1,
        spaceBetween: 30,
        slidesPerView: 1,
        autoplay: { delay: 5000, disableOnInteraction: true },
        draggable: true
    };

    if (error) {
        return (
            <div className="text-center py-8 flex flex-col gap-4 layout">
                <p className="text-red-500">{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="layout max-xl:mb-10">
                <div className=" py-4 grid grid-cols-2 gap-4 max-lg:grid-cols-1 max-lg:px-4 w-full h-[32rem]">
                    <div className="w-full h-full space-y-2">
                        <div className="w-full rounded-lg l-load h-72"></div>
                        <div className="flex items-center gap-2 w-full">
                            <div className="size-8 rounded-full l-load-dt"></div>
                            <div className="w-3/4 h-4 rounded-lg l-load-dt"></div>
                        </div>
                    </div>
                    <div className="w-full h-full space-y-2">
                        {
                            [...Array(3)].map((_, i) => (
                                <div key={i} className="flex items-start gap-3">
                                    <div className="l-load w-52 rounded-lg h-[5.7rem]"></div>
                                    <div className="w-full flex items-center gap-3">
                                        <div className="size-8 rounded-full l-load-dt"></div>
                                        <div className="w-3/4 h-5 rounded-lg l-load-dt"></div>
                                    </div>
                                </div>
                            ))
                        }
                    </div>
                </div>
            </div>
        )
    };

    return (
        <section>
            <section className="pt-10 pb-4">
                <div className="flex justify-center w-full mb-4">
                    <h2 className="services-header after:w-24 flex justify-center after:-bottom-1">
                        {t('home.ivory-news')}
                    </h2>
                </div>
                <div className="flex items-center justify-between !gap-4 relative max-lg:pt-10">

                    <Button className={`border-secondary-tw border-2 text-secondary-tw prev-ivory-news ltr:rotate-180 [&_svg]:size-5 h-8 w-10 max-lg:hidden`}>
                        <ChevronRight />
                    </Button>

                    <Swiper
                        key={URL}
                        {...newsSwiperProps}
                        modules={[Navigation, Autoplay]}
                        navigation={{
                            nextEl: `.next-ivory-news`,
                            prevEl: `.prev-ivory-news`,
                        }}
                    >
                        {
                            groupedNews?.map((group, gI) => {
                                const [featured, ...restItems] = group;

                                return (
                                    <SwiperSlide className="w-full" key={gI}>
                                        <div className="grid lg:grid-cols-2 gap-4 w-full">
                                            <Link to={`/news/${featured?.id}`} className="h-full w-full">
                                                <div className="relative w-full h-72 rounded-lg">
                                                    <Image
                                                        src={featured?.image}
                                                        alt="Featured News"
                                                        className="w-full h-full object-cover rounded-lg"
                                                    />
                                                    <div className="absolute inset-0 bg-black/30 rounded-lg" />
                                                </div>

                                                <div className="px-4 py-2">
                                                    <span className="inline-flex items-center gap-1 text-sm font-semibold text-common-text">
                                                        <CalendarCheck2 size={16} />
                                                        {featured?.date}
                                                    </span>
                                                    <h3 className="text-lg font-semibold text-gray-800 mb-1">
                                                        {featured?.title}
                                                    </h3>
                                                    <p className="text-sm text-gray-700 mb-2">
                                                        {featured?.excerpt}
                                                    </p>
                                                    <p className="text-secondary-tw text-sm hover:underline inline-flex items-center gap-1"
                                                    >
                                                        {t('custom.more-details')}
                                                        <span>
                                                            <ArrowLeft size={15} className="ltr:rotate-180" />
                                                        </span>
                                                    </p>
                                                </div>
                                            </Link>

                                            <div className="space-y-4">
                                                {restItems?.map((item, rI: number) => (

                                                    <Link to={`/news/${item.id}`}
                                                        className="flex items-start gap-3" key={rI}>
                                                        <div className="relative w-40 h-[5.3rem] flex-shrink-0">
                                                            <Image
                                                                src={item.image}
                                                                alt={item?.title}
                                                                className="rounded-md object-cover w-full h-full"
                                                            />
                                                            <div className="absolute inset-0 bg-black/20 rounded-md"></div>
                                                        </div>
                                                        <div className="flex-1 min-w-0">
                                                            <b className="text-xs text-gray-600 flex items-center gap-1 mb-1">
                                                                <CalendarCheck2 size={12} />
                                                                {item.date}
                                                            </b>
                                                            <h3 className="text-sm font-semibold text-gray-800 mb-1 line-clamp-2 truncate">
                                                                {item.title}
                                                            </h3>
                                                            <p className="text-xs text-gray-600 mb-2 line-clamp-1">
                                                                {item.excerpt}
                                                            </p>
                                                            <p className="text-secondary-tw text-sm hover:underline inline-flex items-center gap-1"
                                                            >
                                                                {t('custom.more-details')}
                                                                <span>
                                                                    <ArrowLeft size={15} className="ltr:rotate-180" />
                                                                </span>
                                                            </p>
                                                        </div>
                                                    </Link>
                                                ))}
                                            </div>
                                        </div>
                                    </SwiperSlide>
                                )
                            })
                        }
                    </Swiper>

                    <Button className={`border-2 border-secondary-tw text-secondary-tw next-ivory-news ltr:rotate-180 [&_svg]:size-5 h-8 w-10 max-lg:hidden`}>
                        <ChevronLeft />
                    </Button>

                    <div className="absolute flex items-center gap-2 top-0 right-4 lg:hidden">
                        <Button className={`border-secondary-tw border-2 text-secondary-tw prev-ivory-news ltr:rotate-180 [&_svg]:size-5 h-8 w-10`}>
                            <ChevronRight />
                        </Button>

                        <Button className={`border-2 border-secondary-tw text-secondary-tw next-ivory-news ltr:rotate-180 [&_svg]:size-5 h-8 w-10`}>
                            <ChevronLeft />
                        </Button>
                    </div>
                </div>
                <div className="grid place-items-center mt-8">
                    <Button variant="outline" className="bg-warning text-white w-40 text-base" asChild>
                        <Link to={'/news'} className="flex items-center gap-2">
                            {t('home.all-news')}
                            <span>
                                <ChevronsLeft className="ltr:rotate-180" />
                            </span>
                        </Link>
                    </Button>
                </div>
            </section>
        </section>
    );
};