import React, { FC, useState, useEffect } from 'react';
//local components
import {Checkbox} from '../../../Checkbox'
import {Button} from '../../../Button'

//child components
import ExtraOptions from '../../ExtraOptions'

import { InfiniteListLoader } from '../../../InfiniteListLoader/InfiniteListLoader';

interface extraOptionsContainerProps {
    options: any,
    buttonLabel: string,
    valueField: string,
    extraOptions: {}[],
    selectedOptions: any,
    filterText: string,
    textField: string,
    extraOptionstextField: string,
    extraOptionsvalueField: string,
    isCheckAll: boolean,
    setIsCheckAll: (value: boolean) => void,
    onCloseMenu: () => void,
    onChange: (value: any) => void,
    setSelectedOptions: (option: any) => void,
}

const extraOptionsContainer: FC<extraOptionsContainerProps> = ({
    options,
    buttonLabel,
    valueField,
    extraOptions,
    selectedOptions,
    filterText,
    textField,
    extraOptionstextField,
    extraOptionsvalueField,
    isCheckAll,
    setIsCheckAll,
    onCloseMenu,
    onChange,
    setSelectedOptions,
}) => {

    const filteredOptions = options.filter( (data:any) => !filterText && true || data[textField]?.toLowerCase().includes(filterText.toLowerCase()) )
    const newOptions = [{title:"select_all"}, ...filteredOptions]

    const checkAllOptions = () => {
        const optionSize = options.length
        let selectedOptsSize = Object.keys(selectedOptions).length
        let checks = 0
        if (optionSize == selectedOptsSize){
            Object.keys(selectedOptions).forEach(key => {
                if (selectedOptions[key].length == 3){
                    checks += 1
                }
            })  
            if (checks == optionSize){
                setIsCheckAll(true)
            }
        } else {
            setIsCheckAll(false)
        }
    }

    useEffect(() => {
        checkAllOptions()
    }, [])

    const renderChecks = (values:any, index:number, key:string) => {
        const option = values[index];
        if (index === 0) {
            return(
                <div style={{padding: "10px 12px"}}>
                    <Checkbox						
                        label={"select_all"}
                        id={`${key}-${"select all"}`}
                        checked={isCheckAll}
                        onChange={ () => {
                            const tempCheck = !isCheckAll
                            setIsCheckAll(tempCheck)
                            if(tempCheck){
                                let newSelected = {}
                                options.map( (elem:any) => {
                                    newSelected = { ...newSelected, [ elem[valueField] ]:extraOptions } 
                                })                              
                                setSelectedOptions({ ...newSelected })
                            }else{
                                setSelectedOptions({})
                            }
                        }}
                    />
                </div>
            )
        } else {
            return(
                <ExtraOptions 
                    id={key}
                    label={option[textField]}
                    selectProps={{
                        extraOptions:extraOptions,
                        extraOptionstextField:extraOptionstextField,
                        extraOptionsvalueField:extraOptionsvalueField
                    }}
                    onChange={ (value:any) => {
                        setSelectedOptions(value)  
                        if ( isCheckAll && value.length != 3){
                            setIsCheckAll(false)
                        } else {
                            checkAllOptions()
                        }

                    }}
                    value={option[valueField]}
                    selectedOptions={selectedOptions}
                />
            )
        }
    }

    return(
        <React.Fragment>
            <div style={{ width:394, padding:"5px 5px" }} >                  
                <div style={{ width: "100%", height:240}}>
                    <InfiniteListLoader
                        values={newOptions}
                        itemHeight={35}
                        extraRows={7}
                        renderItem={(values, index, key) => renderChecks(values, index, key)}
                    />               
                </div>
                <br/>
                <div style={{display:"flex", justifyContent:"center"}} >
                    <Button style={{width:"100%"}}  
                        onClick={ ()=> {
                            const keys = Object.keys(selectedOptions)
                            let newSelectedOptions: any[] = []
                            keys.map( key => {
                                const data = {
                                    ...options.filter( (option: any) => option[valueField] == key )[0],
                                    options:selectedOptions[key]
                                }      
                                if (data.options.length > 0) {                          
                                    newSelectedOptions.push(data)
                                }                                   
                            })
                            onChange(newSelectedOptions)
                            onCloseMenu()
                        }} >
                        { buttonLabel }
                    </Button>
                </div>
            </div>
        </React.Fragment>
    );
}

export default extraOptionsContainer;