import { useArticlesStore } from '../stores/articles'
import { ref, computed, watchEffect, toValue } from "vue"
// import { useFetch } from '#app';
// import { useFetch } from "nuxt"
import { type MaybeRef, useFetch } from '#imports'
import type { CslJson, CrossrefArticle, SrcArticle } from '@/types/articles';






export function useFetchArticle(doi: MaybeRef<string> = ref("")) {
    // const article = ref<Article>()
    // const rawArticle = ref<RawArticle>()
    const srcArticle = ref<SrcArticle | null>(null)
    const store = useArticlesStore()
    const pending = ref(false)
    const doiBaseUrl = ref(new URL("https://doi.org/"));
    const url = ref(new URL(`/works/${toValue(doi)}`, " https://api.crossref.org/").href);
    const article = ref()
    const zoteroArticles = ref()

    function toAuthorsString(authors: Array<{ family: string; given: string }>) {
        return authors
            .map((curr) => {
                return `${curr.family} ${curr.given}`;
            })
            .join(", ");
    }

    function getReferenceUrl(doi: string) {
        return new URL(doi, doiBaseUrl.value).href;
    }

    function zoteroArticleToArticle(zoteroArticle: CslJson) {
        if (zoteroArticle != undefined) {
            const {
                DOI,
                title,
                "container-title": ct,
                abstract,
                issued,
                author,
                ...rest
            } = zoteroArticle;
            return {
                DOI,
                title,
                subtitle: toAuthorsString(author || []),
                author,
                containerTitle: ct,
                abstract,
                year: issued?.["date-parts"][0][0] ?? '',
                href: getReferenceUrl(DOI),
                target: "_blank",
                prependIcon: "mdi-newspaper-variant-outline",
            }
        }


    }
    function crossrefToArticle(article: CrossrefArticle): WikiArticle {
        const { title, DOI, type, "container-title": ct, "short-container-title": sct, abstract, author, issued } = article
        // let sanitizedAbstract = abstract
        const sanitizedAbstract = abstract ? /(?:\<jats\:p\>)?(.*)(?:\<\/jats\:p\>)?/.exec(abstract)?.[1] ?? '' : ''
        const sanitizedContainerTitle = sct?.length > 0 ? sct[0] : ct?.length > 0 ? ct[0] : ""
        return {
            title: title?.length > 0 ? title[0] : "",
            DOI,
            abstract: sanitizedAbstract,
            containerTitle: sanitizedContainerTitle,
            subtitle: toAuthorsString(author || []),
            author,
            year: issued?.["date-parts"][0][0] ?? '',
            href: getReferenceUrl(DOI),
            target: "_blank",
            prependIcon: "mdi-newspaper-variant-outline"
        }
    }

    function crossrefToCsl(article: CrossrefArticle): CslJson {
        const { title, DOI, type, "container-title": ct, "short-container-title": sct, abstract, author, issued } = article
        // let sanitizedAbstract = abstract
        const sanitizedAbstract = abstract ? /(?:\<jats\:p\>)?(.*)(?:\<\/jats\:p\>)?/.exec(abstract)?.[1] ?? '' : ''
        const sanitizedContainerTitle = sct?.length > 0 ? sct[0] : ct?.length > 0 ? ct[0] : ""
        return {
            title: title?.length > 0 ? title[0] : "",
            type,
            DOI,
            abstract: sanitizedAbstract,
            author,
            "container-title": sanitizedContainerTitle,
            issued

        }
    }

    if (store.articles.has(toValue(doi))) {
        const cslArticle = store.articles.get(toValue(doi))
        article.value = cslArticle ? zoteroArticleToArticle(cslArticle) : undefined
    }
    else {
        useFetch<RawArticle>(toValue(url), {
            lazy: true, server: false,
        }).then(({ data, pending: pendingUseFetch }) => {
            if (data.value?.message) {
                article.value = crossrefToArticle(data.value.message)
                store.add(crossrefToCsl(data.value.message))
            }
            pending.value = pendingUseFetch.value
        })
    }
    // const fetchCrossRef = () => {
    //     useFetch<RawArticle>(toValue(url), {
    //         lazy: true, server: false,
    //     }).then(({ data, pending: pendingUseFetch }) => {
    //         if (data.value?.message) {
    //             srcArticle.value = data.value.message
    //         }
    //         pending.value = pendingUseFetch.value
    //     })

    // }

    return { article, pending }
}