"use client";
import React from "react";
import { Link } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";

import axios from "axios";
import Image from "@/ui/image";
import Swiper from "@/ui/swiper";

import { ArrowLeft, ChevronsLeft, RefreshCcw } from "lucide-react";
import { SwiperSlide } from "swiper/react";
import { useTranslation } from "react-i18next";
import { useLanguage } from "@/store/language-context";
import { Button } from "@/components/ui/button";

const RecentBlogs = ({ sectionTitle }: { sectionTitle?: React.ReactNode }) => {
    const { URL } = useLanguage();
    const { t } = useTranslation();

    const { data: blogs = [], isLoading, error, refetch } = useQuery({
        queryKey: ['blogs', URL],
        queryFn: async () => {
            const response = await axios.get(`${URL}/blogs`);
            if (response.data.status === 200) {
                return response?.data?.data?.data;
            } else {
                throw new Error(t('custom.err'));
            }
        },
        retry: 1,
        refetchOnWindowFocus: false,
    });

    const blogSwiperProps = {
        loop: blogs?.length > 3,
        spaceBetween: 30,
        slidesPerView: 3,
        breakpoints: {
            0: { slidesPerView: 1 },
            680: { slidesPerView: 2 },
            1200: { slidesPerView: 3 }
        },
        autoplay: { delay: 3000, disableOnInteraction: true },
        draggable: true
    };

    if (isLoading) {
        return (
            <div className="grid grid-cols-3 gap-5 max-2xl:grid-cols-2 max-lg:grid-cols-1 w-full">
                {[1, 2, 3].map((i) => (
                    <div key={i} className={`relative flex items-center justify-center flex-col ${i === 2 || i === 1 ? 'lg:flex max-lg:hidden' : ''}`}>
                        <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>
        )
    };

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

    return (
        <div className="py-8">
            {
                sectionTitle ??
                <div className="flex justify-center mb-4">
                    <h2 className="services-header flex justify-center after:w-20">{t('routes.all-blogs')}</h2>
                </div>
            }

            <Swiper props={blogSwiperProps} id={'blog'} showButtons key={URL}>
                {blogs?.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-96 h-60 rounded-md object-cover"
                                />
                            </div>
                            <div className="absolute inset-0 bg-primary-tw/80 rounded-lg" />
                            <div className="absolute z-20 bottom-3 flex flex-col items-center w-full !px-2 space-y-1">
                                <p className='text-white h-16 text-center'>{item.title}</p>
                                <Link to={`/blogs/${item?.id}`} className='flex items-center gap-2 bg-secondary-tw px-2 py-1 !text-white w-fit rounded-md text-sm'>
                                    <span>
                                        {t('custom.more-details')}
                                    </span>
                                    <span>
                                        <ArrowLeft size={18} className="ltr:rotate-180" />
                                    </span>
                                </Link>
                            </div>
                        </div>
                    </SwiperSlide>
                ))}
            </Swiper>
            <div className="grid place-items-center my-8">
                <Button variant="outline" className="bg-warning text-white w-48 text-base" asChild>
                    <Link to={'/blogs'} className="flex items-center gap-2">
                        {t('home.all-blogs')}
                        <span>
                            <ChevronsLeft className="ltr:rotate-180" />
                        </span>
                    </Link>
                </Button>
            </div>
        </div>
    );
};

export default RecentBlogs;