import React, { useRef, useState } from 'react';
import { FormField, Input, StatusType } from '@wix/design-system';
import { BaseInputProps, BaseInputRef } from '../BaseInput';
import { Field } from '../Field';
import { dataHooks } from '../dataHooks';
import { useTextInput } from '../useTextInput';
import { Link } from '@wix/wix-ui-icons-common';
import { useWixPatternsContainer } from '@wix/bex-core/react';

export interface UrlProps extends BaseInputProps<string> {}

export const Url = ({
  dataHook,
  schema,
  initialValue,
  onChange,
  inputRef,
}: UrlProps) => {
  const { value, charCount, handleChange } = useTextInput({
    initialValue,
    maxLength: schema.maxLength,
    onChange,
  });
  const ref = useRef<BaseInputRef>({});
  const [fieldsStatus, setFieldStatus] = useState<{
    status?: StatusType;
    statusMessage?: string;
  }>({});
  const { translate: t } = useWixPatternsContainer();
  // Same regex as data-extensions https://github.com/wix-private/server-infra/blob/a6c3009d39bbb0312c929f68ee81c559e1eb5b4e/iptf/dataextensions/src/main/scala/com/wixpress/infra/dataextensions/runtime/validator/Formats.scala#L31
  const uriPattern =
    /^[A-Za-z][A-Za-z0-9+.-]*:(\/\/([A-Za-z0-9._~\-%!$&'()*+,;=:]*@)?[A-Za-z0-9._~\-!$&'()*+,;=%:\[\]]*(:[0-9]*)?)?[A-Za-z0-9._~\-%!$&'()*+,;=:@\/]*([?][A-Za-z0-9._~\-%!$&'()*+,;=:@\/?]*)?([#][A-Za-z0-9._~\-%!$&'()*+,;=:@\/?]*)?$/;

  return (
    <Field dataHook={dataHook} type={schema.type}>
      <FormField
        dataHook={dataHooks.Label}
        label={schema.label}
        charCount={charCount}
        {...fieldsStatus}
      >
        <Input
          prefix={
            <Input.IconAffix>
              <Link />
            </Input.IconAffix>
          }
          placeholder={t('cairo.customFields.url-input.placeholder')}
          dataHook={dataHooks.Input}
          value={value}
          onChange={handleChange}
          onBlur={() => {
            ref.current.invalid = value ? !uriPattern.test(value) : false;

            if (ref.current.invalid) {
              setFieldStatus({
                status: 'error',
                statusMessage: t('cairo.customFields.url-input.error'),
              });
            } else {
              setFieldStatus({ status: undefined, statusMessage: undefined });
            }
          }}
          ref={(internalRef) => {
            inputRef?.(ref.current);
            ref.current.focus = () => internalRef?.focus();
          }}
        />
      </FormField>
    </Field>
  );
};
