import { Input } from '@/Components/ui/input';
import React, {
    forwardRef,
    InputHTMLAttributes,
    useEffect,
    useImperativeHandle,
    useRef,
} from 'react';

export default forwardRef(function TextInput(
    {
        type = 'text',
        className = '',
        id,
        startIcon = null,
        endIcon = null,
        isFocused = false,
        readOnly = false,
        value,
        ...props
    }: Omit<InputHTMLAttributes<HTMLInputElement>, 'value'> & {
        isFocused?: boolean;
        label?: string;
        id?: string;
        startIcon?: React.ReactNode;
        endIcon?: React.ReactNode;
        error?: string;
        readOnly?: boolean;
        value?: string | number | readonly string[] | null;
    },
    ref,
) {
    const localRef = useRef<HTMLInputElement>(null);

    useImperativeHandle(ref, () => ({
        focus: () => localRef.current?.focus(),
    }));

    useEffect(() => {
        if (isFocused) {
            localRef.current?.focus();
        }
    }, [isFocused]);

    const getValue = () => (readOnly ? value || '-' : (value ?? ''));

    const getClassName = () => {
        let name = `mt-1 block w-full ${className}`;
        if (startIcon) {
            name += 'pl-8';
        }
        if (readOnly) {
            name += 'border-0';
        }
        return name;
    };

    return (
        <div className="relative flex items-center justify-between gap-4">
            {startIcon}
            <Input
                {...props}
                value={getValue()}
                readOnly={readOnly}
                id={id}
                type={type}
                className={getClassName()}
                ref={localRef}
            />
            {endIcon}
        </div>
    );
});
