import React, { FC, useState, useEffect } from 'react';
import { typeHelpers } from '../../shared';
import { BaseInput } from '../BaseInput';

type BaseInputProps = React.ComponentProps<typeof BaseInput>;

export interface Props
  extends typeHelpers.Omit<BaseInputProps, 'onChange' | 'onFocus' | 'onBlur'> {
  value?: string;
  onChange?: (e: any) => void;
  onFocus?: (e: any) => void;
  onBlur?: (e: any) => void;
  https?: boolean;
}

export const UrlInput: FC<Props> = (props) => {
  const { name, value, onChange, onBlur, ...otherProps } = props;
  const [currentValue, setCurrentValue] = useState(value || '');

  const setFormattedValue = (_value: string) => {
    const formattedValue = /^https?:/.test(_value)
      ? _value
      : `http${props.https ? 's' : ''}://${_value}`;
    setCurrentValue(formattedValue);
  };

  const handleChange = (e: any) => {
    setCurrentValue(e.target.value);
    if (onChange) onChange(e);
  };

  const handleBlur = (e: any) => {
    if (e.target.value !== '') {
      setFormattedValue(e.target.value);
    }

    if (onBlur) onBlur(e);
  };

  useEffect(() => {
    if (value) {
      setCurrentValue(value);
    } else {
      setCurrentValue('');
    }
  }, [value]);

  return (
    <BaseInput
      type="url"
      name={name}
      id={name}
      value={currentValue}
      onChange={handleChange}
      onBlur={handleBlur}
      {...otherProps}
    />
  );
};
