import { useId } from 'react'
import * as React from 'react'
import { DatePicker } from '@planview/pv-uikit'
import type { DatePickerProps } from '@planview/pv-uikit'
import { WrappingParentContext } from '../utils/context'
import { ToolbarItem, ToolbarItemView } from '../wrapper'
import type { DisplayOnType } from '../utils/'
import { DISPLAY_ON_TABLET_PORTRAIT } from '../utils/'
import { ToolbarButtonEmpty } from '../button'
import type { IconProps } from '@planview/pv-icons'
import styled from 'styled-components'

export type ToolbarDatePickerProps = Omit<DatePickerProps, 'defaultActive'> & {
    /**
     * String displayed when not editing.
     * If not used, will fall-back to value of the datepicker input (value/defaultValue/placeHolder)
     */
    label?: string
    /**
     * Icon for trigger button
     * */
    icon?: React.ReactElement<IconProps>
    /**
     * Target display of this item. Note: When this item is hidden, it does not move into the more
     * menu since there is not an equivalent menu representation.
     */
    displayOn?: DisplayOnType
    /**
     * Opt-in to override built-in behavior to remove the visible label of buttons in mobile breakpoint.
     * Set this to true to always show the visible label of button
     */
    preventLabelCollapse?: boolean
}

const DATE_PICKER_TRIGGER_ID = 'pv-toolbar-date_picker-trigger'

const ButtonWrapper = styled.div<{ $hidden: boolean }>`
    ${(props) =>
        props.$hidden
            ? 'visibility: hidden; margin: 0!important; width: 0;'
            : ''};
`

/**
 *
 * `import { ToolbarDatePicker } from '@planview/pv-toolbar'`
 *
 */
export const ToolbarDatePicker = ({
    icon,
    displayOn = DISPLAY_ON_TABLET_PORTRAIT,
    preventLabelCollapse = false,
    label = '',
    ...otherProps
}: ToolbarDatePickerProps) => {
    const [active, setActive] = React.useState(false)
    const datePickerTriggerId = `${DATE_PICKER_TRIGGER_ID}${useId()}`
    const labelValue = React.useMemo(() => {
        if (label) {
            return label
        }
        if (otherProps.value) {
            // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
            return `${otherProps.value}`
        }
        if (otherProps.defaultValue) {
            return `${otherProps.defaultValue}`
        }
        return otherProps.placeholder
    }, [
        label,
        otherProps.value,
        otherProps.defaultValue,
        otherProps.placeholder,
    ])
    /**
     * We need to stop tab behavior; Here the component will
     * toggle active and set focus to trigger. Since this happens async we need to stop
     * tabbing to next focusable item.
     */
    const tabStop: React.KeyboardEventHandler<HTMLDivElement> =
        React.useCallback((ev) => {
            if (ev.key === 'Tab') {
                ev.stopPropagation()
                ev.preventDefault()
            }
        }, [])

    return (
        <ToolbarItem displayOn={displayOn}>
            <ToolbarItemView>
                {() => (
                    <WrappingParentContext.Provider
                        value={{ wrappedInToolbarParent: true }}
                    >
                        {active ? (
                            <div role="none" onKeyDown={tabStop}>
                                <DatePicker
                                    defaultActive
                                    {...otherProps}
                                    onClose={(reason) => {
                                        setActive(false)
                                        if (
                                            reason === 'CONFIRM' ||
                                            reason === 'CONFIRM_TAB' ||
                                            reason === 'CANCEL'
                                        ) {
                                            setTimeout(() => {
                                                const el =
                                                    document.querySelector(
                                                        `[data-trigger-id="${datePickerTriggerId}"]`
                                                    )
                                                if (
                                                    el instanceof
                                                    HTMLButtonElement
                                                ) {
                                                    el.focus()
                                                }
                                            }, 0)
                                        }
                                    }}
                                />
                            </div>
                        ) : null}
                        <ButtonWrapper $hidden={active}>
                            <ToolbarButtonEmpty
                                onClick={() => {
                                    setActive(true)
                                }}
                                withCaret
                                icon={icon}
                                displayOn={displayOn}
                                data-trigger-id={datePickerTriggerId}
                                preventLabelCollapse={preventLabelCollapse}
                            >
                                {labelValue}
                            </ToolbarButtonEmpty>
                        </ButtonWrapper>
                    </WrappingParentContext.Provider>
                )}
            </ToolbarItemView>
        </ToolbarItem>
    )
}
