import React, { useEffect, useState } from 'react'
import { RegionWiseBranchesType } from '../types/regionWiseBranch'
import util from '../lib/util'
import { SouthSvg } from '../assets/svg/SouthSvg'
import { WestSvg } from '../assets/svg/WestSvg'
import { EastSvg } from '../assets/svg/EastSvg'
import { CentralSvg } from '../assets/svg/CentralSvg'
import { NorthSvg } from '../assets/svg/NorthSvg'

const { isEmptyObject, removeDuplicate, regionSort } = util

interface Props {
    /** region wise branch object */
    regions: RegionWiseBranchesType
    /** default selected branches */
    defaultCities?: 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'
    /**clear all selected items */
    clearAll?:boolean
    /** translated "No data" label; English fallback used when omitted */
    noDataLabel?: string
}

type ItemType = { id: number, name: string | null, ta: string | null, hi: string | null, kn: string | null, bn?: string | null, te?: string | null }

type regionsKey = "south" | "west" | "east" | "north" | "central" 

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

export const RegionWiseBranches = (props: Props) => {
    const { regions, defaultCities, multiSelect = false, bulkSelect = false, callback, lang = 'en' ,clearAll, noDataLabel = 'No data' } = props

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

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

    const getKey = (key: regionsKey) => {
        const keyMapper = {
            south: <SouthSvg />,
            west: <WestSvg />,
            east: <EastSvg />,
            central: <CentralSvg />,
            north: <NorthSvg />
        }
        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: regionsKey) => {
        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) => {
                regions[key as keyof RegionWiseBranchesType].forEach((item: ItemType) => {
                        result.push(item.id);
                    });
            });
            setSelected(result)
        } else {
            setSelected([])
        }
    }

    const sortedRegion = regionSort(regions)
    
    return (
        <div>
            {isEmptyObject(sortedRegion)
                ? (noDataLabel)
                : <div>{(Object.entries(sortedRegion) as [regionsKey, ItemType[]][]).map(([key, value]) => ( value.length?
                        <div key={key} className='fr-flex fr-gap-2 fr-flex-wrap 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: ItemType) => (
                                <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 as keyof ItemType] as string | null) : null) || v?.name}
                                </div>
                            ))}
                        </div> : null
                    )
                )}</div>
            }
        </div>
    )
}
