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

const FluidInput = styled(Input)`
    ${inputOverrides}
`

export type GridEditorInputProps<TDataModel extends GridRowData> =
    CellEditorParams<TDataModel> &
        Pick<
            InputProps,
            | 'icon'
            | 'id'
            | 'maxLength'
            | 'nativeProps'
            | 'type'
            | 'error'
            | 'placeholder'
            | 'selected'
        > & {
            /**
             * 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<GridEditorInputProps<GridRowData>>
) => {
    const { columnId, rowId, mode, label, ...rest } = props
    return rest
}

export const GridEditorInput = <TDataModel extends GridRowData>({
    value,
    onCancel,
    onConfirm,
    onChange,
    controlled = false,
    ...rest
}: GridEditorInputProps<TDataModel>) => {
    const inputRef = React.useRef<HTMLInputElement>(null)
    const { val, onChangeHandler, onKeyDownHandler } = useTextEditor(
        inputRef,
        value,
        onConfirm,
        onCancel,
        onChange,
        controlled
    )

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