import React, { useEffect, useState } from 'react'
import util from '../lib/util'

const { isEmptyObject, removeDuplicate } = util

interface Props {
    /** region wise branch object */
    languageTypes: LanguageFilterType
    /** default selected branches */
    defaultTypes?: number[]
    /** determine multiselect is required */
    multiSelect?: boolean
    /** determine bulkselect is required */
    bulkSelect?: boolean
    /** callback to get seleted braches */
    callback: any
    /** Prefered language */
    lang?: 'en' | 'ta' | 'hi' | 'kn' | 'bn' | 'te'
    /** translated "No data" label; English fallback used when omitted */
    noDataLabel?: string
}



/**
 * reusable lanaguge  filter component
 * @param props refer inetrface Props
 * @returns LanaguageFilter jsx
 */

export const LanguageFilter = (props: Props) => {
    const { languageTypes, defaultTypes, multiSelect = false,callback, lang = 'en', noDataLabel = 'No data' } = props

    const [selected, setSelected] = useState<Array<number>>([])

  
    useEffect(()=>{
        if (defaultTypes) {
            setSelected(defaultTypes)
        }
    }, [defaultTypes?.length])



    const onChange = (item: number) => {
        if (multiSelect) {
            const items = selected.includes(item) ? selected.filter((s: number) => s !== item) : [...selected, item]
            setSelected(removeDuplicate(items))
            callback(removeDuplicate(items))
        } else {
            setSelected([item])
            callback([item])
        }
    }


    return (
        <div>
            {isEmptyObject(languageTypes)
                ? (noDataLabel)
                : <div>{Object.entries(languageTypes).map(([key, value]: any) => {
                    return (
                        <div key={key} className='fr-flex fr-gap-2 fr-flex-wrap fr-item-center fr-mb-4'>
                          
                            {value?.map((v: any) => (
                                <div
                                    key={v?.id}
                                    onClick={() => onChange(v?.id)}
                                    className={`fr-py-2 fr-px-2 fr-text-md fr-rounded-full fr-cursor-pointer ${selected.includes(v?.id) ? "fr-chip-active" : "fr-chip"}`}
                                >
                                    {(lang && lang !== 'en' ? v?.[lang] : null) || v?.name}
                                </div>
                            ))}
                        </div>
                    )
                }
                )}</div>
            }
        </div>
    )
}
