import React, {ReactNode, useEffect, useRef, useState} from "react";
import './customradioselect.scss'
import DownArrow from "../../SVG/DownArrow";


interface CustomRadioSelectProps {
    placeholder?: string
    children: ReactNode[]
    disabled?: boolean
    handleChange: (n: string) => void
    value?: any
    isLoading?: boolean
    theme?: 'default' | 'service-header' | 'search-listbox' | 'form-options'
    hasError?: string
    isForGate?: boolean
    validation?: (v: any) => void
    arrowColor?: string
}

export default function CustomRadioSelect({arrowColor,
                                              placeholder,
                                              value,
                                              disabled = false,
                                              children,
                                              handleChange,
                                              isLoading = false,
                                              theme = 'default',
                                              hasError = '',
                                              validation
                                          }: CustomRadioSelectProps) {

    const [isOpen, setIsOpen] = useState(false)
    const selectRef = useRef(null)
    const prevState = useRef<boolean | null>(null)

    useEffect(() => {

        /**
         * we want to run validation when we go from open to close state, but no the first time it mounts
         */
        prevState.current == true && !isOpen && validation && validation(Number(value))
        prevState.current = isOpen

        const handleClick = (e: any) => {
            if (isOpen) {
                if (e.source && e.source.current === selectRef.current) return
                setIsOpen(false)
            }
        }
        window.addEventListener('click', handleClick)
        return () => {
            window.removeEventListener('click', handleClick)
        }
    }, [isOpen]);


    let selectedName = children?.find(c => {
        // @ts-ignore
        return c.props.value == value
    })


    return (
        <>
            <div className={`custom-radio-select ${theme} ${hasError && 'hasError'}`}>
                <div ref={selectRef} className={`select-head ${disabled && 'disabled'} ${isLoading && 'loading'}`}
                     onClick={(e) => {
                         if (isLoading) return
                         // @ts-ignore
                         e.nativeEvent.source = selectRef
                         setIsOpen(true)
                     }}>
                    {/*<p>{(<span>{selectedName}</span>) || <span className="placeholder">"Παρακαλώ επιλέξτε"</span> }</p>*/}
                    <ul className="select-selected">{selectedName ||
                        <span className="select-placeholder">{placeholder}</span>}</ul>
                    <span className={"down-arrow"}><DownArrow color={arrowColor}/></span>
                </div>
                {
                    isOpen && !disabled &&
                    <ul className="options">

                        {
                            React.Children.map(children, child => {
                                // Checking isValidElement is the safe way and avoids a
                                // typescript error too.
                                // @ts-ignore
                                const selected = value == child.props.value
                                if (React.isValidElement(child)) {
                                    return React.cloneElement(child, {
                                        // @ts-ignore
                                        onClick: () => handleChange(child.props.value),
                                        selected,
                                        key: child.props.value
                                    });
                                }
                                return child;
                            })
                        }
                    </ul>
                }

            </div>
            {
                hasError &&  <p className={'error-message'}>{hasError}</p>
            }
        </>

    );
}
