import React, { useCallback, useEffect } from 'react';
import { SilkeBox } from '../../silke-box';
import { SilkeButton } from '../../silke-button';
import { SilkeTextSmall } from '../../silke-text';
import { VideoField as VideoFieldType, SchemaFieldProps } from '@vev/utils';
import { useSchemaContext } from '../silke-schema-context';
import styles from './styles.scss';

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

const VideoField = ({
  value,
  schema,
  disabled,
  readonly,
  onChange,
}: SchemaFieldProps<VideoFieldType>) => {
  const { actions } = useSchemaContext();
  const handleDeleteVideo = useCallback(() => {
    onChange(null);
  }, [onChange]);

  const handleSelectVideo = useCallback(() => {
    if (!actions) return;
    actions.videoLibraryOpen((video: any) => {
      if (!video || !video.url) return;
      onChange(video);
      actions.videoLibraryClose();
    });
  }, [onChange, actions]);

  useEffect(() => {
    handleSelectVideo();
  }, []);

  return (
    <SilkeBox column flex vPad="s" gap="s">
      <SilkeTextSmall>{getTitle(schema)}</SilkeTextSmall>
      {schema.description && (
        <SilkeTextSmall color="neutral-80">{schema.description}</SilkeTextSmall>
      )}
      <SilkeBox column>
        <video
          loop
          muted
          autoPlay
          src={value?.url}
          style={{ background: '#444', borderRadius: '4px', overflow: 'hidden' }}
        />
        <SilkeBox flex align="center" className={styles.imageField__actions}>
          <SilkeButton
            disabled={disabled || readonly}
            icon="edit"
            kind="ghost"
            onClick={handleSelectVideo}
          />
          {value?.url && (
            <SilkeButton
              disabled={disabled || readonly}
              icon="delete"
              kind="ghost"
              onClick={handleDeleteVideo}
            />
          )}
        </SilkeBox>
      </SilkeBox>
    </SilkeBox>
  );
};

export default VideoField;
