import React, {useMemo} from 'react';
import {Pressable, View, StyleProp, ViewStyle} from 'react-native';
import {useTranslation} from 'react-i18next';
import {Typography} from '@components/_core/Typography';
import {Avatar} from '@components/_HuGo/Avatar';
import {AttachmentType} from '@interfaces/attachments';
import {
  getFileNameExtension,
  getFileNameFromUrl,
  getShortenFileName,
} from '@shared/utils';
import {useTheme} from '@shared/theme';
import {commonStyles} from '@shared/styles';

import {styles} from './styles';
import {getIconByTypeOrExtension} from './constants';

interface Props {
  onPress?: () => void;
  name?: string;
  source?: string;
  size: Nullable<string>; // in bytes
  type?: AttachmentType;
  url?: string;
  showExtension?: boolean;
  style?: StyleProp<ViewStyle>;
  actionI18nKey?: string; // By default will be preview
}

export function Attachment({
  onPress,
  name,
  source,
  size,
  type,
  url,
  style,
  showExtension = false,
  actionI18nKey = 'general.preview',
}: Props) {
  const {t} = useTranslation();
  const {theme} = useTheme();

  const {fileName, extension} = useMemo(() => {
    const fullFileName = name || getFileNameFromUrl(source || url);
    return {
      fileName: getShortenFileName({fileName: fullFileName, showExtension}),
      extension: getFileNameExtension(fullFileName),
    };
  }, [name, source, url, showExtension]);

  const Icon = getIconByTypeOrExtension(type, extension);

  return (
    <Pressable
      onPress={onPress}
      style={[
        styles.container,
        {
          backgroundColor: theme.background.elements.default,
          borderColor: theme.border.neutral.default,
        },
        style,
      ]}>
      <Avatar
        style={{backgroundColor: theme.action.background.brand.hover}}
        Icon={Icon}
        iconColor={theme.text.neutral.brand}
      />
      <View style={commonStyles.flex}>
        <Typography variant="s" numberOfLines={1}>
          {fileName}
        </Typography>
        <View style={styles.subtitleContainer}>
          {size && (
            <Typography variant="xs" color={theme.text.neutral.lighter}>
              {`${size} • `}
            </Typography>
          )}
          <Typography variant="xs" color={theme.brand[500]}>
            {t(actionI18nKey)}
          </Typography>
        </View>
      </View>
    </Pressable>
  );
}
