"use client";
import { cmsHtml } from "@/utils/cms-html";
import axios from 'axios';
import { useEffect, useState } from 'react';
import { Link, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useQuery } from '@tanstack/react-query';
import { useLanguage } from '@/store/language-context';

import Breadcrumb from "@/ui/breadcrumb";
import Image from '@/ui/image';
import Swiper from '@/ui/swiper';

import { ArrowLeft, CalendarCheck2, } from 'lucide-react';
import { SwiperSlide } from 'swiper/react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';

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

    const [seeMore, setSeeMore] = useState(false);

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

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

    useEffect(() => {
        if (typeof document !== "undefined") document.title = `${newsDetails?.title || t('routes.news-details')} |  ${t('routes.news')}` || t('routes.news-details');
    }, [newsDetails]);

    if (isLoading) {
        return (
            <div className="layout">
                <section className=''>
                    <div className='relative'>
                        <div className='l-load-dt w-full h-[33rem] aspect-video rounded-md max-lg:h-96'></div>
                    </div>
                    <div className='text-start space-y-2 p-1'>
                        <div className="flex items-center gap-2">
                            <span>
                                <div className='l-load-dt w-8 h-8 rounded-full'></div>
                            </span>
                            <div className='l-load-dt w-24 h-4 rounded'></div>
                        </div>
                        <div className='l-load-dt w-3/4 h-6 rounded'></div>
                        <div className='space-y-3'>
                            <div className='l-load-dt w-full h-4 rounded'></div>
                            <div className='l-load-dt w-full h-4 rounded'></div>
                            <div className='l-load-dt w-5/6 h-4 rounded'></div>
                            <div className='l-load-dt w-full h-4 rounded'></div>
                            <div className='l-load-dt w-4/5 h-4 rounded'></div>
                        </div>
                    </div>
                </section>
            </div>
        )
    }

    if (!newsDetails || Object.keys(newsDetails).length === 0 || error) {
        return <div>{t('custom.no-data-page')}</div>
    }

    const swiperOptions = {
        loop: true,
        navigation: {
            nextEl: '.next-new',
            prevEl: '.prev-new',
        },
        spaceBetween: 30,
        slidesPerView: 3,
        breakpoints: {
            0: { slidesPerView: 1 },
            680: { slidesPerView: 2 },
            992: { slidesPerView: 3 },
        },
        autoplay: {
            delay: 3000,
            disableOnInteraction: true,
        },
        draggable: true,
    };

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

            <div className="layout">
                <section className='grid lg:grid-cols-[40%_56%] gap-4'>
                    <div className='relative h-80 border-2 rounded-lg'>
                        <Image
                            src={newsDetails?.image}
                            alt={newsDetails?.title}
                            className={'object-cover w-full aspect-square rounded-lg h-full'}
                        />
                    </div>
                    <div className={cn('text-start space-y-2 p-4 pb-2 border-2 rounded-lg',
                        seeMore ? 'max-h-max' : 'max-h-96'
                    )}>
                        <div className="flex items-center gap-2">
                            <span className="inline-flex items-center gap-1 text-sm font-semibold text-secondary-tw">
                                <CalendarCheck2 size={16} />
                                {newsDetails?.date}
                            </span>
                        </div>
                        <h1 className='text-xl font-semibold'>
                            {newsDetails.title}
                        </h1>
                        <article
                            dangerouslySetInnerHTML={{ __html: cmsHtml(newsDetails?.description, { alt: newsDetails?.title }) }}
                            className={cn("overflow-hidden",
                                seeMore ? 'max-h-max line-clamp-none' : 'max-h-64 line-clamp-[7]'
                            )}
                        />
                        {
                            newsDetails?.description &&
                            <Button onClick={() => setSeeMore(prev => !prev)} variant='link'
                                className='underline text-base !mt-2'>
                                {seeMore ? t('custom.show-less') : t('custom.show-more')}
                            </Button>
                        }
                    </div>
                </section>

                <div className='my-12'>
                    <div className='flex justify-center m-2'>
                        <h2 className='services-header text-xl flex justify-center after:w-14 after:-bottom-2'>
                            {t('home.another-news')}
                        </h2>
                    </div>

                    <Swiper id={'news'} props={swiperOptions} showButtons>
                        {nsLoading ? (
                            <div>
                                <div className="grid grid-cols-3 gap-4 max-2xl:grid-cols-2 max-lg:grid-cols-1">
                                    {[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>
                            </div>
                        ) : nsErr ? (
                            <div className="text-center py-8">
                                <p className="text-red-500">{t('custom.err-title')}</p>
                                <button
                                    className="mt-2 bg-secondary-tw text-white px-4 py-2 rounded-md"
                                    onClick={() => refetch && refetch()}
                                >
                                    {t('custom.try-again')}
                                </button>
                            </div>
                        ) : news.length === 0 ? (
                            <p className="text-center py-8">{t('custom.no-data')}</p>
                        ) : (
                            news.map((item, i: number) => (
                                <SwiperSlide key={item.id || i}>
                                    {
                                        item?.id !== id &&
                                        <div className='relative flex justify-center flex-col h-96'>
                                            <div className="relative z-0">
                                                <Image
                                                    src={item.image}
                                                    alt={item.title}
                                                    className="w-full h-60 rounded-t-md object-cover"
                                                />
                                                <div className="absolute inset-0 bg-primary-tw/50 rounded-lg" />
                                            </div>
                                            <div className='border border-t-0 p-2 rounded-b-lg space-y-2 h-full relative'>
                                                <div className='flex items-center gap-2'>
                                                    <CalendarCheck2 color='var(--secondary-color)' size={19} />
                                                    <span className='text-sm text-secondary-tw'>
                                                        {item?.date}
                                                    </span>
                                                </div>
                                                <p className='text-start'>
                                                    {item.title}
                                                </p>
                                                <Link to={`/news/${item?.id}`} className='flex items-center gap-2 bg-secondary-tw px-2 py-1 !text-white w-fit rounded-md text-sm absolute bottom-2 end-2'>
                                                    <span>
                                                        {t('custom.more-details')}
                                                    </span>
                                                    <span>
                                                        <ArrowLeft size={18} className="ltr:rotate-180" />
                                                    </span>
                                                </Link>
                                            </div>
                                        </div>
                                    }
                                </SwiperSlide>
                            ))
                        )}
                    </Swiper>

                </div>
            </div>
        </>
    );
};

export default NewsDetails;
