import { SchemaFieldProps, LinkField as LinkFieldType } from '@vev/utils';
import React, { useState } from 'react';
import { SilkeAutocompleteField } from '../../silke-autocomplete-field';
import { SilkeBox } from '../../silke-box';
import { SilkeToggle } from '../../silke-toggle';
import { SilkeText, SilkeTextSmall } from '../../silke-text';

import { useSchemaContext } from '../silke-schema-context';

import { getTitle } from './utils/schema-util';

const SelectField = (props: SchemaFieldProps<LinkFieldType>) => {
  const { onChange, schema, value, disabled, readonly } = props;
  const { pages = [] } = useSchemaContext() || {};
  const [target, setTarget] = useState(value?.target);

  const items = pages
    .map((page) =>
      page.key && page.title
        ? {
            value: page.key || 'no-path',
            label: page.title || 'no-title',
          }
        : {},
    )
    .filter(Boolean);

  const handleAddPageLink = (val: string) => {
    onChange({
      mode: 0,
      page: val,
      target,
    });
  };

  const handleAddLink = (val: string) => {
    const PHONE_NUMBER = /^[0-9 +]*$/;
    const EMAIL = /([a-zA-Z0-9+._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)/;

    if (val.match(EMAIL)) {
      return onChange({
        mode: 3,
        email: val,
      });
    }

    if (val.match(PHONE_NUMBER)) {
      return onChange({
        mode: 4,
        phone: val,
      });
    }

    onChange({
      mode: 2,
      href: val,
      target,
    });
  };

  const getValue = (val: LinkFieldType['valueType']) => {
    if (!val) return '';
    switch (val.mode) {
      case 0:
        return val.page;
      case 2:
        return val.href;
      case 3:
        return val.email;
      case 4:
        return val.phone;
    }
  };

  return (
    <SilkeBox column gap="s" flex>
      <SilkeAutocompleteField
        help={'Search pages or add an external link'}
        label={getTitle(schema)}
        value={getValue(value)}
        name={schema.name}
        items={items}
        disabled={disabled}
        readOnly={readonly}
        onChange={(val: string) => handleAddPageLink(val)}
        onAdd={(val: string) => handleAddLink(val)}
        size="s"
        renderItem={(item) => {
          return (
            <SilkeText style={{ paddingLeft: '4px' }} size="small" title={item.item.label} overflow>
              {item.item.label}
            </SilkeText>
          );
        }}
      />
      <SilkeBox>
        <SilkeTextSmall flex>Open in new tab</SilkeTextSmall>
        <SilkeToggle
          small
          disabled={disabled}
          readOnly={readonly}
          value={target}
          onChange={(val) => {
            value && onChange({ ...value, target: val });
            setTarget(val);
          }}
        />
      </SilkeBox>
    </SilkeBox>
  );
};

export default SelectField;
