import React, {useState} from 'react';
import {ScrollView} from 'react-native';
import {IconDownload} from '@tabler/icons-react-native';
import {CardContainer, ListRow, Spinner} from '@components';
import {Attachment} from '@interfaces/attachments';
import {
  selectSvgLogo,
  getFileNameExtension,
  shortenText,
  handleFileView,
} from '@shared/utils';
import {ICON_SIZES} from '@shared/theme';

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

interface Props {
  files?: Attachment[];
}

// TODO: Use FileCard component once refactored
function Documents({files}: Props) {
  const [fileLoading, setFileLoading] = useState<Nullable<string>>(null);

  const onFileView = (file: Attachment) => async () => {
    setFileLoading(file.url);
    try {
      await handleFileView(file);
    } finally {
      setFileLoading(null);
    }
  };

  return (
    !!files?.length && (
      <ScrollView
        horizontal
        showsHorizontalScrollIndicator={false}
        contentContainerStyle={styles.scrollContainer}>
        {files.map((file, index) => {
          const AvatarIcon = () =>
            selectSvgLogo(
              getFileNameExtension(file.name ?? '', true),
              ICON_SIZES.x6,
            );

          return (
            <CardContainer
              key={index}
              style={
                files.length === 1 ? styles.fullWidthCard : styles.shortenedCard
              }>
              <ListRow onPress={onFileView(file)}>
                <ListRow.Avatar Icon={AvatarIcon} />
                <ListRow.Title
                  description={`${file.size} • ${getFileNameExtension(
                    file.name ?? '',
                    true,
                  )}`}
                  title={shortenText(
                    file.name ?? '',
                    maxTextLimit(files.length === 1),
                  )}
                />
                {fileLoading === file.url ? (
                  <Spinner />
                ) : (
                  <ListRow.SideContent
                    onPressRightButton={onFileView(file)}
                    RightIconButton={IconDownload}
                  />
                )}
              </ListRow>
            </CardContainer>
          );
        })}
      </ScrollView>
    )
  );
}

export default Documents;
