import * as React from 'react'
import type { InputTimeProps } from '@planview/pv-uikit'
import { InputTime } from '@planview/pv-uikit'
import type { CellEditorParams, GridRowData } from '../types'
import { inputOverrides, useTextEditor } from '../utils/input'
import { EditorWrap } from './layout'
import styled from 'styled-components'

const FluidInputTime = styled(InputTime)`
    ${inputOverrides}
`

export type GridEditorInputTimeProps<TDataModel extends GridRowData> =
    CellEditorParams<TDataModel> &
        Omit<
            InputTimeProps,
            | 'onChange'
            | 'onKeyDown'
            | 'value'
            | 'defaultValue'
            | 'icon'
            | 'iconColor'
            | 'clearable'
            | 'onClear'
            | 'password'
            | 'readOnly'
            | 'selected'
            | 'focus'
            | 'disabled'
            | 'onBlur'
            | 'onFocus'
            | 'type'
        > & {
            icon?: React.JSX.Element

            /**
             * Callback triggered after the value changes.
             **/
            onChange?: (value: string) => void

            /**
             * By default the editor will take the value from the cell, and manage all edits internally
             * to the editor. It will also update from the cell if a new value comes in during editing.
             *
             * If you want to customize this behavior, set this prop to true and provide an onChange
             * handler to take full control of value updates.
             */
            controlled?: boolean
        }

const cleanPropForSpread = (
    props: Partial<GridEditorInputTimeProps<GridRowData>>
) => {
    const { columnId, rowId, mode, label, ...rest } = props
    return rest
}
/**
 * Implementation of [Input time editor](https://design.planview.com/components/grid/grid-editors#input-time-editor) which enable users to edit values in the hh:mm format
 *
 *
 * `import { GridEditorInputTime } from '@planview/pv-grid'`
 */
export const GridEditorInputTime = <TDataModel extends GridRowData>({
    value,
    onCancel,
    onConfirm,
    onChange,
    controlled,
    ...rest
}: GridEditorInputTimeProps<TDataModel>) => {
    const inputRef = React.useRef<HTMLInputElement>(null)
    const { val, onChangeHandler, onKeyDownHandler } = useTextEditor(
        inputRef,
        value,
        onConfirm,
        onCancel,
        onChange,
        controlled
    )

    return (
        <EditorWrap>
            <FluidInputTime
                {...cleanPropForSpread(rest)}
                ref={inputRef}
                selected
                value={val as string}
                onChange={onChangeHandler}
                onKeyDown={onKeyDownHandler}
            />
        </EditorWrap>
    )
}
