import React, { useEffect, useState } from 'react'
import util from '../lib/util'
import { TruckTypeType } from '../types/truckType'
import { OpenSvg } from '../assets/svg/OpenSvg'
import { ContainerSvg } from '../assets/svg/ContainerSvg'

const { isEmptyObject, removeDuplicate } = util

interface Props {
    /** region wise branch object */
    truckTypes: TruckTypeType
    /** 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
}

type ItemType = { id: number, name: string }

type truckTypeKey = "open" | "container"

/**
 * reusable region wise branch filter component
 * @param props refer inetrface Props
 * @returns RegionWiseBranches jsx
 */

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

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

    const openLabels: Record<string, string> = { hi: 'खुला', ta: 'ஓபன்', kn: 'ತೆರೆದ', bn: 'খোলা', te: 'తెరిచిన' }
    const containerLabels: Record<string, string> = { hi: 'क्लोज़', ta: 'க்ளோஸ்டு', kn: 'ಕ್ಲೋಜ್ಡ್', bn: 'বন্ধ', te: 'మూసిన' }
    const open = openLabels[lang] || 'Open'
    const container = containerLabels[lang] || 'Closed'

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

    const getKey = (key: truckTypeKey) => {
        const keyMapper = {
            open: <div className='fr-flex fr-justify-center fr-items-center'><OpenSvg /> <span className='fr-text-typo-icon'>{open}: </span></div>,
            container: <div className='fr-flex fr-justify-center fr-items-center'><ContainerSvg /> <span className='fr-text-typo-icon'>{container}: </span></div>
        }
        return keyMapper[key]
    }

    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])
        }
    }

    const onBulkCheck = (key: any) => {
        const checkedItems: string[] = checked.includes(key) ? checked.filter((s: string) => s !== key) : [...checked, key]
        setChecked(checkedItems)
        if (checkedItems.length) {
            const result:number[] = [];
            checkedItems.map((key: any) => {
                truckTypes[key as keyof TruckTypeType].forEach((item: ItemType) => {
                        result.push(item.id);
                    });
            });
            setSelected(result)
        } else {
            setSelected([])
        }
    }
    
    return (
        <div>
            {isEmptyObject(truckTypes)
                ? (noDataLabel)
                : <div>{Object.entries(truckTypes).map(([key, value]: any) => {
                    return (
                        <div key={key} className='fr-flex fr-gap-2 fr-flex-wrap fr-item-center fr-mb-4'>
                            {bulkSelect  ? <input
                                type="checkbox"
                                id={key}
                                name={key}
                                value={key}
                                checked={checked.includes(key)}
                                onChange={() => onBulkCheck(key)}
                            /> : null}
                            {getKey(key)}
                            {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"}`}
                                >
                                    {v?.name}
                                </div>
                            ))}
                        </div>
                    )
                }
                )}</div>
            }
        </div>
    )
}
