import { useState, useEffect } from 'react';
import {
	Box,
	Button,
	Checkbox,
	Dialog,
	DialogActions,
	DialogContent,
	DialogTitle,
	FormControl,
	FormControlLabel,
	FormHelperText,
	Grid,
	MenuItem,
	OutlinedInput,
	Select,
} from '@mui/material';
import { Spinner } from './index';

const FREIGHT_CLASSES = [
	{ value: '', label: 'No Freight Class' },
	{ value: '50', label: '50' },
	{ value: '55', label: '55' },
	{ value: '60', label: '60' },
	{ value: '65', label: '65' },
	{ value: '70', label: '70' },
	{ value: '77.5', label: '77.5' },
	{ value: '85', label: '85' },
	{ value: '92.5', label: '92.5' },
	{ value: '100', label: '100' },
	{ value: '110', label: '110' },
	{ value: '125', label: '125' },
	{ value: '150', label: '150' },
	{ value: '175', label: '175' },
	{ value: '200', label: '200' },
	{ value: '250', label: '250' },
	{ value: '300', label: '300' },
	{ value: '400', label: '400' },
	{ value: '500', label: '500' },
	{ value: 'density_based', label: 'Density Based' },
];

const PalletModal = ({ open, onClose, onSave, palletData, isSaving, isMultiPalletItem = false, selectedProduct = null }) => {
	const [formData, setFormData] = useState({
		nickname: '',
		pallet_length: '',
		pallet_width: '',
		max_height: '',
		pallet_height: '',
		max_weight: '',
		pallet_weight: '',
		pallet_fee: '',
		weight: '',
		is_available: true,
		is_multi_item_pallet: false,
		product_id: null,
		quantity: 1,
		freight_class: '',
	});

	const [errors, setErrors] = useState({});

	useEffect(() => {
		if (open) {
			if (palletData) {
				// Editing existing pallet
				setFormData({
					id: palletData.id,
					nickname: palletData.nickname || '',
					pallet_length: palletData.pallet_length || '',
					pallet_width: palletData.pallet_width || '',
					max_height: palletData.max_height || '',
					pallet_height: palletData.pallet_height || '',
					max_weight: palletData.max_weight || '',
					pallet_weight: palletData.pallet_weight || '',
					pallet_fee: palletData.pallet_fee || '',
					weight: palletData.weight || '',
					is_available: palletData.is_available == 1,
					is_multi_item_pallet: palletData.is_multi_item_pallet == 1,
					product_id: palletData.product_id || null,
					quantity: palletData.quantity || 1,
					freight_class: palletData.freight_class || '',
				});
			} else {
				// Adding new pallet
				setFormData({
					nickname: '',
					pallet_length: '',
					pallet_width: '',
					max_height: '',
					pallet_height: '',
					max_weight: '',
					pallet_weight: '',
					pallet_fee: '',
					weight: '',
					is_available: true,
					is_multi_item_pallet: isMultiPalletItem,
					product_id: selectedProduct?.id || null,
					quantity: 1,
					freight_class: '',
				});
			}
			setErrors({});
		}
	}, [open, palletData, isMultiPalletItem, selectedProduct]);

	const handleChange = (field, value) => {
		setFormData(prev => ({
			...prev,
			[field]: value,
		}));

		// Clear error for this field
		if (errors[field]) {
			setErrors(prev => ({
				...prev,
				[field]: '',
			}));
		}
	};

	const validateForm = () => {
		const newErrors = {};

		// Nickname validation - varchar(50) in DB
		if (!formData.nickname?.trim()) {
			newErrors.nickname = 'Nickname is required';
		} else if (formData.nickname.length > 50) {
			newErrors.nickname = 'Nickname must be 50 characters or less';
		}

		// Length validation - Maximum 3 digits before decimal and 3 after (e.g., 123.456)
		if (!formData.pallet_length || formData.pallet_length === '') {
			newErrors.pallet_length = 'Length is required';
		} else {
			const length = parseFloat(formData.pallet_length);
			if (isNaN(length)) {
				newErrors.pallet_length = 'Length must be a valid number';
			} else if (length <= 0) {
				newErrors.pallet_length = 'Length must be greater than 0';
			} else if (length > 999.999) {
				newErrors.pallet_length = 'Length cannot exceed 999.999';
			} else {
				const decimalPart = formData.pallet_length.toString().split('.')[1];
				if (decimalPart && decimalPart.length > 3) {
					newErrors.pallet_length = 'Length can have maximum 3 decimal places';
				}
			}
		}

		// Width validation - Maximum 3 digits before decimal and 3 after (e.g., 123.456)
		if (!formData.pallet_width || formData.pallet_width === '') {
			newErrors.pallet_width = 'Width is required';
		} else {
			const width = parseFloat(formData.pallet_width);
			if (isNaN(width)) {
				newErrors.pallet_width = 'Width must be a valid number';
			} else if (width <= 0) {
				newErrors.pallet_width = 'Width must be greater than 0';
			} else if (width > 999.999) {
				newErrors.pallet_width = 'Width cannot exceed 999.999';
			} else {
				const decimalPart = formData.pallet_width.toString().split('.')[1];
				if (decimalPart && decimalPart.length > 3) {
					newErrors.pallet_width = 'Width can have maximum 3 decimal places';
				}
			}
		}

		if (isMultiPalletItem) {
			// Multi-pallet item validation

			// Quantity - Maximum 999
			if (!formData.quantity || formData.quantity === '') {
				newErrors.quantity = 'Quantity is required';
			} else {
				const quantity = parseInt(formData.quantity);
				if (isNaN(quantity)) {
					newErrors.quantity = 'Quantity must be a valid number';
				} else if (quantity <= 0) {
					newErrors.quantity = 'Quantity must be greater than 0';
				} else if (quantity > 999) {
					newErrors.quantity = 'Quantity cannot exceed 999';
				} else if (!Number.isInteger(parseFloat(formData.quantity))) {
					newErrors.quantity = 'Quantity must be a whole number';
				}
			}

			// Height validation - Maximum 3 digits before decimal and 3 after (e.g., 123.456)
			if (!formData.max_height || formData.max_height === '') {
				newErrors.max_height = 'Height is required';
			} else {
				const height = parseFloat(formData.max_height);
				if (isNaN(height)) {
					newErrors.max_height = 'Height must be a valid number';
				} else if (height <= 0) {
					newErrors.max_height = 'Height must be greater than 0';
				} else if (height > 999.999) {
					newErrors.max_height = 'Height cannot exceed 999.999';
				} else {
					const decimalPart = formData.max_height.toString().split('.')[1];
					if (decimalPart && decimalPart.length > 3) {
						newErrors.max_height = 'Height can have maximum 3 decimal places';
					}
				}
			}

			// Weight validation - Maximum 5 digits before decimal and 3 after (e.g., 12345.678)
			if (!formData.weight || formData.weight === '') {
				newErrors.weight = 'Weight is required';
			} else {
				const weight = parseFloat(formData.weight);
				if (isNaN(weight)) {
					newErrors.weight = 'Weight must be a valid number';
				} else if (weight <= 0) {
					newErrors.weight = 'Weight must be greater than 0';
				} else if (weight > 99999.999) {
					newErrors.weight = 'Weight cannot exceed 99999.999';
				} else {
					const decimalPart = formData.weight.toString().split('.')[1];
					if (decimalPart && decimalPart.length > 3) {
						newErrors.weight = 'Weight can have maximum 3 decimal places';
					}
				}
			}

			// Freight class validation - varchar(20)
			if (formData.freight_class && formData.freight_class.length > 20) {
				newErrors.freight_class = 'Freight class must be 20 characters or less';
			}
		} else {
			// Standard pallet validation

			// Max Height - Maximum 3 digits before decimal and 3 after (e.g., 123.456)
			if (!formData.max_height || formData.max_height === '') {
				newErrors.max_height = 'Max height is required';
			} else {
				const maxHeight = parseFloat(formData.max_height);
				if (isNaN(maxHeight)) {
					newErrors.max_height = 'Max height must be a valid number';
				} else if (maxHeight <= 0) {
					newErrors.max_height = 'Max height must be greater than 0';
				} else if (maxHeight > 999.999) {
					newErrors.max_height = 'Max height cannot exceed 999.999';
				} else {
					const decimalPart = formData.max_height.toString().split('.')[1];
					if (decimalPart && decimalPart.length > 3) {
						newErrors.max_height = 'Max height can have maximum 3 decimal places';
					}
				}
			}

			// Pallet Height - Maximum 3 digits before decimal and 3 after (e.g., 123.456)
			if (!formData.pallet_height || formData.pallet_height === '') {
				newErrors.pallet_height = 'Pallet height is required';
			} else {
				const palletHeight = parseFloat(formData.pallet_height);
				if (isNaN(palletHeight)) {
					newErrors.pallet_height = 'Pallet height must be a valid number';
				} else if (palletHeight <= 0) {
					newErrors.pallet_height = 'Pallet height must be greater than 0';
				} else if (palletHeight > 999.999) {
					newErrors.pallet_height = 'Pallet height cannot exceed 999.999';
				} else {
					const decimalPart = formData.pallet_height.toString().split('.')[1];
					if (decimalPart && decimalPart.length > 3) {
						newErrors.pallet_height = 'Pallet height can have maximum 3 decimal places';
					}
				}

				// Cross-field validation
				if (!isNaN(palletHeight) && !isNaN(parseFloat(formData.max_height)) && palletHeight >= parseFloat(formData.max_height)) {
					newErrors.pallet_height = 'Pallet height must be less than max height';
				}
			}

			// Max Weight - Maximum 5 digits before decimal and 3 after (e.g., 12345.678)
			if (!formData.max_weight || formData.max_weight === '') {
				newErrors.max_weight = 'Max weight is required';
			} else {
				const maxWeight = parseFloat(formData.max_weight);
				if (isNaN(maxWeight)) {
					newErrors.max_weight = 'Max weight must be a valid number';
				} else if (maxWeight <= 0) {
					newErrors.max_weight = 'Max weight must be greater than 0';
				} else if (maxWeight > 99999.999) {
					newErrors.max_weight = 'Max weight cannot exceed 99999.999';
				} else {
					const decimalPart = formData.max_weight.toString().split('.')[1];
					if (decimalPart && decimalPart.length > 3) {
						newErrors.max_weight = 'Max weight can have maximum 3 decimal places';
					}
				}
			}

			// Pallet Weight - Maximum 5 digits before decimal and 3 after (e.g., 12345.678)
			if (!formData.pallet_weight || formData.pallet_weight === '') {
				newErrors.pallet_weight = 'Pallet weight is required';
			} else {
				const palletWeight = parseFloat(formData.pallet_weight);
				if (isNaN(palletWeight)) {
					newErrors.pallet_weight = 'Pallet weight must be a valid number';
				} else if (palletWeight <= 0) {
					newErrors.pallet_weight = 'Pallet weight must be greater than 0';
				} else if (palletWeight > 99999.999) {
					newErrors.pallet_weight = 'Pallet weight cannot exceed 99999.999';
				} else {
					const decimalPart = formData.pallet_weight.toString().split('.')[1];
					if (decimalPart && decimalPart.length > 3) {
						newErrors.pallet_weight = 'Pallet weight can have maximum 3 decimal places';
					}
				}

				// Cross-field validation
				if (!isNaN(palletWeight) && !isNaN(parseFloat(formData.max_weight)) && palletWeight >= parseFloat(formData.max_weight)) {
					newErrors.pallet_weight = 'Pallet weight must be less than max weight';
				}
			}

			// Pallet Fee - Must be between 0 and 999.99
			if (formData.pallet_fee && formData.pallet_fee !== '') {
				const palletFee = parseFloat(formData.pallet_fee);
				if (isNaN(palletFee)) {
					newErrors.pallet_fee = 'Pallet fee must be a valid number';
				} else if (palletFee < 0) {
					newErrors.pallet_fee = 'Pallet fee cannot be negative';
				} else if (palletFee > 999.99) {
					newErrors.pallet_fee = 'Pallet fee must be between 0 and 999.99';
				} else {
					const decimalPart = formData.pallet_fee.toString().split('.')[1];
					if (decimalPart && decimalPart.length > 2) {
						newErrors.pallet_fee = 'Pallet fee can have maximum 2 decimal places';
					}
				}
			}
		}

		setErrors(newErrors);
		return Object.keys(newErrors).length === 0;
	};

	const handleSubmit = () => {
		if (!validateForm()) {
			return;
		}

		onSave(formData);
	};

	const calculateMaxHeightWithPallet = () => {
		const max = parseFloat(formData.max_height) || 0;
		const pallet = parseFloat(formData.pallet_height) || 0;
		return max - pallet;
	};

	const calculateMaxWeightWithPallet = () => {
		const max = parseFloat(formData.max_weight) || 0;
		const pallet = parseFloat(formData.pallet_weight) || 0;
		return max - pallet;
	};

	return (
		<Dialog open={open} onClose={onClose} maxWidth='md' fullWidth>
			<DialogTitle>
				{isMultiPalletItem
					? 'Handling Unit Properties'
					: 'Pallet Properties'}
			</DialogTitle>
			<DialogContent>
				<Box sx={{ mt: 2 }}>
					{/* Quantity (multi-pallet only) */}
					{isMultiPalletItem && (
						<FormControl fullWidth sx={{ mb: 2 }}>
							<FormHelperText>
								Quantity
								<span style={{ color: 'red', fontSize: '14px', display: 'inline-block', marginLeft: '5px' }}>
									*
								</span>
							</FormHelperText>
							<OutlinedInput
								fullWidth
								size='small'
								type='number'
								value={formData.quantity}
								onChange={e => handleChange('quantity', e.target.value)}
								error={!!errors.quantity}
								inputProps={{ min: 1, max: 999, step: 1 }}
							/>
							{errors.quantity && (
								<FormHelperText sx={{ color: 'red' }}>{errors.quantity}</FormHelperText>
							)}
						</FormControl>
					)}

					{isMultiPalletItem && (
						<Grid container sx={{ mb: 2 }}>
						<Grid item xs={12}>
							<FormControl fullWidth>
								<FormHelperText>
									Nickname
									<span style={{ color: 'red', fontSize: '14px', display: 'inline-block', marginLeft: '5px' }}>
										*
									</span>
								</FormHelperText>
								<OutlinedInput
									fullWidth
									size='small'
									inputProps={{ maxLength: 50 }}
									value={formData.nickname}
									onChange={e => handleChange('nickname', e.target.value)}
									error={!!errors.nickname}
								/>
								{errors.nickname && (
									<FormHelperText sx={{ color: 'red' }}>{errors.nickname}</FormHelperText>
								)}
							</FormControl>
						</Grid>
						</Grid>
					)}

					{/* Freight Class (multi-pallet only) */}
					{isMultiPalletItem && (
						<FormControl fullWidth sx={{ mb: 2 }}>
							<FormHelperText>Freight Class</FormHelperText>
							<Select
								fullWidth
								size='small'
								displayEmpty
								value={formData.freight_class}
								onChange={e => handleChange('freight_class', e.target.value)}>
								{FREIGHT_CLASSES.map(option => (
									<MenuItem key={option.value} value={option.value}>
										{option.label}
									</MenuItem>
								))}
							</Select>
						</FormControl>
					)}

					{/* Pallet Dimensions */}
					<Grid container spacing={2} sx={{ mb: 2 }}>
						{/* Standard pallet nickname; handling-unit nickname appears above. */}
						{!isMultiPalletItem && (
						<Grid item xs={6}>
							<FormControl fullWidth>
								<FormHelperText>
									Nickname
									<span style={{ color: 'red', fontSize: '14px', display: 'inline-block', marginLeft: '5px' }}>
										*
									</span>
								</FormHelperText>
								<OutlinedInput
									fullWidth
									size='small'
									placeholder='e.g., Standard 48x40'
									value={formData.nickname}
									onChange={e => handleChange('nickname', e.target.value)}
									error={!!errors.nickname}
								/>
								{errors.nickname && (
									<FormHelperText sx={{ color: 'red' }}>{errors.nickname}</FormHelperText>
								)}
							</FormControl>
						</Grid>
						)}
						<Grid item xs={6}>
							<FormControl fullWidth>
								<FormHelperText>
									Length (in)
									<span style={{ color: 'red', fontSize: '14px', display: 'inline-block', marginLeft: '5px' }}>
										*
									</span>
								</FormHelperText>
								<OutlinedInput
									fullWidth
									size='small'
									type='number'
									value={formData.pallet_length}
									onChange={e => handleChange('pallet_length', e.target.value)}
									error={!!errors.pallet_length}
									inputProps={{ step: '0.001', min: '0', max: '999.999' }}
								/>
								{errors.pallet_length && (
									<FormHelperText sx={{ color: 'red' }}>{errors.pallet_length}</FormHelperText>
								)}
							</FormControl>
						</Grid>

						<Grid item xs={6}>
							<FormControl fullWidth>
								<FormHelperText>
									Width (in)
									<span style={{ color: 'red', fontSize: '14px', display: 'inline-block', marginLeft: '5px' }}>
										*
									</span>
								</FormHelperText>
								<OutlinedInput
									fullWidth
									size='small'
									type='number'
									value={formData.pallet_width}
									onChange={e => handleChange('pallet_width', e.target.value)}
									error={!!errors.pallet_width}
									inputProps={{ step: '0.001', min: '0', max: '999.999' }}
								/>
								{errors.pallet_width && (
									<FormHelperText sx={{ color: 'red' }}>{errors.pallet_width}</FormHelperText>
								)}
							</FormControl>
						</Grid>

						<Grid item xs={6}>
							<FormControl fullWidth>
								<FormHelperText>
									{isMultiPalletItem ? 'Height (in)' : 'Max Height (in)'}
									<span style={{ color: 'red', fontSize: '14px', display: 'inline-block', marginLeft: '5px' }}>
										*
									</span>
								</FormHelperText>
								<OutlinedInput
									fullWidth
									size='small'
									type='number'
									value={formData.max_height}
									onChange={e => handleChange('max_height', e.target.value)}
									error={!!errors.max_height}
									inputProps={{ step: '0.001', min: '0', max: '999.999' }}
								/>
								{errors.max_height && (
									<FormHelperText sx={{ color: 'red' }}>{errors.max_height}</FormHelperText>
								)}
							</FormControl>
						</Grid>

						{/* Multi-pallet item: Show Weight instead of pallet-specific fields */}
						{isMultiPalletItem ? (
							<Grid item xs={6}>
								<FormControl fullWidth>
									<FormHelperText>
										Weight (LBS)
										<span style={{ color: 'red', fontSize: '14px', display: 'inline-block', marginLeft: '5px' }}>
											*
										</span>
									</FormHelperText>
									<OutlinedInput
										fullWidth
										size='small'
										type='number'
										value={formData.weight}
										onChange={e => handleChange('weight', e.target.value)}
										error={!!errors.weight}
										inputProps={{ step: '0.001', min: '0', max: '99999.999' }}
									/>
									{errors.weight && (
										<FormHelperText sx={{ color: 'red' }}>{errors.weight}</FormHelperText>
									)}
								</FormControl>
							</Grid>
						) : (
							<>
								{/* Standard pallet fields */}
								<Grid item xs={6}>
									<FormControl fullWidth>
										<FormHelperText>
											Pallet Height (in)
											<span style={{ color: 'red', fontSize: '14px', display: 'inline-block', marginLeft: '5px' }}>
												*
											</span>
										</FormHelperText>
										<OutlinedInput
											fullWidth
											size='small'
											type='number'
											value={formData.pallet_height}
											onChange={e => handleChange('pallet_height', e.target.value)}
											error={!!errors.pallet_height}
											inputProps={{ step: '0.001', min: '0', max: '999.999' }}
										/>
										{errors.pallet_height && (
											<FormHelperText sx={{ color: 'red' }}>{errors.pallet_height}</FormHelperText>
										)}
									</FormControl>
								</Grid>

								<Grid item xs={6}>
									<FormControl fullWidth>
										<FormHelperText>
											Max Weight (LBS)
											<span style={{ color: 'red', fontSize: '14px', display: 'inline-block', marginLeft: '5px' }}>
												*
											</span>
										</FormHelperText>
										<OutlinedInput
											fullWidth
											size='small'
											type='number'
											value={formData.max_weight}
											onChange={e => handleChange('max_weight', e.target.value)}
											error={!!errors.max_weight}
											inputProps={{ step: '0.001', min: '0', max: '99999.999' }}
										/>
										{errors.max_weight && (
											<FormHelperText sx={{ color: 'red' }}>{errors.max_weight}</FormHelperText>
										)}
									</FormControl>
								</Grid>

								<Grid item xs={6}>
									<FormControl fullWidth>
										<FormHelperText>
											Pallet Weight (LBS)
											<span style={{ color: 'red', fontSize: '14px', display: 'inline-block', marginLeft: '5px' }}>
												*
											</span>
										</FormHelperText>
										<OutlinedInput
											fullWidth
											size='small'
											type='number'
											value={formData.pallet_weight}
											onChange={e => handleChange('pallet_weight', e.target.value)}
											error={!!errors.pallet_weight}
											inputProps={{ step: '0.001', min: '0', max: '99999.999' }}
										/>
										{errors.pallet_weight && (
											<FormHelperText sx={{ color: 'red' }}>{errors.pallet_weight}</FormHelperText>
										)}
									</FormControl>
								</Grid>

								<Grid item xs={6}>
									<FormControl fullWidth>
										<FormHelperText>Pallet Fee (e.g 1.75)</FormHelperText>
										<OutlinedInput
											fullWidth
											size='small'
											type='number'
											value={formData.pallet_fee}
											onChange={e => handleChange('pallet_fee', e.target.value)}
											error={!!errors.pallet_fee}
											inputProps={{ step: '0.01', min: '0', max: '999.99' }}
										/>
										{errors.pallet_fee && (
											<FormHelperText sx={{ color: 'red' }}>{errors.pallet_fee}</FormHelperText>
										)}
									</FormControl>
								</Grid>

								{/* Calculated Fields - only for standard pallets */}
								<Grid item xs={6}>
									<FormControl fullWidth>
										<FormHelperText>Max Height w/ Pallet (in)</FormHelperText>
										<OutlinedInput
											fullWidth
											size='small'
											value={calculateMaxHeightWithPallet().toFixed(2)}
											disabled
										/>
									</FormControl>
								</Grid>

								<Grid item xs={6}>
									<FormControl fullWidth>
										<FormHelperText>Max Weight w/ Pallet (LBS)</FormHelperText>
										<OutlinedInput
											fullWidth
											size='small'
											value={calculateMaxWeightWithPallet().toFixed(2)}
											disabled
										/>
									</FormControl>
								</Grid>
							</>
						)}
					</Grid>

					{/* Is Available Checkbox - hide for multi-pallet items */}
					{!isMultiPalletItem && (
						<FormControlLabel
							control={
								<Checkbox
									checked={formData.is_available}
									onChange={e => handleChange('is_available', e.target.checked)}
								/>
							}
							label='Available'
							sx={{ mt: 2 }}
						/>
					)}
				</Box>
			</DialogContent>
			<DialogActions>
				<Button onClick={onClose} disabled={isSaving}>
					Cancel
				</Button>
				<Button onClick={handleSubmit} variant='contained' disabled={isSaving}>
					{isSaving ? <Spinner size={20} /> : 'Save'}
				</Button>
			</DialogActions>
		</Dialog>
	);
};

export default PalletModal;
