import { FC, useMemo } from 'react';

import CardContent from '@material-hu/mui/CardContent';
import Stack from '@material-hu/mui/Stack';
import { FileAsset } from '@material-hu/types/attachments';

import FileAssetListItem from 'src/pages/dashboard/serviceManagement/form/files/FileAssetListItem';
import { getFileType } from 'src/utils/files';
import { getFileNameExtension } from 'src/utils/files';

export type FileAssetListProps = {
  files: FileAsset[];
  handleRemove?: Function;
  loadingFiles?: File[];
};

const FileAssetList: FC<FileAssetListProps> = ({
  files,
  handleRemove,
  loadingFiles = [],
}) => {
  const filesList = useMemo(
    () =>
      files?.map(asset => ({
        ...asset,
        previewUrl: asset.url,
        previewType:
          getFileType(getFileNameExtension(asset.name || '')!) || asset.type,
      })),
    [files],
  );

  return (
    <CardContent sx={{ p: 0 }}>
      <Stack sx={{ gap: 1 }}>
        {filesList?.map((file, index) => (
          <FileAssetListItem
            key={file.url}
            file={file}
            index={index}
            handleRemove={handleRemove}
            allowDownload
          />
        ))}
        {loadingFiles.map((file, index) => (
          <FileAssetListItem
            key={file.name}
            file={{
              name: file.name,
              url: URL.createObjectURL(file),
              previewType: getFileType(getFileNameExtension(file.name || '')!),
            }}
            index={index}
            isLoading={true}
          />
        ))}
      </Stack>
    </CardContent>
  );
};

export default FileAssetList;
