import { useState, useEffect, useMemo } from 'react';
import { debounce } from '@mui/material/utils';
import {
	Autocomplete,
	Box,
	Button,
	Checkbox,
	Chip,
	Dialog,
	DialogActions,
	DialogContent,
	DialogTitle,
	FormControl,
	FormControlLabel,
	FormHelperText,
	Grid,
	MenuItem,
	OutlinedInput,
	Radio,
	RadioGroup,
	Select,
	TextField,
	Typography,
} from '@mui/material';
import { useSelector } from 'react-redux';
import { useGetCarriersMutation } from '../redux/Actions/ProvidersAction';
import {
	useGetCountriesStatesQuery,
	useGetProductTagsQuery,
	useGetProductBrandsQuery,
} from '../redux/Actions/WooCommerceDataAction';
import {
	initialState,
	RULE_TYPES,
	APPLY_TO_OPTIONS,
	DEFAULT_APPLY_TO,
} from '../redux/features/shippingRules/shippingRulesSlice';

const RANGE_FILTERS = [
	{ check: 'filter_by_weight_check', from: 'filter_by_weight_from', to: 'filter_by_weight_to', label: 'weight' },
	{ check: 'filter_by_price_check', from: 'filter_by_price_from', to: 'filter_by_price_to', label: 'price' },
	{ check: 'filter_by_quantity_check', from: 'filter_by_quantity_from', to: 'filter_by_quantity_to', label: 'quantity' },
];

const requiredMark = (
	<span style={{ color: 'red', fontSize: '14px', display: 'inline-block', marginLeft: '5px' }}>*</span>
);

const SectionHeading = ({ children }) => (
	<Typography variant='subtitle2' fontWeight='bold' sx={{ mb: 1, mt: 1 }}>
		{children}
	</Typography>
);

const Field = ({ label, required, error, helper, children }) => (
	<FormControl fullWidth sx={{ mb: 2 }}>
		<FormHelperText>
			{label}
			{required ? requiredMark : null}
		</FormHelperText>
		{children}
		{error ? (
			<FormHelperText sx={{ color: 'red' }}>{error}</FormHelperText>
		) : helper ? (
			<FormHelperText>{helper}</FormHelperText>
		) : null}
	</FormControl>
);

const ShippingRuleModal = ({ open, onClose, onSave, ruleData, isSaving }) => {
	const [formData, setFormData] = useState(initialState);
	const [errors, setErrors] = useState({});
	const [carriersByProvider, setCarriersByProvider] = useState({});

	const admin_obj = eniture_rtsq || {};
	const url = admin_obj?.eniture_rtsq_rest_url;

	const { installedProviders } = useSelector(state => state.providers);
	const globalSettings = useSelector(state => state.globalSettings);
	const [getCarriers] = useGetCarriersMutation();
	const { data: countriesData } = useGetCountriesStatesQuery({ url }, { skip: !open });

	const countries = countriesData?.data || [];

	const [tagInput, setTagInput] = useState('');
	const [brandInput, setBrandInput] = useState('');
	const [tagSearch, setTagSearch] = useState('');
	const [brandSearch, setBrandSearch] = useState('');

	const debouncedTagSearch = useMemo(() => debounce(value => setTagSearch(value), 500), []);
	const debouncedBrandSearch = useMemo(() => debounce(value => setBrandSearch(value), 500), []);

	const { data: tagsData, isFetching: isLoadingTags } = useGetProductTagsQuery(
		{ url, search: tagSearch },
		{ skip: !open || tagSearch.length < 2 }
	);
	const { data: brandsData, isFetching: isLoadingBrands } = useGetProductBrandsQuery(
		{ url, search: brandSearch },
		{ skip: !open || brandSearch.length < 2 }
	);

	const tagOptions = tagsData?.data || [];
	const brandOptions = brandsData?.data || [];

	const activeProviders = useMemo(() => {
		return (installedProviders || [])
			.filter(provider => Number(provider.status) === 1)
			.slice()
			.sort((a, b) => (a.name || '').localeCompare(b.name || ''));
	}, [installedProviders]);

	const showFilters =
		formData.rule_type !== 'showcheapest' && formData.rule_type !== 'largecartsettings';
	const showProviders =
		formData.rule_type === 'hidemethods' || formData.rule_type === 'freeshipping';
	const showApplyTo = formData.rule_type !== 'largecartsettings';
	const isSurcharge = formData.rule_type === 'surcharge';
	const isDiscount = formData.rule_type === 'discount';
	const isFreeShipping = formData.rule_type === 'freeshipping';
	const showLocation =
		formData.rule_type === 'hidemethods' ||
		formData.rule_type === 'overriderates' ||
		formData.rule_type === 'freeshipping';

	useEffect(() => {
		if (!open) return;

		if (ruleData) {
			const filterSettings = ruleData.filter_settings || {};
			const normalizedRule = {};

			Object.keys(initialState).forEach(key => {
				if (Object.prototype.hasOwnProperty.call(ruleData, key)) {
					normalizedRule[key] = ruleData[key];
				}

				if (Object.prototype.hasOwnProperty.call(filterSettings, key)) {
					normalizedRule[key] = filterSettings[key];
				}
			});

			setFormData({
				...initialState,
				...normalizedRule,
				providers: ruleData.providers || [],
				is_available: Boolean(Number(ruleData.is_available)),
			});
		} else {
			setFormData(initialState);
		}

		setErrors({});
	}, [open, ruleData]);

	useEffect(() => {
		const selected = formData.providers || [];
		if (selected.length === 0) return;

		selected.forEach(entry => {
			const uuid = entry.installed_provider_uuid;
			if (!uuid || carriersByProvider[uuid]) return;

			getCarriers({ action: 'get_carriers', url, installed_provider_uuid: uuid })
				.unwrap()
				.then(res => {
					if (!res?.error) {
						setCarriersByProvider(prev => ({
							...prev,
							[uuid]: {
								options: res?.data?.carriers || [],
								isServices: res?.data?.list_type === 'services',
							},
						}));
					}
				})
				.catch(() => {});
		});
	}, [formData.providers, url]);

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

		setFormData(prev => {
			if (field === 'rule_type') {
				return {
					...prev,
					rule_type: value,
					apply_to: DEFAULT_APPLY_TO[value] ?? 'cart',
					providers: [],
				};
			}
			return { ...prev, [field]: value };
		});
	};

	const handleProviderSelection = selectedUuids => {
		setFormData(prev => {
			const providers = selectedUuids.map(uuid => {
				const existing = (prev.providers || []).find(p => p.installed_provider_uuid === uuid);
				return existing || { installed_provider_uuid: uuid, services: [] };
			});

			const applyTo =
				prev.rule_type === 'freeshipping' && providers.length > 0 && prev.apply_to === 'product'
					? 'cart'
					: prev.apply_to;

			return { ...prev, providers, apply_to: applyTo };
		});
	};

	const handleServiceSelection = (providerUuid, services) => {
		setFormData(prev => ({
			...prev,
			providers: (prev.providers || []).map(p =>
				p.installed_provider_uuid === providerUuid ? { ...p, services } : p
			),
		}));
	};

	const handleCountrySelection = selected => {
		const codes = selected.map(country => country.code);
		setFormData(prev => {
			const states = { ...prev.states };
			Object.keys(states).forEach(code => {
				if (!codes.includes(code)) delete states[code];
			});
			return { ...prev, countries: codes, states };
		});
	};

	const validate = () => {
		const validationErrors = {};

		if (!formData.rule_name?.trim()) {
			validationErrors.rule_name = 'Rule name is required.';
		}

		if ((isSurcharge || isDiscount) && !String(formData.discount_or_surcharge_amount).trim()) {
			validationErrors.discount_or_surcharge_amount = 'Discount/Surcharge amount is required.';
		}

		if (formData.rule_type === 'overriderates' && !String(formData.flat_rate).trim()) {
			validationErrors.flat_rate = 'Flat rate is required.';
		}

		if (formData.rule_type === 'largecartsettings') {
			if (!formData.max_items || Number(formData.max_items) < 1) {
				validationErrors.max_items = 'Max items must be greater than 0.';
			}
			const maxWeight = Number(formData.max_weight_per_package);
			if (!formData.max_weight_per_package || maxWeight <= 0 || maxWeight > 150) {
				validationErrors.max_weight_per_package =
					'Max weight per package must be greater than 0 and no more than 150.';
			}
		}

		if (showFilters) {
			RANGE_FILTERS.forEach(filter => {
				if (!formData[filter.check]) return;

				const from = formData[filter.from];
				const to = formData[filter.to];

				if (from === '' || from === null || from === undefined) {
					validationErrors[filter.from] = `Filter by ${filter.label} from is required.`;
				} else if (to !== '' && to !== null && Number(to) <= Number(from)) {
					validationErrors[filter.to] = `Filter by ${filter.label} to must be greater than from.`;
				}
			});

			if (formData.filter_by_brand_check && !formData.filter_by_brand_value?.trim()) {
				validationErrors.filter_by_brand_value = 'Filter by product brand value is required.';
			}

			if (formData.filter_by_product_tag_check && !formData.filter_by_product_tag_value?.trim()) {
				validationErrors.filter_by_product_tag_value = 'Filter by product tag value is required.';
			}

			if (formData.filter_by_country_state_check && formData.countries.length === 0) {
				validationErrors.countries = 'Select at least one country.';
			}
		}

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

	const handleSave = () => {
		if (validate()) onSave(formData);
	};

	const numericChange = (field, value, allowDecimal = true) => {
		const pattern = allowDecimal ? /^\d*\.?\d*$/ : /^\d*$/;
		if (pattern.test(value)) handleChange(field, value);
	};

	const applyToOptions = (APPLY_TO_OPTIONS[formData.rule_type] || []).filter(option => {
		if (option.value !== 'product') return true;
		return (formData.providers || []).length === 0;
	});

	const radEnabled = Boolean(globalSettings?.auto_detect_residential_address);

	const rangeFilter = filter => (
		<Box key={filter.check} sx={{ mb: 2 }}>
			<FormControlLabel
				control={
					<Checkbox
						checked={Boolean(formData[filter.check])}
						onChange={e => handleChange(filter.check, e.target.checked)}
					/>
				}
				label={`Filter by ${filter.label}`}
			/>
			<Grid container spacing={2}>
				<Grid item xs={6}>
					<FormControl fullWidth>
						<FormHelperText>From</FormHelperText>
						<OutlinedInput
							fullWidth
							size='small'
							value={formData[filter.from]}
							disabled={!formData[filter.check]}
							onChange={e => numericChange(filter.from, e.target.value, filter.label !== 'quantity')}
							error={!!errors[filter.from]}
						/>
						{errors[filter.from] && (
							<FormHelperText sx={{ color: 'red' }}>{errors[filter.from]}</FormHelperText>
						)}
					</FormControl>
				</Grid>
				<Grid item xs={6}>
					<FormControl fullWidth>
						<FormHelperText>To</FormHelperText>
						<OutlinedInput
							fullWidth
							size='small'
							value={formData[filter.to]}
							disabled={!formData[filter.check]}
							onChange={e => numericChange(filter.to, e.target.value, filter.label !== 'quantity')}
							error={!!errors[filter.to]}
						/>
						{errors[filter.to] && (
							<FormHelperText sx={{ color: 'red' }}>{errors[filter.to]}</FormHelperText>
						)}
					</FormControl>
				</Grid>
			</Grid>
		</Box>
	);

	const termFilter = (checkKey, valueKey, label, options, isLoading, inputValue, setInputValue, onSearch, placeholder) => {
		const selected = String(formData[valueKey] || '')
			.split(',')
			.map(v => v.trim())
			.filter(Boolean);

		return (
			<Box sx={{ mb: 2 }}>
				<FormControlLabel
					control={
						<Checkbox
							checked={Boolean(formData[checkKey])}
							onChange={e => handleChange(checkKey, e.target.checked)}
						/>
					}
					label={label}
				/>
				<Autocomplete
					multiple
					freeSolo
					size='small'
					disabled={!formData[checkKey]}
					options={options}
					value={selected}
					inputValue={inputValue}
					loading={isLoading}
					onChange={(event, newValue) => handleChange(valueKey, newValue.join(','))}
					onInputChange={(event, newInput) => {
						setInputValue(newInput);
						onSearch(newInput);
					}}
					renderTags={(value, getTagProps) =>
						value.map((option, index) => (
							<Chip
								label={option}
								{...getTagProps({ index })}
								key={option}
								color='primary'
								variant='outlined'
								size='small'
							/>
						))
					}
					renderInput={params => (
						<TextField
							{...params}
							size='small'
							error={!!errors[valueKey]}
							helperText={errors[valueKey] || ''}
							placeholder={placeholder}
						/>
					)}
					noOptionsText={
						inputValue.length < 2 ? 'Type at least 2 characters' : isLoading ? 'Loading...' : 'No results found'
					}
				/>
			</Box>
		);
	};

	return (
		<Dialog open={open} onClose={onClose} maxWidth='md' fullWidth>
			<DialogTitle>
				<Typography variant='h6' fontWeight='bold'>
					{ruleData ? 'Edit Shipping Rule' : 'Add Shipping Rule'}
				</Typography>
			</DialogTitle>
			<DialogContent dividers>
				<Field label='Rule name' required error={errors.rule_name}>
					<OutlinedInput
						fullWidth
						size='small'
						value={formData.rule_name}
						onChange={e => handleChange('rule_name', e.target.value)}
						error={!!errors.rule_name}
						inputProps={{ maxLength: 100 }}
					/>
				</Field>

				<Field label='Type'>
					<Select
						fullWidth
						size='small'
						value={formData.rule_type}
						onChange={e => handleChange('rule_type', e.target.value)}>
						{RULE_TYPES.map(type => (
							<MenuItem key={type.value} value={type.value}>
								{type.label}
							</MenuItem>
						))}
					</Select>
				</Field>

				{showApplyTo && applyToOptions.length > 0 && (
					<Box sx={{ mb: 2 }}>
						<FormHelperText>Apply to:</FormHelperText>
						<RadioGroup
							value={formData.apply_to}
							onChange={e => handleChange('apply_to', e.target.value)}>
							{applyToOptions.map(option => (
								<FormControlLabel
									key={option.value}
									value={option.value}
									control={<Radio size='small' />}
									label={option.label}
								/>
							))}
						</RadioGroup>
					</Box>
				)}

				{showProviders && (
					<>
						<Field label="Shipping provider's nickname">
							<Autocomplete
								multiple
								size='small'
								options={activeProviders}
								getOptionLabel={option => option.name || ''}
								isOptionEqualToValue={(option, value) => option.uuid === value.uuid}
								value={activeProviders.filter(provider =>
									(formData.providers || []).some(p => p.installed_provider_uuid === provider.uuid)
								)}
								onChange={(event, selected) => handleProviderSelection(selected.map(p => p.uuid))}
								renderInput={params => (
									<TextField {...params} placeholder='Select installed providers' />
								)}
							/>
						</Field>

						{(formData.providers || []).map(entry => {
							const provider = activeProviders.find(p => p.uuid === entry.installed_provider_uuid);
							const carrierList = carriersByProvider[entry.installed_provider_uuid] || {};
							const carriers = carrierList.options || [];

							return (
								<Field
									key={entry.installed_provider_uuid}
									label={`${carrierList.isServices ? 'Services' : 'Carriers'} — ${provider?.name || ''}`}>
									<Autocomplete
										multiple
										size='small'
										options={carriers}
										getOptionLabel={option => option.carrier_name || option.scac || ''}
										isOptionEqualToValue={(option, value) => option.scac === value.scac}
										value={carriers.filter(carrier => (entry.services || []).includes(carrier.scac))}
										onChange={(event, selected) =>
											handleServiceSelection(
												entry.installed_provider_uuid,
												selected.map(carrier => carrier.scac)
											)
										}
										renderInput={params => (
											<TextField
												{...params}
												placeholder={carrierList.isServices ? 'All services' : 'All carriers'}
											/>
										)}
									/>
								</Field>
							);
						})}
					</>
				)}

				{(isSurcharge || isDiscount) && (
					<>
						<Field
							label='Discount/Surcharge Amount'
							required
							error={errors.discount_or_surcharge_amount}
							helper='Amount excluding tax. Enter an amount, e.g 3.75, or a percentage of the shipping rate, e.g 5%. A negative value reverses the rule.'>
							<OutlinedInput
								fullWidth
								size='small'
								value={formData.discount_or_surcharge_amount}
								onChange={e => handleChange('discount_or_surcharge_amount', e.target.value)}
								error={!!errors.discount_or_surcharge_amount}
							/>
						</Field>

						{isSurcharge && formData.apply_to === 'product_tag' && (
							<Box sx={{ mb: 2 }}>
								<FormHelperText>Surcharge × Quantity:</FormHelperText>
								<RadioGroup
									value={formData.multiply_by_quantity ?? '0'}
									onChange={e => handleChange('multiply_by_quantity', e.target.value)}>
									<FormControlLabel
										value='1'
										control={<Radio size='small' />}
										label='Yes — multiply surcharge by product quantity'
									/>
									<FormControlLabel
										value='0'
										control={<Radio size='small' />}
										label='No — apply surcharge once per shipment'
									/>
								</RadioGroup>
								<FormHelperText>
									When enabled, the surcharge amount will be multiplied by the quantity of products
									that match the configured product tags. This surcharge is added to the final
									shipping rate during rate calculation.
								</FormHelperText>
							</Box>
						)}

						{isSurcharge && formData.apply_to === 'cart' && (
							<Box sx={{ mb: 2 }}>
								<FormHelperText>Surcharge × Weight:</FormHelperText>
								<RadioGroup
									value={formData.multiply_by_weight ?? '0'}
									onChange={e => handleChange('multiply_by_weight', e.target.value)}>
									<FormControlLabel
										value='1'
										control={<Radio size='small' />}
										label='Yes — multiply surcharge by total cart weight'
									/>
									<FormControlLabel
										value='0'
										control={<Radio size='small' />}
										label='No — apply surcharge once per cart'
									/>
								</RadioGroup>
								<FormHelperText>
									When enabled, the surcharge amount will be multiplied by the total weight of all
									items in the cart.
								</FormHelperText>
							</Box>
						)}
					</>
				)}

				{formData.rule_type === 'overriderates' && (
					<>
						<Field label='Display as'>
							<OutlinedInput
								fullWidth
								size='small'
								value={formData.display_as}
								onChange={e => handleChange('display_as', e.target.value)}
							/>
						</Field>
						<Field label='Description'>
							<OutlinedInput
								fullWidth
								size='small'
								value={formData.description}
								onChange={e => handleChange('description', e.target.value)}
							/>
						</Field>
						<Field label='Flat rate' required error={errors.flat_rate}>
							<OutlinedInput
								fullWidth
								size='small'
								value={formData.flat_rate}
								onChange={e => numericChange('flat_rate', e.target.value)}
								error={!!errors.flat_rate}
							/>
						</Field>
						<Box sx={{ mb: 2 }}>
							<FormControlLabel
								control={
									<Checkbox
										checked={Boolean(formData.suppress_rate)}
										onChange={e => handleChange('suppress_rate', e.target.checked)}
									/>
								}
								label='Suppress other rates'
							/>
						</Box>
					</>
				)}

				{isFreeShipping && (
					<Field
						label='Label as'
						helper='Applied when the rule is limited to particular providers or carriers. Otherwise each carrier keeps its own service name.'>
						<OutlinedInput
							fullWidth
							size='small'
							value={formData.free_shipping_label}
							onChange={e => handleChange('free_shipping_label', e.target.value)}
						/>
					</Field>
				)}

				{formData.rule_type === 'largecartsettings' && (
					<>
						<Field
							label='Max items'
							required
							error={errors.max_items}
							helper='When the cart contains more than this number of items, the packaging algorithm will be bypassed and rates will be calculated exclusively on the basis of weight.'>
							<OutlinedInput
								fullWidth
								size='small'
								value={formData.max_items}
								onChange={e => numericChange('max_items', e.target.value, false)}
								error={!!errors.max_items}
							/>
						</Field>
						<Field
							label='Max weight per package'
							required
							error={errors.max_weight_per_package}
							helper='Specify the maximum weight allowed per package when the packaging algorithm is bypassed. The maximum permitted value is 150 LB.'>
							<OutlinedInput
								fullWidth
								size='small'
								value={formData.max_weight_per_package}
								onChange={e => numericChange('max_weight_per_package', e.target.value)}
								error={!!errors.max_weight_per_package}
							/>
						</Field>
					</>
				)}

				{showFilters && (
					<>
						{RANGE_FILTERS.map(rangeFilter)}

						{termFilter(
							'filter_by_brand_check',
							'filter_by_brand_value',
							'Filter by product brand',
							brandOptions,
							isLoadingBrands,
							brandInput,
							setBrandInput,
							debouncedBrandSearch,
							'Type at least 2 characters to search'
						)}

						{termFilter(
							'filter_by_product_tag_check',
							'filter_by_product_tag_value',
							'Filter by product tag',
							tagOptions,
							isLoadingTags,
							tagInput,
							setTagInput,
							debouncedTagSearch,
							'Type at least 2 characters to search'
						)}

						{isFreeShipping && formData.apply_to !== 'product' && (
							<Box sx={{ mb: 2, pl: 2 }}>
								<FormHelperText>When product tag filter is satisfied...</FormHelperText>
								<FormControlLabel
									control={
										<Checkbox
											disabled={!formData.filter_by_product_tag_check}
											checked={Boolean(formData.calculate_without_matching_product_tags)}
											onChange={e =>
												handleChange('calculate_without_matching_product_tags', e.target.checked)
											}
										/>
									}
									label='Calculate shipping using products without matching product tag(s)'
								/>
							</Box>
						)}

						<Box sx={{ mb: 2 }}>
							<FormControlLabel
								control={
									<Checkbox
										checked={Boolean(formData.filter_by_address_type)}
										onChange={e => handleChange('filter_by_address_type', e.target.checked)}
									/>
								}
								label='Filter by address type'
							/>
							<FormControl fullWidth>
								<Select
									fullWidth
									size='small'
									value={formData.address_type_check}
									disabled={!formData.filter_by_address_type}
									onChange={e => handleChange('address_type_check', e.target.value)}>
									<MenuItem value='all'>All address types (default)</MenuItem>
									<MenuItem value='commercial' disabled={!radEnabled}>
										Commercial addresses
									</MenuItem>
									<MenuItem value='residential' disabled={!radEnabled}>
										Residential addresses
									</MenuItem>
								</Select>
								{!radEnabled && (
									<FormHelperText>
										Residential and commercial options require automatic residential address
										detection to be enabled in Address Type Settings.
									</FormHelperText>
								)}
							</FormControl>
						</Box>

						{showLocation && (
							<Box sx={{ mb: 2 }}>
								<FormControlLabel
									control={
										<Checkbox
											checked={Boolean(formData.filter_by_country_state_check)}
											onChange={e => handleChange('filter_by_country_state_check', e.target.checked)}
										/>
									}
									label='Filter by location'
								/>
								<Field label='Countries' error={errors.countries}>
									<Autocomplete
										multiple
										size='small'
										disabled={!formData.filter_by_country_state_check}
										options={countries}
										getOptionLabel={option => option.name || ''}
										isOptionEqualToValue={(option, value) => option.code === value.code}
										value={countries.filter(country => formData.countries.includes(country.code))}
										onChange={(event, selected) => handleCountrySelection(selected)}
										renderInput={params => <TextField {...params} placeholder='Select countries' />}
									/>
								</Field>

								{formData.filter_by_country_state_check &&
									formData.countries.map(code => {
										const country = countries.find(c => c.code === code);
										if (!country || country.states.length === 0) return null;

										return (
											<Field key={code} label={`States/Provinces — ${country.name}`}>
												<Autocomplete
													multiple
													size='small'
													options={country.states}
													getOptionLabel={option => option.name || ''}
													isOptionEqualToValue={(option, value) => option.code === value.code}
													value={country.states.filter(state =>
														(formData.states[code] || []).includes(state.code)
													)}
													onChange={(event, selected) =>
														handleChange('states', {
															...formData.states,
															[code]: selected.map(state => state.code),
														})
													}
													renderInput={params => (
														<TextField {...params} placeholder='Select states' />
													)}
												/>
											</Field>
										);
									})}
							</Box>
						)}

						<RadioGroup
							value={String(formData.match_with_logical_operator)}
							onChange={e => handleChange('match_with_logical_operator', Number(e.target.value))}>
							<FormControlLabel
								value='2'
								control={<Radio size='small' />}
								label='Apply rule only if all the filters are met'
							/>
							<FormControlLabel
								value='1'
								control={<Radio size='small' />}
								label='Apply rule if any of the filters are met'
							/>
						</RadioGroup>
					</>
				)}

				<Box sx={{ mt: 1 }}>
					<FormControlLabel
						control={
							<Checkbox
								checked={Boolean(formData.is_available)}
								onChange={e => handleChange('is_available', e.target.checked)}
							/>
						}
						label='Available'
					/>
				</Box>
			</DialogContent>
			<DialogActions>
				<Button onClick={onClose} disabled={isSaving}>
					Cancel
				</Button>
				<Button onClick={handleSave} variant='contained' disabled={isSaving}>
					{isSaving ? 'Saving...' : 'Save'}
				</Button>
			</DialogActions>
		</Dialog>
	);
};

export default ShippingRuleModal;
