import { Grid, Typography, FormControlLabel, Checkbox, FormHelperText, Box, TextField } from '@mui/material';
import { useSelector } from 'react-redux';
import DESCRIPTIONS from '../constants/descriptions';
import { isPositiveNumber } from '../utils/numbers';

export const LIMITED_ACCESS_FEE_MESSAGE = 'Enter the limited access delivery fee as a number greater than 0.';

const enabled = value => [true, 1, '1', 'true', 'yes', 'on'].includes(value);

/**
 * Whether any limited access setting is on.
 */
export const isLimitedAccessEnabled = state =>
	enabled(state?.always_quote_limited_access_delivery) ||
	enabled(state?.offer_limited_access_delivery) ||
	enabled(state?.auto_detect_residential_addresses_limited_access);

/**
 * Whether the limited access fee is missing or not greater than 0 while limited access is on.
 */
export const limitedAccessFeeInvalid = state => {
	const fee = state?.limited_access_delivery_fee ?? '';

	return isLimitedAccessEnabled(state) && (String(fee).trim() === '' || !isPositiveNumber(fee));
};

/**
 * Limited access delivery: always, as an option, or when a residential address is detected, with the
 * fee the store charges for it (the carrier does not price it). Without a fee no limited access rate shows.
 * With requireFee the fee field shows an error while limited access is on and the fee is not above 0.
 */
const LimitedAccess = ({ state = {}, handleChange = (name = '', val = '') => {}, requireFee = false }) => {
	const settings = useSelector(state => state.globalSettings);
	const automaticDetectionUnavailable =
		enabled(settings?.suspend_rad_use) || enabled(settings?.always_quote_residential_delivery);
	const anyLimitedAccess = isLimitedAccessEnabled(state);
	const feeError = requireFee && limitedAccessFeeInvalid(state);

	return (
		<Grid container spacing={1} flex mt={3} mb={3} className='woo-rtsq-limited-access'>
			<Grid item flex={1} xs={4}>
				<Typography variant='subtitle1' fontWeight='bold'>
					Limited access settings
				</Typography>
				<p>
					<strong>Always quote limited access delivery</strong> -{' '}
					{DESCRIPTIONS.quote_limited_access}
				</p>
				<p>
					<strong>Offer limited access delivery as an option</strong> -{' '}
					{DESCRIPTIONS.offer_limited_access}
				</p>
				<p>
					<strong>
						Always include limited access delivery when a residential address is detected
					</strong>{' '}
					- {DESCRIPTIONS.always_quote_limited_access_when_residential}
				</p>
			</Grid>

			<Grid item flex={2} xs={8} mt={2}>
				<Box>
					<FormControlLabel
						control={
							<Checkbox
								checked={enabled(state?.always_quote_limited_access_delivery)}
								onChange={e => {
									handleChange('always_quote_limited_access_delivery', e.target.checked);
									handleChange('offer_limited_access_delivery', false);
									handleChange('auto_detect_residential_addresses_limited_access', false);
								}}
							/>
						}
						label='Always quote limited access delivery'
						title='Always quote limited access delivery'
					/>
				</Box>
				<Box>
					<FormControlLabel
						control={
							<Checkbox
								checked={enabled(state?.offer_limited_access_delivery)}
								onChange={e => {
									handleChange('offer_limited_access_delivery', e.target.checked);
									handleChange('always_quote_limited_access_delivery', false);
								}}
							/>
						}
						label='Offer limited access delivery as an option'
						title='Offer limited access delivery as an option'
					/>
				</Box>
				<FormControlLabel
					control={
						<Checkbox
							checked={enabled(state?.auto_detect_residential_addresses_limited_access)}
							onChange={e => {
								handleChange('auto_detect_residential_addresses_limited_access', e.target.checked);
								handleChange('always_quote_limited_access_delivery', false);
							}}
							disabled={automaticDetectionUnavailable}
						/>
					}
					label='Always include limited access delivery when a residential address is detected'
					title='Always include limited access delivery when a residential address is detected'
				/>

				{automaticDetectionUnavailable && (
					<Box ml={3}>
						<FormHelperText sx={{ color: 'error.main' }}>
							This option is only available when auto detect residential address settings is enabled.
						</FormHelperText>
					</Box>
				)}

				<Box mt={3}>
					<TextField
						label='Limited access delivery fee'
						title='Limited access delivery fee'
						placeholder='Enter delivery fee, e.g 100'
						variant='standard'
						helperText={feeError ? LIMITED_ACCESS_FEE_MESSAGE : DESCRIPTIONS.limited_access_fee}
						error={feeError}
						InputLabelProps={{ shrink: true }}
						inputProps={{ maxLength: 8 }}
						fullWidth
						disabled={!anyLimitedAccess}
						value={state?.limited_access_delivery_fee ?? ''}
						onChange={e => {
							e.target.value.match(/^[0-9]*\.?[0-9]{0,2}$/) &&
								handleChange('limited_access_delivery_fee', e.target.value);
						}}
					/>
				</Box>
			</Grid>
		</Grid>
	);
};

export default LimitedAccess;
