import React, {useEffect, useState} from 'react';
import ReactDOM from 'react-dom';
import {getCatalogueContent} from "../../../API/contacts";
import DuaLoader from '../../UI/Loader/DuaLoader/DuaLoader';
import CreateButton from "../../UI/CreateButton/CreateButton";
import SearchBar from '../../UI/SearchBar/SearchBar';
import Usefullicon from '../../SVG/Usefull';
import ContactsList from './ContactsSearchList/ContactsList';
import UsefulPhonesModal from "./UsefulPhonesModal";
import {toastError,} from "../../../services/toaster";
import useLoading from "../../../hooks/useLoading";
import {CATALOG_ENTRY, FILTERED_CATALOGUE_ENTRY} from "../../../models/Contacts/Contacts";
import './contacts-search.scss';
import SearchIcon from "../../SVG/SearchIcon";


const ContactsSearch = () => {


    const [searchTerm, setSearchTerm] = useState<string>('')
    const [isLoading, setIsLoading] = useLoading(false);
    const [catalogueContent, setCatalogueContent] = useState<CATALOG_ENTRY[]>([]);
    const [filteredCat, setFilteredCat] = useState<FILTERED_CATALOGUE_ENTRY[]>([]);
    const [activeModal, setActiveModal] = useState<string | null>(null);

    const fetchCatalogue = async () => {
        try {
            setIsLoading(true);
            const res = await getCatalogueContent();
            setCatalogueContent(res.data);
        } catch (e) {
            toastError('Φαίνεται ότι η ενέργεια δεν ολοκληρώθηκε. Παρακαλούμε προσπαθήστε ξανά')
        } finally {
            setIsLoading(false)
        }
    }
    const closeModal = () => {
        setActiveModal(null);
    };

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

    useEffect(() => {

        if (searchTerm.length >= 3 && catalogueContent) {

            const keyword = searchTerm;
            const finalCat = catalogueContent.reduce((filtered: FILTERED_CATALOGUE_ENTRY[], obj: CATALOG_ENTRY) => {

                let found = false;
                const full_name = obj.lastname_el + " " + obj.firstname_el;
                const full_name_en = obj.lastname_en + " " + obj.firstname_en;
                const email = obj.email;
                const phone = obj.phone;
                const webpage = obj.webpage
                const skype = obj.skype


                if (full_name && full_name.includes(keyword.toUpperCase())) {
                    found = true;
                }
                if (full_name_en && full_name_en.includes(keyword.toUpperCase())) {
                    found = true;
                }
                if (email && email.includes(keyword.toLowerCase())) {
                    found = true;
                }

                if (phone && phone.includes(keyword)) {
                    found = true;
                }
                if (webpage && webpage.includes(keyword.toLowerCase())) {
                    found = true;
                }
                if (skype && skype.includes(keyword.toLowerCase())) {
                    found = true;
                }


                if (found) {
                    const filt: FILTERED_CATALOGUE_ENTRY = {

                        id: obj.id,
                        full_name: full_name.replace(keyword.toUpperCase(), `<b>${keyword.toUpperCase()}</b>`),
                        email: email.replace(keyword.toLowerCase(), `<b>${keyword.toLowerCase()}</b>`),
                        phone: phone.replaceAll(keyword, `<b>${keyword}</b>`),
                        building: obj.building_number,
                        skype: skype.replace(keyword.toLowerCase(), `<b>${keyword.toLowerCase()}</b>`),
                        webpage: webpage.replace(keyword.toLowerCase(), `<b>${keyword.toLowerCase()}</b>`),

                    }
                    return [...filtered, filt]
                }
                return filtered
// eslint-disable-next-line react-hooks/exhaustive-deps
            }, []);

            setFilteredCat(finalCat);
            setIsLoading(false);
        } else {
            setFilteredCat([]);
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [searchTerm, catalogueContent]);


    return (
        <div id={'contacts-search'}>

            {
                isLoading &&
                ReactDOM.createPortal(
                    <div className="dua-loader-portal">
                        <DuaLoader/>
                    </div>,
                    document.body
                )
            }
            <div className="search-wrapper row mb-7 gap-4">

                <div className="col">
                    <SearchBar
                        onSearch={(s) => {
                            setSearchTerm(s)
                        }}
                        value={searchTerm}
                        placeholder={`Αναζητήστε στις επαφές με βάση το Όνομα, Επώνυμο, email ή εσωτερικό τηλέφωνο (${catalogueContent?.length ?? "..."})`}

                    >
                        <div className='img-container'><SearchIcon/></div>
                        <div className='search-divider'></div>
                    </SearchBar>
                </div>
                <div className="col-auto">
                    <div className='btn-container col-auto'>
                        <CreateButton onClick={() => {
                            setActiveModal('useful')
                        }}>
                            <Usefullicon/>
                            <p>Χρησιμα Τηλεφωνα</p>
                        </CreateButton>
                    </div>
                </div>
            </div>


            <div className='contacts-search-list-container'>
                <ContactsList
                    key={'ley-' + filteredCat.length}
                    entries={filteredCat}
                    catalogueLength={filteredCat?.length}/>
            </div>
            {
                activeModal === 'useful' &&
                <UsefulPhonesModal onClose={closeModal}/>
            }
        </div>
    );
}
export default ContactsSearch;
