import React, { useState, useEffect } from "react";
import axios from "axios";
import useAxios from "../../../hooks/useAxios";
import useIsMobile from "../../../hooks/useIsMobile";
import Highlighter from "react-highlight-words";
import { Translate } from "react-translated";
import Spinner from "../Spinner";

const ContactResult = (props) => {
    const [resultArray, setresultArray] = useState([]);
    const [visibleCount, setVisibleCount] = useState(1);
    const [announcement, setAnnouncement] = useState("");
    const [vocabMap, setVocabMap] = useState({});
    const isMobile = useIsMobile();
    const { response, error, isLoading } = useAxios(
        {
            method: "get",
            url: "",
            baseURL:
                props.url +
                "/@search?&_core=directory&b_size=100&metadata_fields=taxonomy_contact_category",
            headers: {
                Accept: "application/json",
            },
            params:
                props.urlParams.SearchableText || props.urlParams.iam || props.urlParams.topics
                    ? props.urlParams
                    : {},
        },
        [props]
    );
    
    useEffect(() => {
        if (props.url) {
            axios
                .get(
                    props.url +
                        "/@directory_request_forwarder/@vocabularies/collective.taxonomy.contact_category",
                    {
                        headers: { Accept: "application/json" },
                        params: { wcatoken: "false" },
                    }
                )
                .then((res) => {
                    if (res.data?.items) {
                        const map = {};
                        res.data.items.forEach((item) => {
                            map[item.token] = item.title;
                        });
                        setVocabMap(map);
                    }
                })
                .catch(() => {});
        }
    }, [props.url]);

    useEffect(() => {
        if (response !== null) {
            setresultArray(response.items);
            props.onCount?.(response.items.length);
        } else {
            setresultArray([]);
        }
    }, [response]); // eslint-disable-line react-hooks/exhaustive-deps

    useEffect(() => {
        setVisibleCount(1);
    }, [props.urlParams]);

    return (
        <div className="search-contact">
            <div className="r-search-header">
                <h2 className="r-search-header-title">
                    <Translate text="Contacts" />
                </h2>
                <p className="r-search-header-count">
                    {resultArray.length > 0 ? (
                        <>
                            {" "}
                            {resultArray.length} <Translate text="Résultats" />{" "}
                        </>
                    ) : (
                        <Translate text="Aucun résultat" />
                    )}
                </p>
            </div>
            {isLoading ? (
                <Spinner />
            ) : (
                <ul
                    id="contact-results-list"
                    className="r-search-list"
                    aria-label="Liste des résultats dans l'annuaire"
                >
                    {(isMobile ? resultArray.slice(0, visibleCount) : resultArray).map((item, i) => (
                        <li key={i} className="r-search-item">
                            <a href={item["_url"]}>
                                <Highlighter
                                    highlightClassName="r-search-highlighter"
                                    searchWords={[props.urlParams.SearchableText]}
                                    textToHighlight={item.title}
                                />
                            {item.taxonomy_contact_category?.length > 0 && (() => {
                                const titles = item.taxonomy_contact_category.map(
                                    (token) => vocabMap[token] || token
                                );
                                const leaves = titles
                                    .filter(
                                        (title) =>
                                            !titles.some(
                                                (other) =>
                                                    other !== title && other.startsWith(title + " » ")
                                            )
                                    )
                                    .map((title) => title.split(" » ").pop());
                                return (
                                    <span className="r-search-item-category">{leaves.join(", ")}</span>
                                );
                            })()}
                            </a>
                        </li>
                    ))}
                </ul>
            )}
            <div role="status" aria-live="polite" aria-atomic="true" className="r-sr-only">
                {announcement}
            </div>
            {isMobile && resultArray.length > visibleCount && (
                <button
                    type="button"
                    className="r-load-more-btn"
                    aria-controls="contact-results-list"
                    onClick={() => {
                        const next = visibleCount + 3;
                        setVisibleCount(next);
                        setAnnouncement(`${Math.min(next, resultArray.length)} / ${resultArray.length}`);
                    }}
                >
                    <Translate text="Afficher plus" />
                </button>
            )}
        </div>
    );
};
export default ContactResult;
