import React, { useCallback } from 'react';
import { SilkeBox } from '../../silke-box';
import { SilkeIcon, SilkeIcons } from '../../silke-icon';
import { SilkeText } from '../../silke-text';
import { SilkeTextFieldOutline } from '../../silke-text-field/silke-text-field-outline';
import { EmojiType, IconField as IconFieldType, SchemaFieldProps } from '@vev/utils';
import { useSchemaContext } from '../silke-schema-context';
import { getTitle } from './utils/schema-util';

const IconField = ({
  value,
  schema,
  disabled,
  readonly,
  onChange,
}: SchemaFieldProps<IconFieldType>) => {
  const { actions } = useSchemaContext();
  const handleDeleteIcon = useCallback(
    (e: React.MouseEvent) => {
      e.stopPropagation();
      onChange(null);
    },
    [onChange],
  );

  const handleSelectIcon = useCallback(() => {
    if (!actions) return;
    actions.shapeLibraryOpen((shape: any) => {
      if (!shape || !shape.path) return;
      onChange({ key: shape.key, name: shape.name, path: shape.path });
      actions.shapeLibraryClose();
    });
  }, [onChange, actions]);

  const hasIcon = !!value?.path;

  return (
    <SilkeTextFieldOutline
      label={getTitle(schema)}
      flex
      disabled={disabled}
      tooltip={schema.description}
    >
      <SilkeBox
        tag="button"
        flex
        vAlign="center"
        gap="s"
        cursor={disabled ? undefined : 'pointer'}
        onClick={handleSelectIcon}
        data-input
        style={{ outline: 'none', background: 'none', border: 'none', textAlign: 'left', padding: 8 }}
        onKeyDown={(e: React.KeyboardEvent) => {
          if (e.key === 'Enter' || e.key === ' ') {
            e.preventDefault();
            handleSelectIcon();
          }
        }}
      >
        <SilkeBox width="m" height="m" rounded="tiny" bg="surface-1" align="center" overflow="hidden">
          {hasIcon ? (
            <SilkeIcon
              icon={
                {
                  type: EmojiType.icon,
                  value: value.path,
                } as SilkeIcons
              }
            />
          ) : (
            <SilkeIcon icon="shapes" />
          )}
        </SilkeBox>
        <SilkeBox flex>
          <SilkeText size="small">{hasIcon ? 'Change icon' : 'Select icon'}</SilkeText>
        </SilkeBox>
        <SilkeBox
          size="xs"
          align="center"
          onClick={hasIcon ? handleDeleteIcon : undefined}
        >
          <SilkeIcon icon={hasIcon ? 'delete' : 'add'} />
        </SilkeBox>
      </SilkeBox>
    </SilkeTextFieldOutline>
  );
};

export default IconField;
