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


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

}

export default function CustomRadioSelect({
                                              placeholder,
                                              value,
                                              id,
                                              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)
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [isOpen]);

    const isEmptyValue = value === null || value === undefined || value === '';


    const selectedName = !isEmptyValue
        ? React.Children.toArray(children).find((c) => (
            React.isValidElement(c) && c.props.value == value // use strict equality
        ))
        : undefined;
    const arrowColor = theme === 'search-listbox-blue' ? 'white' : '#707070'

    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">
                        {children &&
                            React.Children.map(children, (child, index) => {
                                if (React.isValidElement(child)) {
                                    const selected = value === child.props.value;
                                    if (selected) {
                                        return (
                                            <li
                                                className={child.props.disabled ? 'disabled' : ''}
                                                onClick={() => handleChange(child.props.value)}
                                                data-selected={selected}
                                                key={`${child.props.value}-${selected}-${index}`} // unique key
                                            >
                                                {child.props.children}
                                            </li>
                                        );
                                    }
                                }
                            })}
                        {children &&
                            React.Children.map(children, (child, index) => {
                                if (React.isValidElement(child)) {
                                    const selected = value === child.props.value;
                                    if (!selected) {
                                        return (

                                        <li
                                            className={child.props.disabled ? 'disabled' : ''}
                                            onClick={() => handleChange(child.props.value)}
                                            data-selected={selected}
                                            key={`${child.props.value}-${selected}-${index}`} // unique key
                                        >
                                            {child.props.children}
                                        </li>
                                        );
                                    }
                                }
                            })}
                    </ul>

                }

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

    );
}
