import { useState, useEffect, useMemo } from 'react';
import { debounce } from '@mui/material/utils';
import {
	Box,
	Button,
	Checkbox,
	Dialog,
	DialogActions,
	DialogContent,
	DialogTitle,
	FormControl,
	FormControlLabel,
	FormHelperText,
	Grid,
	MenuItem,
	OutlinedInput,
	Radio,
	RadioGroup,
	Select,
	TextField,
	Typography,
	Chip,
	Autocomplete,
} from '@mui/material';
import { Spinner } from './index';
import {
	useGetProductSkusQuery,
	useGetProductCategoriesQuery,
	useGetProductTagsQuery,
	useGetProductBrandsQuery,
} from '../redux/Actions/WooCommerceDataAction';
import {
	MERCHANT_DEFINED_BOX,
	fedexOneRateBoxLabel,
	findFedexOneRateBox,
} from '../constants/fedexOneRateBoxes';
import { trimNumber } from '../utils/numbers';

const BoxSizeModal = ({
	open,
	onClose,
	onSave,
	boxData,
	isSaving,
	isMultiPackageBox = false,
	selectedProduct = null,
	fedexOneRateBoxes = [],
	showFedexOneRateBoxes = false,
}) => {
	const [formData, setFormData] = useState({
		nickname: '',
		box_type: 1, // Default to Merchant defined box (constant ID)
		box_code: null,
		interior_length: '',
		interior_width: '',
		interior_height: '',
		exterior_length: '',
		exterior_width: '',
		exterior_height: '',
		max_weight: '',
		box_weight: '',
		box_fee: '',
		box_availability: 'universally_available',
		availability_type: 'product_sku',
		availability_values: [],
		is_available: true,
		is_multi_item_box: false,
		product_id: null,
		quantity: 1,
	});

	const [inputValue, setInputValue] = useState('');
	const [searchTerm, setSearchTerm] = useState('');
	const [errors, setErrors] = useState({});

	// Get REST API URL
	const url = window.eniture_rtsq?.rest_url || '/wp-json/eniture-real-time-shipping-quotes/v1';

	// Debounced search to prevent excessive API calls
	const debouncedSetSearchTerm = useMemo(
		() => debounce((value) => {
			setSearchTerm(value);
		}, 500), // 500ms delay
		[]
	);

	// Fetch data based on availability type - only when search term is at least 2 characters
	const shouldSkipSkus = formData.availability_type !== 'product_sku' ||
		formData.box_availability !== 'specific_use' ||
		searchTerm.length < 2;

	const shouldSkipCategories = formData.availability_type !== 'category' ||
		formData.box_availability !== 'specific_use' ||
		searchTerm.length < 2;

	const shouldSkipTags = formData.availability_type !== 'product_tag' ||
		formData.box_availability !== 'specific_use' ||
		searchTerm.length < 2;

	const shouldSkipBrands = formData.availability_type !== 'brand' ||
		formData.box_availability !== 'specific_use' ||
		searchTerm.length < 2;

	const { data: skusData, isFetching: isFetchingSkus } = useGetProductSkusQuery(
		{ url, search: searchTerm },
		{ skip: shouldSkipSkus }
	);

	const { data: categoriesData, isFetching: isFetchingCategories } = useGetProductCategoriesQuery(
		{ url, search: searchTerm },
		{ skip: shouldSkipCategories }
	);

	const { data: tagsData, isFetching: isFetchingTags } = useGetProductTagsQuery(
		{ url, search: searchTerm },
		{ skip: shouldSkipTags }
	);

	const { data: brandsData, isFetching: isFetchingBrands } = useGetProductBrandsQuery(
		{ url, search: searchTerm },
		{ skip: shouldSkipBrands }
	);

	// Get options based on availability type
	const getAutocompleteOptions = () => {
		if (formData.box_availability !== 'specific_use') return [];

		switch (formData.availability_type) {
			case 'product_sku':
				return skusData?.data || [];
			case 'category':
				return categoriesData?.data || [];
			case 'product_tag':
				return tagsData?.data || [];
			case 'brand':
				return brandsData?.data || [];
			default:
				return [];
		}
	};

	// Check if currently fetching
	const isLoadingOptions = () => {
		switch (formData.availability_type) {
			case 'product_sku':
				return isFetchingSkus;
			case 'category':
				return isFetchingCategories;
			case 'product_tag':
				return isFetchingTags;
			case 'brand':
				return isFetchingBrands;
			default:
				return false;
		}
	};

	useEffect(() => {
		if (boxData) {
			setFormData({
				...boxData,
				interior_length: trimNumber(boxData.interior_length),
				interior_width: trimNumber(boxData.interior_width),
				interior_height: trimNumber(boxData.interior_height),
				// Convert null to empty string for form inputs (simple and clean)
				exterior_length: trimNumber(boxData.exterior_length || ''),
				exterior_width: trimNumber(boxData.exterior_width || ''),
				exterior_height: trimNumber(boxData.exterior_height || ''),
				box_fee: trimNumber(boxData.box_fee || ''),
				max_weight: trimNumber(boxData.max_weight || ''),
				box_weight: trimNumber(boxData.box_weight),
				availability_values: boxData.availability_values || [],
				quantity: boxData.quantity || 1,
				is_available: boxData.is_available == 1,
				box_code: +boxData.box_type === 2 ? boxData.box_code : null,
			});
		} else {
			// Reset form when creating new box
			setFormData({
				nickname: '',
				box_type: 1,
				box_code: null,
				interior_length: '',
				interior_width: '',
				interior_height: '',
				exterior_length: '',
				exterior_width: '',
				exterior_height: '',
				max_weight: isMultiPackageBox ? '' : '',
				box_weight: '',
				box_fee: '',
				box_availability: 'universally_available',
				availability_type: 'product_sku',
				availability_values: [],
				is_available: true,
				is_multi_item_box: isMultiPackageBox,
				product_id: selectedProduct?.id || null,
				quantity: 1,
			});
		}
		setErrors({});
	}, [boxData, open, isMultiPackageBox, selectedProduct]);

	const selectedFedexBox = isMultiPackageBox
		? null
		: findFedexOneRateBox(fedexOneRateBoxes, formData.box_code);
	const isFedexBox = !!selectedFedexBox;
	const boxTypeOptions = fedexOneRateBoxes.filter(
		box => showFedexOneRateBoxes || (boxData?.box_code && box.box_code === boxData.box_code)
	);

	/**
	 * Choosing a FedEx One Rate box fills in FedEx's inside dimensions and maximum weight, which the
	 * merchant can still change, leaves the box weight to the merchant and makes the box available for
	 * all products; going back to a merchant defined box clears those values.
	 */
	const handleBoxTypeChange = value => {
		const fedexBox = findFedexOneRateBox(fedexOneRateBoxes, value);
		const previousFedexBox = selectedFedexBox;

		setFormData(prev => {
			const keepNickname =
				prev.nickname.trim() !== '' &&
				!(previousFedexBox && prev.nickname === previousFedexBox.nickname);

			if (fedexBox) {
				return {
					...prev,
					box_type: 2,
					box_code: fedexBox.box_code,
					nickname: keepNickname ? prev.nickname : fedexBox.nickname,
					interior_length: String(fedexBox.length),
					interior_width: String(fedexBox.width),
					interior_height: String(fedexBox.height),
					exterior_length: '',
					exterior_width: '',
					exterior_height: '',
					max_weight: String(fedexBox.max_weight),
					box_weight: '',
					box_availability: 'universally_available',
					availability_values: [],
				};
			}

			return {
				...prev,
				box_type: 1,
				box_code: null,
				nickname: keepNickname ? prev.nickname : '',
				interior_length: '',
				interior_width: '',
				interior_height: '',
				max_weight: '',
				box_weight: '',
			};
		});
		setErrors({});
	};

	const handleChange = (field, value) => {
		setFormData(prev => ({ ...prev, [field]: value }));
		// Clear error for this field
		if (errors[field]) {
			setErrors(prev => ({ ...prev, [field]: '' }));
		}
		// Reset search term and clear selected values when availability type changes
		if (field === 'availability_type') {
			setInputValue('');
			setSearchTerm('');
			setFormData(prev => ({ ...prev, availability_values: [] }));
		}
	};

	// Clean up debounce on unmount
	useEffect(() => {
		return () => {
			debouncedSetSearchTerm.clear();
		};
	}, [debouncedSetSearchTerm]);

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

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

		// Dimension validations (required)
		// Use simple labels for multi-package boxes
		const simpleLabels = isMultiPackageBox || isFedexBox;
		const maxDecimals = isFedexBox ? 3 : 2;
		const dimensionFields = [
			{ field: 'interior_length', label: simpleLabels ? 'Length' : 'Interior Length', max: 999.99 },
			{ field: 'interior_width', label: simpleLabels ? 'Width' : 'Interior Width', max: 999.99 },
			{ field: 'interior_height', label: simpleLabels ? 'Height' : 'Interior Height', max: 999.99 },
		];

		dimensionFields.forEach(({ field, label, max }) => {
			const text = String(formData[field] ?? '');
			const value = parseFloat(text);
			if (text.trim() === '') {
				newErrors[field] = `${label} is required`;
			} else if (isNaN(value)) {
				newErrors[field] = `${label} must be a valid number`;
			} else if (value <= 0) {
				newErrors[field] = `${label} must be greater than 0`;
			} else if (value > max) {
				newErrors[field] = `${label} cannot exceed ${max}`;
			} else {
				const decimalPart = text.split('.')[1];
				if (decimalPart && decimalPart.length > maxDecimals) {
					newErrors[field] = `${label} can have maximum ${maxDecimals} decimal places`;
				}
			}
		});

		// Exterior Dimension validations (optional) - skip for multi-package boxes
		if (!isMultiPackageBox && !isFedexBox) {
			const exteriorDimensionFields = [
				{ field: 'exterior_length', label: 'Exterior Length', max: 999.99 },
				{ field: 'exterior_width', label: 'Exterior Width', max: 999.99 },
				{ field: 'exterior_height', label: 'Exterior Height', max: 999.99 },
			];

			exteriorDimensionFields.forEach(({ field, label, max }) => {
				// Only validate if value is provided
				if (formData[field] && formData[field].trim() !== '') {
					const value = parseFloat(formData[field]);
					if (isNaN(value)) {
						newErrors[field] = `${label} must be a valid number`;
					} else if (value <= 0) {
						newErrors[field] = `${label} must be greater than 0`;
					} else if (value > max) {
						newErrors[field] = `${label} cannot exceed ${max}`;
					} else {
						// Check decimal places
						const decimalPart = formData[field].split('.')[1];
						if (decimalPart && decimalPart.length > 2) {
							newErrors[field] = `${label} can have maximum 2 decimal places`;
						}
					}
				}
			});
		}

		// Weight validations - max_weight is not required for multi-package boxes
		if (!isMultiPackageBox) {
			const maxWeightLabel = isFedexBox ? 'Max weight' : 'Max Weight';
			const maxWeightText = String(formData.max_weight ?? '');
			const maxWeight = parseFloat(maxWeightText);
			if (maxWeightText.trim() === '') {
				newErrors.max_weight = `${maxWeightLabel} is required`;
			} else if (isNaN(maxWeight)) {
				newErrors.max_weight = `${maxWeightLabel} must be a valid number`;
			} else if (maxWeight <= 0) {
				newErrors.max_weight = `${maxWeightLabel} must be greater than 0`;
			} else if (maxWeight > 99999.99) {
				newErrors.max_weight = `${maxWeightLabel} cannot exceed 99999.99`;
			} else {
				const decimalPart = maxWeightText.split('.')[1];
				if (decimalPart && decimalPart.length > 2) {
					newErrors.max_weight = `${maxWeightLabel} can have maximum 2 decimal places`;
				}
			}
		}

		const boxWeightText = String(formData.box_weight ?? '');
		const boxWeight = parseFloat(boxWeightText);
		if (isFedexBox && !(boxWeight > 0)) {
			newErrors.box_weight = 'Box weight must be greater than 0';
		} else if (boxWeightText.trim() === '') {
			newErrors.box_weight = 'Box Weight is required';
		} else if (isNaN(boxWeight)) {
			newErrors.box_weight = 'Box Weight must be a valid number';
		} else if (boxWeight < 0) {
			newErrors.box_weight = 'Box Weight cannot be negative';
		} else if (boxWeight > 99.99) {
			newErrors.box_weight = 'Box Weight cannot exceed 99.99';
		} else {
			const decimalPart = boxWeightText.split('.')[1];
			if (decimalPart && decimalPart.length > 2) {
				newErrors.box_weight = 'Box Weight can have maximum 2 decimal places';
			}
		}

		// Box fee validation (optional field)
		if (formData.box_fee && formData.box_fee.trim() !== '') {
			const boxFee = parseFloat(formData.box_fee);
			if (isNaN(boxFee)) {
				newErrors.box_fee = 'Box Fee must be a valid number';
			} else if (boxFee < 0) {
				newErrors.box_fee = 'Box Fee cannot be negative';
			} else if (boxFee > 9999.99) {
				newErrors.box_fee = 'Box Fee cannot exceed 9999.99';
			} else {
				const decimalPart = formData.box_fee.split('.')[1];
				if (decimalPart && decimalPart.length > 2) {
					newErrors.box_fee = 'Box Fee can have maximum 2 decimal places';
				}
			}
		}

		// Availability validation - not applicable for multi-package boxes
		if (!isMultiPackageBox && !isFedexBox) {
			if (
				formData.box_availability === 'specific_use' &&
				formData.availability_values.length === 0
			) {
				newErrors.availability_values = 'Please add at least one value';
			}
		}

		// Quantity validation for multi-package boxes
		if (isMultiPackageBox) {
			const quantity = parseInt(formData.quantity);
			if (!formData.quantity || formData.quantity.toString().trim() === '') {
				newErrors.quantity = 'Quantity is required';
			} else if (isNaN(quantity)) {
				newErrors.quantity = 'Quantity must be a valid number';
			} else if (quantity < 1) {
				newErrors.quantity = 'Quantity must be at least 1';
			} else if (quantity > 99999) {
				newErrors.quantity = 'Quantity cannot exceed 99999';
			}
		}

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

	/**
	 * One number field of the FedEx One Rate box form, with its label, required mark and error; the
	 * label line has the same height with or without the required mark, so paired fields line up.
	 */
	const renderFedexNumberField = (field, label, required, step, max) => (
		<Grid item xs={6}>
			<FormControl fullWidth>
				<FormHelperText sx={{ minHeight: 24 }}>
					{label}
					{required && (
						<span style={{ color: 'red', fontSize: '14px', display: 'inline-block', marginLeft: '5px' }}>
							*
						</span>
					)}
				</FormHelperText>
				<OutlinedInput
					fullWidth
					size='small'
					type='number'
					value={formData[field]}
					onChange={e => handleChange(field, e.target.value)}
					error={!!errors[field]}
					inputProps={{ step, min: '0', max, 'aria-label': label }}
				/>
				{errors[field] && (
					<FormHelperText sx={{ color: 'red' }}>{errors[field]}</FormHelperText>
				)}
			</FormControl>
		</Grid>
	);

	const handleSubmit = () => {
		if (validateForm()) {
			onSave(formData);
		}
	};

	return (
		<Dialog open={open} onClose={onClose} maxWidth='md' fullWidth>
			<DialogTitle>
				<Typography variant='h6' fontWeight='bold'>
					{isMultiPackageBox
						? (boxData ? 'Edit Product Box Size' : 'Add Product Box Size')
						: 'Box Size'}
				</Typography>
			</DialogTitle>
			<DialogContent>
				<Box sx={{ mt: 2 }}>
					{/* Quantity - only for multi-package boxes */}
					{isMultiPackageBox && (
						<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, step: 1 }}
							/>
							{errors.quantity && (
								<FormHelperText sx={{ color: 'red' }}>{errors.quantity}</FormHelperText>
							)}
						</FormControl>
					)}

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

					{/* Box Type - hide for multi-package boxes */}
					{!isMultiPackageBox && (
						<FormControl fullWidth sx={{ mb: 2 }}>
							<FormHelperText id='rtsq-box-type-label'>Box type</FormHelperText>
							<Select
								fullWidth
								labelId='rtsq-box-type-label'
								value={selectedFedexBox ? selectedFedexBox.box_code : MERCHANT_DEFINED_BOX}
								onChange={e => handleBoxTypeChange(e.target.value)}
								size='small'>
								<MenuItem value={MERCHANT_DEFINED_BOX}>Merchant Defined Box (default)</MenuItem>
								{boxTypeOptions.map(box => (
									<MenuItem key={box.box_code} value={box.box_code}>
										{fedexOneRateBoxLabel(box)}
									</MenuItem>
								))}
							</Select>
							{isFedexBox && (
								<FormHelperText>
									Filled in with this FedEx box's inside dimensions. Used only for FedEx One
									Rate quotes; available for all products.
								</FormHelperText>
							)}
						</FormControl>
					)}

					{isFedexBox && (
						<Grid container spacing={2} sx={{ mb: 2 }}>
							{renderFedexNumberField('interior_length', 'Length (in)', true, '0.001', '999.99')}
							{renderFedexNumberField('interior_width', 'Width (in)', true, '0.001', '999.99')}
							{renderFedexNumberField('interior_height', 'Height (in)', true, '0.001', '999.99')}
							{renderFedexNumberField('max_weight', 'Max weight (LBS)', true, '0.01', '99999.99')}
							{renderFedexNumberField('box_weight', 'Box weight (LBS)', true, '0.01', '99.99')}
							{renderFedexNumberField('box_fee', 'Box fee (e.g 1.75)', false, '0.01', '9999.99')}
						</Grid>
					)}

					{/* Dimensions */}
					{isFedexBox ? null : isMultiPackageBox ? (
						/* Simple dimensions for multi-package and FedEx One Rate boxes */
						<Grid container spacing={2} sx={{ mb: 2 }}>
							<Grid item xs={4}>
								<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.interior_length}
										onChange={e => handleChange('interior_length', e.target.value)}
										error={!!errors.interior_length}
										inputProps={{ step: '0.01', min: '0', max: '999.99' }}
									/>
									{errors.interior_length && (
										<FormHelperText sx={{ color: 'red' }}>{errors.interior_length}</FormHelperText>
									)}
								</FormControl>
							</Grid>
							<Grid item xs={4}>
								<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.interior_width}
										onChange={e => handleChange('interior_width', e.target.value)}
										error={!!errors.interior_width}
										inputProps={{ step: '0.01', min: '0', max: '999.99' }}
									/>
									{errors.interior_width && (
										<FormHelperText sx={{ color: 'red' }}>{errors.interior_width}</FormHelperText>
									)}
								</FormControl>
							</Grid>
							<Grid item xs={4}>
								<FormControl fullWidth>
									<FormHelperText>
										Height (in)
										<span style={{ color: 'red', fontSize: '14px', display: 'inline-block', marginLeft: '5px' }}>
											*
										</span>
									</FormHelperText>
									<OutlinedInput
										fullWidth
										size='small'
										type='number'
										value={formData.interior_height}
										onChange={e => handleChange('interior_height', e.target.value)}
										error={!!errors.interior_height}
										inputProps={{ step: '0.01', min: '0', max: '999.99' }}
									/>
									{errors.interior_height && (
										<FormHelperText sx={{ color: 'red' }}>{errors.interior_height}</FormHelperText>
									)}
								</FormControl>
							</Grid>
						</Grid>
					) : (
						/* Interior and Exterior dimensions for regular boxes */
						<Grid container spacing={2} sx={{ mb: 2 }}>
							<Grid item xs={6}>
								<FormControl fullWidth>
									<FormHelperText>
										Interior Length (in)
										<span style={{ color: 'red', fontSize: '14px', display: 'inline-block', marginLeft: '5px' }}>
											*
										</span>
									</FormHelperText>
									<OutlinedInput
										fullWidth
										size='small'
										type='number'
										value={formData.interior_length}
										onChange={e => handleChange('interior_length', e.target.value)}
										error={!!errors.interior_length}
										inputProps={{ step: '0.01', min: '0', max: '999.99' }}
									/>
									{errors.interior_length && (
										<FormHelperText sx={{ color: 'red' }}>{errors.interior_length}</FormHelperText>
									)}
								</FormControl>
							</Grid>
							<Grid item xs={6}>
								<FormControl fullWidth>
									<FormHelperText>
										Interior Width (in)
										<span style={{ color: 'red', fontSize: '14px', display: 'inline-block', marginLeft: '5px' }}>
											*
										</span>
									</FormHelperText>
									<OutlinedInput
										fullWidth
										size='small'
										type='number'
										value={formData.interior_width}
										onChange={e => handleChange('interior_width', e.target.value)}
										error={!!errors.interior_width}
										inputProps={{ step: '0.01', min: '0', max: '999.99' }}
									/>
									{errors.interior_width && (
										<FormHelperText sx={{ color: 'red' }}>{errors.interior_width}</FormHelperText>
									)}
								</FormControl>
							</Grid>
							<Grid item xs={6}>
								<FormControl fullWidth>
									<FormHelperText>
										Interior Height (in)
										<span style={{ color: 'red', fontSize: '14px', display: 'inline-block', marginLeft: '5px' }}>
											*
										</span>
									</FormHelperText>
									<OutlinedInput
										fullWidth
										size='small'
										type='number'
										value={formData.interior_height}
										onChange={e => handleChange('interior_height', e.target.value)}
										error={!!errors.interior_height}
										inputProps={{ step: '0.01', min: '0', max: '999.99' }}
									/>
									{errors.interior_height && (
										<FormHelperText sx={{ color: 'red' }}>{errors.interior_height}</FormHelperText>
									)}
								</FormControl>
							</Grid>
							<Grid item xs={6}>
								<FormControl fullWidth>
									<FormHelperText>Exterior Length (in)</FormHelperText>
									<OutlinedInput
										fullWidth
										size='small'
										type='number'
										value={formData.exterior_length}
										onChange={e => handleChange('exterior_length', e.target.value)}
										error={!!errors.exterior_length}
										inputProps={{ step: '0.01', min: '0', max: '999.99' }}
									/>
									{errors.exterior_length && (
										<FormHelperText sx={{ color: 'red' }}>{errors.exterior_length}</FormHelperText>
									)}
								</FormControl>
							</Grid>
							<Grid item xs={6}>
								<FormControl fullWidth>
									<FormHelperText>Exterior Width (in)</FormHelperText>
									<OutlinedInput
										fullWidth
										size='small'
										type='number'
										value={formData.exterior_width}
										onChange={e => handleChange('exterior_width', e.target.value)}
										error={!!errors.exterior_width}
										inputProps={{ step: '0.01', min: '0', max: '999.99' }}
									/>
									{errors.exterior_width && (
										<FormHelperText sx={{ color: 'red' }}>{errors.exterior_width}</FormHelperText>
									)}
								</FormControl>
							</Grid>
							<Grid item xs={6}>
								<FormControl fullWidth>
									<FormHelperText>Exterior Height (in)</FormHelperText>
									<OutlinedInput
										fullWidth
										size='small'
										type='number'
										value={formData.exterior_height}
										onChange={e => handleChange('exterior_height', e.target.value)}
										error={!!errors.exterior_height}
										inputProps={{ step: '0.01', min: '0', max: '999.99' }}
									/>
									{errors.exterior_height && (
										<FormHelperText sx={{ color: 'red' }}>{errors.exterior_height}</FormHelperText>
									)}
								</FormControl>
							</Grid>
						</Grid>
					)}

					{/* Weight and Fee */}
					{!isFedexBox && (
					<Grid container spacing={2} sx={{ mb: 2 }}>
						{/* Max Weight - hide for multi-package boxes */}
						{!isMultiPackageBox && (
							<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.01', min: '0', max: '99999.99' }}
									/>
									{errors.max_weight && (
										<FormHelperText sx={{ color: 'red' }}>{errors.max_weight}</FormHelperText>
									)}
								</FormControl>
							</Grid>
						)}
						<Grid item xs={6}>
							<FormControl fullWidth>
								<FormHelperText>
									Box Weight (LBS)
									<span style={{ color: 'red', fontSize: '14px', display: 'inline-block', marginLeft: '5px' }}>
										*
									</span>
								</FormHelperText>
								<OutlinedInput
									fullWidth
									size='small'
									type='number'
									value={formData.box_weight}
									onChange={e => handleChange('box_weight', e.target.value)}
									error={!!errors.box_weight}
									inputProps={{ step: '0.01', min: '0', max: '99.99' }}
								/>
								{errors.box_weight && (
									<FormHelperText sx={{ color: 'red' }}>{errors.box_weight}</FormHelperText>
								)}
							</FormControl>
						</Grid>
						<Grid item xs={6}>
							<FormControl fullWidth>
								<FormHelperText>Box Fee (e.g 1.75)</FormHelperText>
								<OutlinedInput
									fullWidth
									size='small'
									type='number'
									value={formData.box_fee}
									onChange={e => handleChange('box_fee', e.target.value)}
									error={!!errors.box_fee}
									inputProps={{ step: '0.01', min: '0', max: '9999.99' }}
								/>
								{errors.box_fee && (
									<FormHelperText sx={{ color: 'red' }}>{errors.box_fee}</FormHelperText>
								)}
							</FormControl>
						</Grid>
					</Grid>
					)}

					{/* Box Availability - hide for multi-package and FedEx One Rate boxes */}
					{!isMultiPackageBox && !isFedexBox && (
						<>
							<Typography variant='subtitle2' fontWeight='bold' sx={{ mb: 1 }}>
								Box Availability
							</Typography>
							<RadioGroup
								value={formData.box_availability}
								onChange={e => handleChange('box_availability', e.target.value)}>
								<FormControlLabel
									value='universally_available'
									control={<Radio />}
									label='Universally available for use'
								/>
								<FormControlLabel
									value='specific_use'
									control={<Radio />}
									label='For use only with specific products'
								/>
							</RadioGroup>

							{/* Conditional fields for specific use */}
							{formData.box_availability === 'specific_use' && (
						<Box sx={{ ml: 4, mt: 2 }}>
							<Grid container spacing={2}>
								<Grid item xs={3}>
									<FormControlLabel
										value='product_sku'
										control={
											<Radio
												checked={formData.availability_type === 'product_sku'}
												onChange={e =>
													e.target.checked && handleChange('availability_type', 'product_sku')
												}
											/>
										}
										label='Product SKU'
									/>
								</Grid>
								<Grid item xs={3}>
									<FormControlLabel
										value='category'
										control={
											<Radio
												checked={formData.availability_type === 'category'}
												onChange={e =>
													e.target.checked && handleChange('availability_type', 'category')
												}
											/>
										}
										label='Category'
									/>
								</Grid>
								<Grid item xs={3}>
									<FormControlLabel
										value='product_tag'
										control={
											<Radio
												checked={formData.availability_type === 'product_tag'}
												onChange={e =>
													e.target.checked && handleChange('availability_type', 'product_tag')
												}
											/>
										}
										label='Product Tag'
									/>
								</Grid>
								<Grid item xs={3}>
									<FormControlLabel
										value='brand'
										control={
											<Radio
												checked={formData.availability_type === 'brand'}
												onChange={e =>
													e.target.checked && handleChange('availability_type', 'brand')
												}
											/>
										}
										label='Brand'
									/>
								</Grid>
							</Grid>

							<Autocomplete
								multiple
								freeSolo
								options={getAutocompleteOptions()}
								value={formData.availability_values}
								inputValue={inputValue}
								loading={isLoadingOptions()}
								onChange={(_, newValue) => {
									setFormData(prev => ({ ...prev, availability_values: newValue }));
								}}
								onInputChange={(_, newInputValue) => {
									setInputValue(newInputValue);
									debouncedSetSearchTerm(newInputValue);
								}}
								renderTags={(value, getTagProps) =>
									value.map((option, index) => (
										<Chip
											label={option}
											{...getTagProps({ index })}
											color='primary'
											variant='outlined'
										/>
									))
								}
								renderInput={params => (
									<TextField
										{...params}
										variant='outlined'
										size='small'
										label={`Enter ${
											formData.availability_type === 'product_sku'
												? 'Product SKU'
												: formData.availability_type === 'category'
												? 'Category'
												: formData.availability_type === 'product_tag'
												? 'Product Tag'
												: 'Brand'
										}`}
										error={!!errors.availability_values}
										helperText={
											errors.availability_values ||
											(inputValue.length > 0 && inputValue.length < 2
												? 'Type at least 2 characters to search'
												: '')
										}
										placeholder='Type at least 2 characters to search'
									/>
								)}
								noOptionsText={
									inputValue.length < 2
										? 'Type at least 2 characters'
										: isLoadingOptions()
										? 'Loading...'
										: 'No results found'
								}
								sx={{ mt: 2 }}
							/>
						</Box>
					)}
						</>
					)}

					{/* Is Available Checkbox - hide for multi-package boxes */}
					{!isMultiPackageBox && (
						<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} /> : boxData ? 'Update' : 'Save'}
				</Button>
			</DialogActions>
		</Dialog>
	);
};

export default BoxSizeModal;
