import React from 'react';
import {AvatarProps} from '@components';
import {MediaEntity, MediaType} from '@modules/chats/interfaces';
import {AudioPlayer, MessageItem} from '@modules/chats/components';
import {Message} from '@modules/chats/interfaces/models/message';
import {useAudioTrackPlayer} from '@modules/chats/contexts/AudioPlayerContext';
import {useCurrentTrack} from '@modules/chats/store/zustand/useTrackStateStore';
import {useUser} from '@redux/selectors';

interface AudioProps {
  audio: MediaEntity;
}

function SendingVoiceMessage({audio}: AudioProps) {
  const durationInMs = audio.metadata?.durationInMs ?? 0;
  const duration = durationInMs * 0.001;
  const trackId = audio.id.toString();
  const url = audio.localUri;
  const {
    currentId,
    initializePlaylist,
    pause,
    seekTo,
    toggleRate,
    rate,
    state,
    play,
  } = useAudioTrackPlayer();
  const currentTrack = useCurrentTrack(trackId);
  const user = useUser();
  const progress = duration ? currentTrack.position / duration : 0;
  const isTrackActive = currentId === trackId;
  const isPlaying = isTrackActive && !!state?.isPlaying;
  const isLoading = state?.isLoading;
  const avatar: AvatarProps = {
    url: user.profilePicture,
    name: `${user.firstName} ${user.lastName}`,
  };

  const onPlay = () => {
    const track = {id: trackId, uri: url};
    initializePlaylist([track]);
    play(track);
  };

  return (
    <AudioPlayer
      isPlaying={isPlaying}
      isLoading={isLoading}
      avatar={avatar}
      duration={duration}
      progress={progress}
      onPlay={onPlay}
      onPause={pause}
      onSeek={seekTo}
      onToggleRate={toggleRate}
      rate={rate}>
      <MessageItem.Footer />
    </AudioPlayer>
  );
}

export function SendingMultimedia({item}: {item: Message}) {
  if (!item.pendingAssets?.length) {
    return null;
  }

  const attachment = item.pendingAssets.at(0);
  const isAudio = attachment?.type === MediaType.AUDIO;

  return isAudio ? <SendingVoiceMessage audio={attachment} /> : null;
}
