import React from 'react';
import Hook from '../../hook';
import { S3ProviderListOutput, S3ProviderListOutputItem } from '@aws-amplify/storage';
import {
	TableContainer,
	Table,
	TableHead,
	TableRow,
	TableCell,
	TableBody,
	Typography
} from '@mui/material';
import { en } from './(translation)/en';
import { es } from './(translation)/es';
import { Dialog } from '../../dialogs';
import { Loading } from '../../loading';
import { listFromS3 } from '../../utils/storage';
import { DownloadFileItem } from './download-item';

export interface ExcelDownloadData {
	folder: string;
	file: string;
	caption: string;
}

export interface ExcelDownloadOutput {

}

export const ExcelDownloadDialog = Hook.Dialog<ExcelDownloadData, ExcelDownloadOutput>(({ data, open, onClose }) => {
	const [located] = Hook.useLocalization({ en, es });
	const [loading, setLoading] = React.useState(false);
	const [s3FilesList, setS3FilesList] = React.useState<S3ProviderListOutput>(null);

	React.useEffect(() => {
		if (!s3FilesList) {
			const getFileData = async () => {
				setLoading(true);
				try {
					const s3Provider = await listFromS3('unified-s3-pipeline', data.folder, data.file);
					setS3FilesList(s3Provider);
				} finally {
					setLoading(false);
				}
			};

			getFileData();
		}
	}, []);

	const handleClose = (accept: boolean) => {
		onClose({ data: {}, rejected: !accept });
	};

	return (
		<Dialog
			className="download-file-dialog"
			open={!!open}
			caption={`${located.dialog.caption} ${data.caption}`}
			onClose={() => handleClose(false)}
		>
			<TableContainer style={{ width: '852px' }}>
				<Table stickyHeader>
					<TableHead>
						<TableRow className="download-file-table-head-row">
							<TableCell align="center" />
							<TableCell>{located.dialog.table.columns.fileName}</TableCell>
							<TableCell />
							<TableCell>{located.dialog.table.columns.date}</TableCell>
							<TableCell>{located.dialog.table.columns.size}</TableCell>
							<TableCell />
						</TableRow>
					</TableHead>
					<TableBody>
						{loading ? (
							<Loading />
						) : s3FilesList && s3FilesList.length > 1 ? (
							s3FilesList.map(
								(file: S3ProviderListOutputItem, index: number) =>
									index > 0 && (
										<DownloadFileItem
											key={file.eTag}
											filename={file.key.split(`${data.folder}/${data.file}/`)[1]}
											source={file.key}
											size={file.size}
											date={file.lastModified}
										/>
									),
							)
						) : (
							<Typography
								style={{
									position: 'absolute',
									textAlign: 'center',
									width: '852px',
									marginTop: '2.5rem !important',
								}}>

								{located.dialog.table.message.empty}
							</Typography>
						)}
					</TableBody>
				</Table>
			</TableContainer>
		</Dialog>
	);
});
