import React from 'react';
import {ScrollView} from 'react-native';
import {IconTrash} from '@tabler/icons-react-native';
import {useNewPost, CardContainer, ListRow, Spinner} from '@components';
import {Attachment} from '@interfaces/attachments';
import {
  getFileNameExtension,
  shortenText,
  sizeToBytes,
  AvatarIcon,
} from '@shared/utils';
import {useTheme} from '@shared/theme';

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

function Documents() {
  const {files, setFiles, setCurrentSize, post} = useNewPost();
  const requestEdit = !!post?._links?.requestEdit;
  const {theme} = useTheme();
  const onDelete = (file: Attachment) => () =>
    setFiles(prevState => {
      const remainingFiles: Attachment[] = [];
      prevState.forEach(currentFile =>
        currentFile.url === file.url
          ? setCurrentSize(prevSize => prevSize - sizeToBytes(currentFile.size))
          : remainingFiles.push(currentFile),
      );
      return remainingFiles;
    });

  return (
    !!files.length && (
      <ScrollView horizontal contentContainerStyle={styles.scrollContainer}>
        {files.map((file, index) => {
          return (
            <CardContainer
              key={index}
              style={
                files.length === 1 ? styles.fullWidthCard : styles.shortenedCard
              }>
              <ListRow>
                {file.isLoading ? (
                  <Spinner />
                ) : (
                  <ListRow.Avatar
                    style={{backgroundColor: theme.background.layout.inverted}}
                    Icon={() => <AvatarIcon fileName={file.name ?? ''} />}
                  />
                )}
                <ListRow.Title
                  description={`${file.size} • ${getFileNameExtension(
                    file.name ?? '',
                    true,
                  )}`}
                  title={shortenText(
                    file.name ?? '',
                    maxTextLimit(files.length === 1),
                  )}
                />
                {!file.isLoading && !requestEdit && (
                  <ListRow.SideContent
                    onPressRightButton={onDelete(file)}
                    RightIconButton={IconTrash}
                  />
                )}
              </ListRow>
            </CardContainer>
          );
        })}
      </ScrollView>
    )
  );
}

export default Documents;
