import * as React from 'react';
import { format } from 'date-fns';
import { Button, TableRow, TableCell } from '@mui/material';
import { CloudDownload, Description } from '@mui/icons-material';
import { downloadCSVfromS3 } from '../../utils/excel';
import { Loading } from '../../loading';

interface DownloadFileItemProps {
    filename: string;
    size: number;
    source: string;
    date: Date;
}
export const DownloadFileItem: React.FC<DownloadFileItemProps> = ({ filename, size, source, date }) => {
    const [progress, setProgress] = React.useState<number>(null);

    const downloadFile = async () => {
        await downloadCSVfromS3('unified-s3-pipeline', source, progress => setProgress(progress.loaded));
    };

    const formatBytes = (bytes: number) => {
        let units = ['B', 'KB', 'MB', 'GB'],
            i = 0,
            result = bytes;

        while (result >= 1024) {
            if (i < units.length - 1) {
                result /= 1024;
                i++;
            } else break;
        }

        return `${parseFloat(result.toFixed(2))} ${units[i]}`;
    };

    return (
        <TableRow>
            <TableCell
                style={{
                    textAlign: 'center',
                    width: '23px',
                    paddingRight: '0px',
                }}>
                <Description />
            </TableCell>
            <TableCell>{filename}</TableCell>
            <TableCell />
            <TableCell>{format(new Date(date), 'yyyy-MM-dd')}</TableCell>
            <TableCell>{formatBytes(size)}</TableCell>
            <TableCell align="center" style={{ width: '7rem' }}>
                {
                    progress && progress !== size
                        ? (
                            progress > 1 &&
                            <Loading
                                value={(progress * 100) / size}
                                style={{
                                    width: '31px',
                                    height: '31px',
                                }} />
                        )
                        : (
                            <Button onClick={downloadFile}>
                                <CloudDownload />
                            </Button>
                        )
                }
            </TableCell>
        </TableRow>
    );
};
