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

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

const AudioField = ({
  value,
  schema,
  disabled,
  readonly,
  onChange,
}: SchemaFieldProps<AudioFieldType>) => {
  const { actions } = useSchemaContext();
  const handleDeleteAudio = useCallback(() => {
    onChange(null);
  }, [onChange]);

  const handleSelectAudio = useCallback(() => {
    if (!actions) return;
    actions.audioLibraryOpen((audio) => {
      if (!audio || !audio.url) return;
      onChange(audio);
      actions.audioLibraryClose();
    });
  }, [onChange, actions]);

  useEffect(() => {
    if (!value) {
      handleSelectAudio();
    }
  }, []);

  return (
    <SilkeBox column flex vPad="s" gap="s">
      <SilkeTextSmall>{getTitle(schema)}</SilkeTextSmall>
      {schema.description && (
        <SilkeTextSmall color="neutral-80">{schema.description}</SilkeTextSmall>
      )}
      <SilkeBox column>
        <SilkeBox flex align="center" column>
          <SilkeBox pad="m" rounded="small" fill flex align column>
            <SilkeIcon
              color={value ? undefined : 'neutral-40'}
              style={{ fontSize: '2rem' }}
              icon="waveform"
            />
            <SilkeText>{value ? value.filename : 'No file selected'}</SilkeText>
          </SilkeBox>
          <SilkeBox>
            <SilkeButton
              disabled={disabled || readonly}
              icon="edit"
              kind="ghost"
              onClick={handleSelectAudio}
            />
            {value?.url && (
              <SilkeButton
                disabled={disabled || readonly}
                icon="delete"
                kind="ghost"
                onClick={handleDeleteAudio}
              />
            )}
          </SilkeBox>
        </SilkeBox>
      </SilkeBox>
    </SilkeBox>
  );
};

export default AudioField;
