'use client';

import s from './input.module.scss';

import React, { InputHTMLAttributes, useState } from 'react';
import clsx from 'clsx';

type InputPropsType = {
  className?: string;
  placeholder: string;
  errorMessage?: string | boolean;
} & InputHTMLAttributes<HTMLInputElement>;

const Input = ({
  placeholder,
  errorMessage,
  disabled,
  className,
  onChange,
  ...props
}: InputPropsType) => {
  const [onFocus, setOnFocus] = useState(false);

  const hasValue =
    typeof props.value === 'string'
      ? props.value.length > 0
      : props.value !== undefined && props.value !== null;

  return (
    <div>
      <div
        className={clsx(s.input, className, {
          [s['input--error']]: !!errorMessage,
        })}
      >
        <label
          className={clsx(s.input__placeholder, {
            [s.input__placeholder_active]: hasValue || onFocus,
          })}
        >
          {placeholder}
        </label>
        <input
          {...props}
          onChange={onChange}
          onFocus={(event) => {
            if (typeof props.onFocus !== 'undefined') {
              props.onFocus(event);
            }
            setOnFocus(true);
          }}
          onBlur={(event) => {
            if (typeof props.onBlur !== 'undefined') {
              props.onBlur(event);
            }
            setOnFocus(false);
          }}
          disabled={disabled}
          className={clsx(s.input__self, { [s['input--disabled']]: disabled })}
        />
      </div>
      {errorMessage && (
        <span className={s.input__errorMessage}>{errorMessage}</span>
      )}
    </div>
  );
};

export default Input;
