import styles from './styles.module.css'
import Option, {OptionInterface} from '../option'
import {useContext, useEffect, useState} from "react";
import Context, {ContextInterface} from "../command/context";

interface OptionsInterface {
    optionList: OptionInterface[]
}

export default function Options({optionList}: OptionsInterface) {
    let {optionList: ol, setOptionList} = useContext<ContextInterface>(Context)
    let [availableOptions, setAvailableOptions] = useState<OptionInterface[]>(optionList);
    let [values, setValues] = useState<OptionInterface[]>([]);

    useEffect(() => {
        let result: OptionInterface[] = [];
        optionList.forEach((value, index, array) => {
            let check = values.find(item => item === value)
            !check && result.push(value)
        })
        setAvailableOptions(result)
    }, [values]);

    if (!optionList.length) {
        return <></>
    }

    let onChange = (event: any) => {
        let selectedValue = event.target.value
        let selectedOption = availableOptions.find(item => item.name === selectedValue)
        selectedOption && values.push(selectedOption)
        setValues([ ...values ])
        event.target.value = '';

        let temp = {
            ...ol
        }
        if (selectedOption) {
            temp[selectedOption.name] = '';
        }
        setOptionList(temp)
    }
    return (
        <>
            {availableOptions.length > 0 && <><select onChange={onChange}>
                <option value="">-</option>
                {availableOptions.map((option: OptionInterface, index: number) => (
                    <option key={index} value={option.name}>{option.name}</option>
                ))}
            </select>&nbsp;</>}
            {values.map((option: OptionInterface, index: number) => (
                <Option key={index} {...option} />
            ))}
        </>
    )
}
