import * as React from 'react'
import styled from 'styled-components'
import type { DatePickerProps } from '@planview/pv-uikit'
import { DatePicker } from '@planview/pv-uikit'
import type { CellEditorParams, GridRowData } from '../types'
import type { IconProps } from '@planview/pv-icons'

export type GridEditorDatePickerProps<TDataModel extends GridRowData> = Omit<
    CellEditorParams<TDataModel>,
    'value'
> &
    Omit<
        DatePickerProps,
        | 'disabled'
        | 'readOnly'
        | 'onChange'
        | 'onClose'
        | 'goToToday'
        | 'clearDate'
        | 'defaultValue'
        | 'defaultActive'
        | 'required'
        | 'inputRef'
        | 'icon'
    > & {
        /** Input icon. Defaults to no icon. */
        icon?: React.ReactElement<IconProps> | null
    }

const StyledDatePicker = styled(DatePicker)`
    height: 100%;

    > div {
        height: 100%;
    }
`

const cleanPropForSpread = (
    props: Partial<GridEditorDatePickerProps<GridRowData>>
) => {
    const { tabIndex, columnId, rowId, mode, label, ...rest } = props
    return rest
}

export const GridEditorDatePicker = <TDataModel extends GridRowData>({
    value,
    onCancel,
    onConfirm,
    icon = null,
    ...rest
}: GridEditorDatePickerProps<TDataModel>) => {
    const wrapperRef = React.useRef<HTMLDivElement | null>(null)
    const inputRef = React.useRef<HTMLElement | undefined>(undefined)
    const valRef = React.useRef(value)
    const shiftKeyRef = React.useRef(false)

    React.useEffect(() => {
        valRef.current = value
    }, [value])

    return (
        <StyledDatePicker
            {...cleanPropForSpread(rest)}
            onKeyDownCapture={(ev) => {
                if (ev.key === 'Tab') {
                    if (ev.target === inputRef.current) {
                        shiftKeyRef.current = ev.shiftKey
                        ev.preventDefault()
                    }
                }
            }}
            inputRef={(el: HTMLElement | undefined) => (inputRef.current = el)}
            ref={wrapperRef}
            value={value}
            onClose={(reason) => {
                if (reason === 'CANCEL') {
                    onCancel()
                } else {
                    setTimeout(() => {
                        onConfirm(valRef.current, {
                            continueEditing:
                                reason === 'CONFIRM_TAB'
                                    ? shiftKeyRef.current
                                        ? 'previous'
                                        : 'next'
                                    : false,
                        })
                    })
                }
            }}
            onChange={(v) => {
                valRef.current = v
            }}
            defaultActive
            icon={icon}
        />
    )
}
