import {
	Box,
	Link,
	Paper,
	Table,
	TableBody,
	TableCell,
	TableContainer,
	TableHead,
	TableRow,
	Typography,
} from '@mui/material';

const headings = [
	'Log ID',
	'Integration',
	'Request Time',
	'Response Time',
	'Latency',
	'Packaging Time',
	'Large Cart Rule',
	'Items',
	'DIMs (L x W x H)',
	'Qty',
	'Sender Address',
	'Receiver Address',
	'Response',
];

const styles = {
	cell: { whiteSpace: 'nowrap', verticalAlign: 'top' },
	itemsCell: { verticalAlign: 'top', minWidth: 160 },
	action: { cursor: 'pointer', fontWeight: 600 },
};

const EMPTY = '—';

const capitalize = value => (value ? value.charAt(0).toUpperCase() + value.slice(1) : '');

const orEmpty = value => (value === null || value === undefined || value === '' ? EMPTY : value);

/**
 * One line per logged item, or a dash when the transaction has no items on record
 * (quotes made while Enable Logs was off keep no items, dimensions or quantities).
 */
const itemLines = (items, field) =>
	items.length
		? items.map((item, itemIndex) => (
				<Typography key={itemIndex} variant='body2'>
					{orEmpty(item?.[field])}
				</Typography>
		  ))
		: EMPTY;

const LogsTable = ({ logs = [], onViewResponse, onViewPackaging }) => {
	if (!logs.length) {
		return (
			<Box sx={{ p: 6, textAlign: 'center' }}>
				<Typography variant='subtitle1' fontWeight='bold'>
					No logs found
				</Typography>
				<Typography variant='body2' color='textSecondary' mt={1}>
					Transactions appear here once a carrier with logs enabled has been quoted.
				</Typography>
			</Box>
		);
	}

	return (
		<TableContainer component={Paper} sx={{ mt: 1 }}>
			<Table size='small'>
				<TableHead>
					<TableRow sx={{ backgroundColor: '#f5f5f5' }}>
						{headings.map(heading => (
							<TableCell key={heading} sx={styles.cell}>
								<strong>{heading}</strong>
							</TableCell>
						))}
					</TableRow>
				</TableHead>
				<TableBody>
					{logs.map((log, index) => {
						const items = Array.isArray(log.items) ? log.items : [];
						const isError = (log.status || 'error').toLowerCase() === 'error';

						return (
							<TableRow key={log.id ?? index} hover>
								<TableCell sx={styles.cell}>{orEmpty(log.id)}</TableCell>
								<TableCell sx={styles.cell}>{orEmpty(log.carrier_name)}</TableCell>
								<TableCell sx={styles.cell}>{orEmpty(log.request_time)}</TableCell>
								<TableCell sx={styles.cell}>{orEmpty(log.response_time)}</TableCell>
								<TableCell sx={styles.cell}>{orEmpty(log.latency)}</TableCell>
								<TableCell sx={styles.cell}>{orEmpty(log.packaging_time)}</TableCell>
								<TableCell sx={styles.cell}>
									{log.large_cart_rule ? (
										<>
											Applied{' '}
											<Link
												href='https://support.eniture.com/understanding-the-large-cart-shipping-rule'
												target='_blank'
												rel='noopener noreferrer'
												underline='hover'>
												Learn More
											</Link>
										</>
									) : (
										EMPTY
									)}
								</TableCell>
								<TableCell sx={styles.itemsCell}>{itemLines(items, 'name')}</TableCell>
								<TableCell sx={styles.cell}>{itemLines(items, 'dimensions')}</TableCell>
								<TableCell sx={styles.cell}>{itemLines(items, 'quantity')}</TableCell>
								<TableCell sx={styles.cell}>{orEmpty(log.origin)}</TableCell>
								<TableCell sx={styles.cell}>{orEmpty(log.destination)}</TableCell>
								<TableCell sx={styles.cell}>
									<Link
										component='button'
										type='button'
										underline='hover'
										color={isError ? 'error' : 'primary'}
										sx={styles.action}
										onClick={() => onViewResponse(log)}>
										{capitalize(log.status || 'error')}
									</Link>
									{!!log.packaging && (
										<>
											<Box component='span' sx={{ mx: 0.5, color: 'text.disabled' }}>
												|
											</Box>
											<Link
												component='button'
												type='button'
												underline='hover'
												sx={styles.action}
												onClick={() => onViewPackaging(log)}>
												Packaging
											</Link>
										</>
									)}
								</TableCell>
							</TableRow>
						);
					})}
				</TableBody>
			</Table>
		</TableContainer>
	);
};

export default LogsTable;
