import { Popover, PopoverProps } from 'antd'
import { FC, memo, useEffect } from 'react'
import Display from './Display.tsx'
import PickerPanel from './PickerPanel'
import { ICON_RESET, PickerContextProvider, usePickerContext } from './context.tsx'
import { IconUnit } from '@/components/icon/types.ts'

interface PickerProps extends Partial<PopoverProps> {
    value?: string,
    onChange?: (value: string) => void,
}

const IconPicker: FC = memo((props: PickerProps) => {

    const { state, actions: { selectIcon, togglePanel } } = usePickerContext()
    const { value, onChange } = props

    useEffect(() => {
        if (onChange && state.icon) {
            if (state.icon === ICON_RESET) {
                return onChange('')
            }
            const icon = state.icon as IconUnit
            onChange(state.icon ? `${icon.type}:${icon.componentName}` : '')
        }
    }, [ state.icon ])


    useEffect(() => {
        if (value) {
            const [ type, componentName ] = value.split(':')
            selectIcon({ type, componentName } as any)
        } else {
            selectIcon(null as any)
        }
    }, [ value ])

    return (

            <Popover
                    placement={'bottomLeft'}
                    {...props}
                    onOpenChange={(e) => {
                        togglePanel(e)
                    }}
                    showArrow={false}
                    open={state.open}
                    trigger={'click'}
                    content={<PickerPanel/>}
            >
                <Display/>
            </Popover>
    )
})

export default memo((props: PickerProps) => {
    return <PickerContextProvider value={{} as any}>
        <IconPicker {...props as any}/>
    </PickerContextProvider>
})