import { useEffect, useState } from 'react';
import {
	Box,
	Button,
	Typography,
	Skeleton,
	Accordion,
	AccordionSummary,
	AccordionDetails,
	Table,
	TableBody,
	TableCell,
	TableContainer,
	TableHead,
	TableRow,
	Paper,
	IconButton,
	Pagination,
	TextField,
	InputAdornment,
} from '@mui/material';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';
import SearchIcon from '@mui/icons-material/Search';

const MultiPalletItems = ({
	products = [],
	pallets = [],
	onAddPallet,
	onEditPallet,
	onDeletePallet,
	isLoading = false
}) => {
	const [page, setPage] = useState(1);
	const [searchQuery, setSearchQuery] = useState('');
	const itemsPerPage = 10; // Show 10 products per page

	// Group pallets by product_id
	const getProductPallets = (productId) => {
		return pallets.filter(pallet => pallet.product_id == productId && pallet.is_multi_item_pallet == 1);
	};

	// Filter products based on search query
	const filteredProducts = products.filter(product => {
		const searchLower = searchQuery.toLowerCase();
		return (
			product.name?.toLowerCase().includes(searchLower) ||
			product.sku?.toLowerCase().includes(searchLower)
		);
	});

	// Calculate pagination
	const totalPages = Math.ceil(filteredProducts.length / itemsPerPage);
	const startIndex = (page - 1) * itemsPerPage;
	const endIndex = startIndex + itemsPerPage;
	const paginatedProducts = filteredProducts.slice(startIndex, endIndex);

	// Reset to page 1 when search changes
	useEffect(() => {
		setPage(1);
	}, [searchQuery]);

	return (
		<Box mt={3}>
			{/* Header with Title and Search */}
			<Box display='flex' justifyContent='space-between' alignItems='flex-start' mb={2}>
				<Box>
					<Typography variant='h6' fontWeight='bold' mb={1}>
						Items that ship as multiple pallets
					</Typography>
					<Typography variant='body2' color='textSecondary'>
						In order for an item to appear below, it must have the <strong>This item ships as multiple pallets</strong> setting enabled on its Product Settings.
					</Typography>
				</Box>

				{!isLoading && products && products.length > 0 && (
					<Box sx={{ minWidth: 350, ml: 2 }}>
						<TextField
							size='small'
							fullWidth
							placeholder='Search by product name or SKU...'
							value={searchQuery}
							onChange={(e) => setSearchQuery(e.target.value)}
							InputProps={{
								startAdornment: (
									<InputAdornment position='start'>
										<SearchIcon />
									</InputAdornment>
								),
							}}
						/>
						{filteredProducts.length > 0 && (
							<Typography variant='body2' color='textSecondary' sx={{ mt: 1, textAlign: 'right' }}>
								Showing {startIndex + 1}-{Math.min(endIndex, filteredProducts.length)} of {filteredProducts.length} products
							</Typography>
						)}
					</Box>
				)}
			</Box>

			{isLoading ? (
				<Skeleton variant='rectangular' animation='wave' height={200} />
			) : !products || products.length === 0 ? (
				<Box mt={2} p={3} sx={{ border: '1px solid #e0e0e0', borderRadius: 1, backgroundColor: '#f9f9f9' }}>
					<Typography variant='body2' color='textSecondary'>
						No products found with "This item ships as multiple pallets" enabled.
					</Typography>
				</Box>
			) : (
				<Box mt={2}>
					{/* Products List */}
					{filteredProducts.length === 0 ? (
						<Box p={3} sx={{ border: '1px solid #e0e0e0', borderRadius: 1, backgroundColor: '#f9f9f9' }}>
							<Typography variant='body2' color='textSecondary'>
								No products match your search.
							</Typography>
						</Box>
					) : (
						<>
							{paginatedProducts.map((product) => {
								const productPallets = getProductPallets(product.id);

								return (
									<Accordion key={product.id} sx={{ mb: 1 }}>
										<AccordionSummary
											expandIcon={<ExpandMoreIcon />}
											aria-controls={`panel-${product.id}-content`}
											id={`panel-${product.id}-header`}
										>
											<Box>
												<Typography variant='body1' fontWeight='bold'>
													SKU: {product.sku || 'N/A'}
												</Typography>
												<Typography variant='body2' color='textSecondary'>
													{product.name}
												</Typography>
											</Box>
										</AccordionSummary>
										<AccordionDetails>
											<Box>
												<Box display='flex' justifyContent='space-between' alignItems='center' mb={2}>
													<Typography variant='body2' color='textSecondary'>
														{productPallets.length} pallet{productPallets.length !== 1 ? 's' : ''} configured
													</Typography>
													<Button
														variant='contained'
														color='primary'
														size='small'
														onClick={() => onAddPallet(product)}
														sx={{ textTransform: 'capitalize' }}
													>
														Add Pallet
													</Button>
												</Box>

												{productPallets.length === 0 ? (
													<Box p={2} sx={{ backgroundColor: '#f9f9f9', borderRadius: 1 }}>
														<Typography variant='body2' color='textSecondary'>
															No pallets configured yet for this product.
														</Typography>
													</Box>
												) : (
													<TableContainer component={Paper}>
														<Table size='small'>
															<TableHead>
																<TableRow sx={{ backgroundColor: '#f5f5f5' }}>
																	<TableCell><strong>Quantity</strong></TableCell>
																	<TableCell><strong>Nickname</strong></TableCell>
																	<TableCell><strong>Freight Class</strong></TableCell>
																	<TableCell><strong>Length (in)</strong></TableCell>
																	<TableCell><strong>Width (in)</strong></TableCell>
																	<TableCell><strong>Height (in)</strong></TableCell>
																	<TableCell><strong>Weight (lbs)</strong></TableCell>
																	<TableCell align='center'><strong>Actions</strong></TableCell>
																</TableRow>
															</TableHead>
															<TableBody>
																{productPallets.map((pallet) => (
																	<TableRow key={pallet.id} hover>
																		<TableCell>{pallet.quantity || 1}</TableCell>
																		<TableCell>{pallet.nickname}</TableCell>
																		<TableCell>{pallet.freight_class || 'N/A'}</TableCell>
																		<TableCell>{pallet.pallet_length}</TableCell>
																		<TableCell>{pallet.pallet_width}</TableCell>
																		<TableCell>{pallet.max_height}</TableCell>
																		<TableCell>{pallet.weight || 'N/A'}</TableCell>
																		<TableCell align='center'>
																			<IconButton
																				size='small'
																				color='primary'
																				onClick={() => onEditPallet(pallet)}
																				title='Edit'
																			>
																				<EditIcon fontSize='small' />
																			</IconButton>
																			<IconButton
																				size='small'
																				color='error'
																				onClick={() => onDeletePallet(pallet)}
																				title='Delete'
																			>
																				<DeleteIcon fontSize='small' />
																			</IconButton>
																		</TableCell>
																	</TableRow>
																))}
															</TableBody>
														</Table>
													</TableContainer>
												)}
											</Box>
										</AccordionDetails>
									</Accordion>
								);
							})}

							{/* Pagination */}
							{totalPages > 1 && (
								<Box display='flex' justifyContent='center' mt={3}>
									<Pagination
										count={totalPages}
										page={page}
										onChange={(event, value) => setPage(value)}
										color='primary'
										showFirstButton
										showLastButton
									/>
								</Box>
							)}
						</>
					)}
				</Box>
			)}
		</Box>
	);
};

export default MultiPalletItems;
