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

type BaseInputProps = React.ComponentProps<typeof BaseInput>;

export interface UrlInputProps
  extends Omit<BaseInputProps, 'onChange' | 'onBlur'> {
  value?: string;
  onChange?: (e: any) => void;
  onBlur?: (e: any) => void;
  onFormattedValueSet?: (
    value: string,
    e: React.FocusEvent<HTMLInputElement>
  ) => void;
  https?: boolean;
}

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

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

    if (onFormattedValueSet) {
      onFormattedValueSet(formattedValue, e);
    }
  };

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

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

    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}
    />
  );
};
