import { FC, useState, useRef, useEffect } from "react";
import renderOneClientSelection from "./renderOneClientSelection";

interface ClientSelectionSectionProps {
    selectionData: any;
    initialSelectedClient?: any;
    onClientSelect?: (client: any) => void;
}

const ClientSelectionSection: FC<ClientSelectionSectionProps> = ({
    selectionData,
    initialSelectedClient = null,
    onClientSelect
}) => {
    const [selectedClient, setSelectedClient] = useState<any>(initialSelectedClient);
    const [isDropdownOpen, setIsDropdownOpen] = useState(false);
    const dropdownRef = useRef<HTMLDivElement>(null);

    // If there's only one client or no clients, don't show dropdown functionality
    const shouldShowAsDropdown = selectionData?.selectionList?.length > 1;

    if (!selectionData || !selectionData.selectionList || selectionData.selectionList.length === 0) {
        return null;
    }

    const handleClientSelection = (client: any) => {
        setSelectedClient(client);
        setIsDropdownOpen(false);
        if (onClientSelect) {
            onClientSelect(client);
        }
    };

    // Close dropdown when clicking outside
    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
                setIsDropdownOpen(false);
            }
        };

        document.addEventListener('mousedown', handleClickOutside);
        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, []);

    return (
        <div className="mb-3 relative" ref={dropdownRef}>
            {/* Current selection that acts as dropdown trigger */}
            <div onClick={() => shouldShowAsDropdown && setIsDropdownOpen(!isDropdownOpen)}>
                {selectedClient && renderOneClientSelection({
                    item: selectedClient,
                    isSelected: true,
                    onClickHandler: () => shouldShowAsDropdown && setIsDropdownOpen(!isDropdownOpen)
                })}
            </div>

            {/* Dropdown menu */}
            {shouldShowAsDropdown && isDropdownOpen && (
                <div className="absolute left-0 right-0 top-full mt-1 bg-white rounded-lg shadow-lg z-10 max-h-60 overflow-y-auto">
                    {selectionData.selectionList
                        .filter((client: any) => client.uu_id !== selectedClient?.uu_id)
                        .map((client: any, index: number) => (
                            <div
                                key={client.uu_id || client.id || `client-${index}`}
                                onClick={() => handleClientSelection(client)}
                            >
                                {renderOneClientSelection({
                                    item: client,
                                    isSelected: false,
                                    onClickHandler: handleClientSelection
                                })}
                            </div>
                        ))
                    }
                </div>
            )}
        </div>
    );
};

export default ClientSelectionSection;
