import type { ChangeEvent, ComponentPropsWithRef } from 'react';
import React, { forwardRef } from 'react';
import { Form } from '@theorchard/suite-components';
import { GlyphIcon } from '@theorchard/suite-icons';

const CLASS_NAME = 'ClearableInput';

export interface Props extends ComponentPropsWithRef<typeof Form.Control> {
    labelText?: string;
    selectedValue?: string;
    onChange?: (event: ChangeEvent<HTMLInputElement>) => void;
}

export const ClearableInput: React.FC<Props> = forwardRef<
    HTMLInputElement,
    Props
>(({ labelText, selectedValue, ...props }, ref) => {
    const handleClear = () => {
        props.onChange?.({
            target: { name: props.name || '', value: '', type: 'input' },
        } as React.ChangeEvent<HTMLInputElement>);
    };

    return (
        <Form.Group className={CLASS_NAME}>
            <Form.Label>{labelText}</Form.Label>
            <Form.Control {...props} ref={ref}>
                {props.children}
            </Form.Control>
            {selectedValue && (
                <span className="clear-container">
                    <button
                        data-testid="clearable-input-clear-button"
                        type="button"
                        onClick={handleClear}
                        className="clear-button"
                    >
                        <GlyphIcon name="clear" size={16} />
                    </button>
                </span>
            )}
        </Form.Group>
    );
});

export default ClearableInput;
