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';
import { trimNumber } from '../utils/numbers';

const MultiPackageItems = ({
	products = [],
	boxes = [],
	onAddBox,
	onEditBox,
	onDeleteBox,
	isLoading = false
}) => {
	const [page, setPage] = useState(1);
	const [searchQuery, setSearchQuery] = useState('');
	const itemsPerPage = 10; // Show 10 products per page

	// Group boxes by product_id
	const getProductBoxes = (productId) => {
		return boxes.filter(box => box.product_id == productId && box.is_multi_item_box == 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 packages
					</Typography>
					<Typography variant='body2' color='textSecondary'>
						In order for an item to appear below, it must have the <strong>This item ships as multiple packages</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 packages" 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 productBoxes = getProductBoxes(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'>
										{productBoxes.length} box{productBoxes.length !== 1 ? 'es' : ''} configured
									</Typography>
									<Button
										variant='contained'
										color='primary'
										size='small'
										onClick={() => onAddBox(product)}
										sx={{ textTransform: 'capitalize' }}
									>
										Add Box
									</Button>
								</Box>

								{productBoxes.length > 0 ? (
									<TableContainer component={Paper} variant='outlined'>
										<Table size='small'>
											<TableHead>
												<TableRow>
													<TableCell>Quantity</TableCell>
													<TableCell>Nickname</TableCell>
													<TableCell>Length (in)</TableCell>
													<TableCell>Width (in)</TableCell>
													<TableCell>Height (in)</TableCell>
													<TableCell>Weight (LBS)</TableCell>
													<TableCell align='right'>Actions</TableCell>
												</TableRow>
											</TableHead>
											<TableBody>
												{productBoxes.map((box) => (
													<TableRow key={box.id}>
														<TableCell>{box.quantity || 1}</TableCell>
														<TableCell>{box.nickname}</TableCell>
														<TableCell>{trimNumber(box.interior_length)}</TableCell>
														<TableCell>{trimNumber(box.interior_width)}</TableCell>
														<TableCell>{trimNumber(box.interior_height)}</TableCell>
														<TableCell>{trimNumber(box.box_weight)}</TableCell>
														<TableCell align='right'>
															<IconButton
																size='small'
																onClick={() => onEditBox(box)}
																title='Edit'
															>
																<EditIcon fontSize='small' />
															</IconButton>
															<IconButton
																size='small'
																onClick={() => onDeleteBox(box)}
																title='Delete'
																color='error'
															>
																<DeleteIcon fontSize='small' />
															</IconButton>
														</TableCell>
													</TableRow>
												))}
											</TableBody>
										</Table>
									</TableContainer>
								) : (
									<Typography variant='body2' color='textSecondary' sx={{ fontStyle: 'italic' }}>
										No boxes configured for this product yet.
									</Typography>
								)}
							</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 MultiPackageItems;
