import React, {ReactNode, useEffect, useState} from 'react';
import NewsArticleSlider from "../UI/NewsArticleSlider/NewsArticleSlider";
import {useParams} from "react-router-dom";
import {NewsSingle} from "../../models/Wordpress/NewsSingleWP";
import {getPostsWP} from "../../API/wordpress";

type ApplicationHeaderProps = {
    children?: ReactNode
}

const ApplicationHeader = ({children}: ApplicationHeaderProps) => {

    const {application} = useParams();
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const [isLoading, setIsLoading] = useState(true);
    const [headerArticle, setHeaderArticle] = useState<NewsSingle[]>([]);
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const [headerArticleOptions, setHeaderOptions] = useState({
        totalPages: 1,
        currentPage: 1,
        currentOrder: "desc",
        currentCategory: application,
    });

    const getHeaderArticle = async () => {
        setIsLoading(true);
        const responsePosts = await getPostsWP(
            headerArticleOptions.currentPage,
            headerArticleOptions.currentOrder,
            // @ts-ignore
            headerArticleOptions.currentCategory
        );
        setIsLoading(false);

        //Fetching the featured image URL for each post
        const newsWithImages = await Promise.all(
            responsePosts.data.map(async (post) => {
                // Check if _embedded property exists and if featured media is available
                const featuredMediaId = post.featured_media;
                let featuredImageUrl = '';
                if (featuredMediaId) {
                    try {
                        const response = await fetch(`http://localhost/egovsupport/wp-json/wp/v2/media/${featuredMediaId}`);
                        const data = await response.json();
                        featuredImageUrl = data.source_url || '';
                    } catch (error) {
                        console.error('Error fetching featured image:', error);
                    }
                }
                return {...post, featuredImageUrl};
            })
        );

        setHeaderArticle(newsWithImages);
    };


    useEffect(() => {
        getHeaderArticle();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    return (

        <>
            {
                headerArticle && headerArticle.map((article) => {
                        return (

                            <NewsArticleSlider
                                key={article.id}
                                image={article.acf!.article_image! ? article.acf!.article_image!.url : ''}
                                title={article.acf!.title}
                                subtitle={article.acf!.subtitle}
                                content={article.acf!.content}
                                btnUrl={article.acf!.button_url ? article.acf!.button_url.url : ''}
                                btnLabel={article.acf!.button_label}
                            />
                        )
                    })
            }
        </>


    );
}

export default ApplicationHeader;
