import {createRef, range} from '@befe/brick-utils'
import {TypeAsideItem} from '@befe/brick-ui-comps'
import {Dayjs} from 'dayjs'
import {getYearList} from '../../utils/date-utils'
import {UiAside} from '../../ui-comps/ui-aside'

export function createAside(
    opts: {
        getDisplayed: () => Dayjs
        onDisplayedChange: (displayed: Dayjs) => void
        handleUiUpdated: (syncScrolling: () => void) => void
    }
) {
    const asideRef = createRef<UiAside>()

    const handleYearChange = (year: string | number) => {
        opts.onDisplayedChange(opts.getDisplayed().clone().year(~~year))
    }


    function syncAsideScroll() {
        opts.handleUiUpdated(
            () => {
                if (asideRef.elem) {
                    asideRef.elem.scrollToItem(
                        opts.getDisplayed().year()
                    )
                }
            }
        )
    }

    return {
        syncAsideScroll,

        render() {
            const displayedYear = opts.getDisplayed().year()
            return (
                <UiAside
                    itemKeySelected={displayedYear}
                    onFetchPrev={
                        (firstItem: TypeAsideItem) => {
                            const currStartYear = +firstItem.key
                            return range(
                                currStartYear - 12,
                                currStartYear - 1
                            ).map(item => ({
                                key: item,
                                text: item,
                            }))
                        }
                    }
                    onFetchNext={
                        (lastItem: TypeAsideItem) => {
                            const currEndYear = +lastItem.key
                            return range(
                                currEndYear + 1,
                                currEndYear + 12
                            ).map(item => ({
                                key: item,
                                text: item,
                            }))
                        }
                    }
                    asideItems={
                        getYearList(
                            displayedYear
                        )
                    }
                    onChange={handleYearChange}
                    ref={asideRef.ref}
                />
            )
        },
    }
}
