import React from 'react';
import {View} from 'react-native';
import {useRoute} from '@react-navigation/native';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {Video, Image, BackButton} from '@components';
import {useGoBack} from '@hooks/useGoBack';
import {Attachment, AttachmentType} from '@interfaces/attachments';
import {windowDimensions} from '@shared/constants';
import {useTheme} from '@shared/theme';

import {styles} from './styles';

interface ViewAttachmentRouteParams {
  attachment: Attachment;
}

export function ViewAttachment() {
  const route = useRoute();
  const {goBack} = useGoBack();
  const {colors} = useTheme();
  const {top, bottom} = useSafeAreaInsets();

  const {attachment} = route.params as ViewAttachmentRouteParams;

  const isImage = attachment.type === AttachmentType.IMAGE;
  const isVideo = attachment.type === AttachmentType.VIDEO;

  if (!isImage && !isVideo) {
    return null;
  }

  const onClose = () => {
    goBack();
  };

  return (
    <View
      style={[
        styles.container,
        {
          backgroundColor: colors.black,
          paddingTop: top,
          paddingBottom: bottom,
        },
      ]}>
      <BackButton
        iconColor={colors.neutral}
        onPress={onClose}
        style={styles.header}
      />
      <View style={styles.container}>
        {isImage && (
          <Image
            contentFit="contain"
            source={{uri: attachment.path || attachment.url || ''}}
            style={styles.attachment}
          />
        )}
        {isVideo && (
          <Video
            style={styles.attachment}
            video={attachment}
            width={windowDimensions.width}
            withAutoPlay
            withSmallPlayButton={false}
            withCustomControls
            isVisible={true}
          />
        )}
      </View>
    </View>
  );
}
