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

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

  const handleSelectImage = useCallback(() => {
    if (!actions) return;
    actions.imageLibraryOpen((image: any) => {
      if (!image || !image.url) return;
      onChange({ key: image.key, url: image.url });
      actions.imageLibraryClose();
    });
  }, [onChange, actions]);

  const hasImage = !!value?.url;

  return (
    <SilkeTextFieldOutline
      label={getTitle(schema)}
      flex
      disabled={disabled}
      tooltip={schema.description}
    >
      <SilkeBox
        tag="button"
        flex
        vAlign="center"
        gap="s"
        cursor={disabled ? undefined : 'pointer'}
        onClick={handleSelectImage}
        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();
            handleSelectImage();
          }
        }}
      >
        <SilkeBox width="m" height="m" rounded="tiny" bg="surface-1" align="center" overflow="hidden">
          {hasImage ? (
            <SilkeImage src={value.url} width="m" height="m" />
          ) : (
            <SilkeIcon icon="image" />
          )}
        </SilkeBox>
        <SilkeBox flex>
          <SilkeText size="small">{hasImage ? 'Change image' : 'Select image'}</SilkeText>
        </SilkeBox>
        <SilkeBox
          size="xs"
          align="center"
          onClick={hasImage ? handleDeleteImage : undefined}
        >
          <SilkeIcon icon={hasImage ? 'delete' : 'add'} />
        </SilkeBox>
      </SilkeBox>
    </SilkeTextFieldOutline>
  );
};

export default ImageField;
