import React, { useState, useEffect } from 'react';
import axiosInstance from '../../src/axiosSecure';
import common from '../../src/helpers/common';
//import { is } from 'date-fns/locale';

function PublisherSearchBox({ id, selectedId, onChange, isFocused, filterDate, showSearch = true, showList = false, showAllAuto = false, infoText = " Семеен глава" }) {
    const [selectedItem, setSelectedItem] = useState(null);

    const [searchText, setSearchText] = useState('');
    const [publishers, setPublishers] = useState([]);
    const [searchResults, setSearchResults] = useState([]);
    const [selectedDate, setSelectedDate] = useState(filterDate);


    // useEffect(() => {
    //     fetchPublishers();
    // }, []);  // Empty dependency array ensures this useEffect runs only once

    // Update publishers when filterDate or showList changes
    useEffect(() => {
        fetchPublishers();
    }, [filterDate, showList]);

    const fetchPublishers = async () => {
        console.log("fetchPublishers called");
        try {
            let url = `/api/?action=filterPublishers&select=id,firstName,lastName,email,isActive&availabilities=false`;

            if (filterDate) {
                url += `&filterDate=${common.getISODateOnly(filterDate)}`;
            }
            if (showList) {
                url += `&assignments=true`;
            }

            const { data: publishersData } = await axiosInstance.get(url);
            //setPublishers(publishersData);
            const activePublishers = publishersData.filter(publisher => publisher.isActive === true);
            setPublishers(activePublishers);

        } catch (error) {
            // Handle errors
            console.error("Error fetching publishers:", error);
        }
    };

    const handleHeadSelection = (pub) => {
        setSearchText('');
        setSearchResults([]);
        setSelectedItem(pub);
        onChange(pub); // Pass the selected parent to the parent component
    };

    //allows us to trigger a focus on the input field when we trigger to show the search box from outside
    const inputRef = React.useRef(null);
    useEffect(() => {
        console.log("isFocused changed = ", isFocused);
        if (isFocused && inputRef.current) {
            inputRef.current.focus();
        }
    }, [isFocused]);

    // Update selectedDate filter from outside
    // useEffect(() => {
    //     setSelectedDate(filterDate);
    //     console.log("filterDate changed = ", filterDate);
    // }, [filterDate]);



    // Update selectedItem when selectedId changes and also at the initial load
    useEffect(() => {
        if (publishers) {
            const head = publishers.find((publisher) => publisher.id === selectedId);
            if (head) {
                //setSearchText(`${head.firstName} ${head.lastName}`);
                setSelectedItem(head);
            }
        }
    }, [selectedId, publishers]);

    // Update searchResults when searchText or publishers change
    useEffect(() => {
        if (searchText || showAllAuto) {
            const filteredResults = publishers.filter((publisher) => {
                const fullName = `${publisher.firstName} ${publisher.lastName} `.toLowerCase();
                return fullName.includes(searchText.trim().toLowerCase())
                    || publisher.email.toLowerCase().includes(searchText.trim().toLowerCase());
            });
            setSearchResults(filteredResults);
        } else {
            setSearchResults([]);
        }
    }, [searchText, publishers]);

    return (
        <div className="relative">
            {showSearch ? (
                <>
                    <input ref={inputRef}
                        {...(id ? { id } : {})}
                        type="text"
                        value={searchText}
                        onChange={(e) => setSearchText(e.target.value)}
                        onFocus={() => { isFocused = true; }}
                        className="textbox"
                        placeholder={`${selectedItem?.firstName || ""} ${selectedItem?.lastName || ""}`}
                    />
                    {(showSearch) && (searchResults.length > 0 || showAllAuto) && (
                        <ul className="absolute bg-white border border-gray-300 w-full z-10">
                            {/* showAllAuto ? publishers : searchResults */}
                            {(searchResults).map((publisher) => (
                                <li key={publisher.id}
                                    className={`p-2 cursor-pointer hover:bg-gray-200 ${publisher.assignmentsCurrentWeek > 0 ? 'text-orange-500' : ''}`}
                                    onClick={() => { handleHeadSelection(publisher); }} >
                                    {publisher.firstName} {publisher.lastName}
                                </li>
                            ))}
                        </ul>
                    )}
                    {selectedItem && infoText && (
                        <p className="font-semibold pl-1">
                            {infoText}: {selectedItem.firstName} {selectedItem.lastName}
                        </p>
                    )}
                </>
            ) : null}
            {showList ? (
                // Display only clickable list of all publishers
                <ul className="absolute bg-white border border-gray-300 w-full z-10 overflow-y-auto">
                    {publishers.map((publisher) => (
                        <li key={publisher.id}
                            className="p-2 cursor-pointer hover:bg-gray-200"
                            onClick={() => { handleHeadSelection(publisher); }} >
                            {publisher.firstName} {publisher.lastName}
                        </li>
                    ))}
                </ul>
            ) : null
            }
        </div >
    );
}

export default PublisherSearchBox;
