import { useRef, useState } from 'react';
import {
	Box,
	Checkbox,
	FormControlLabel,
	FormGroup,
	Grid,
	Stack,
	TextField,
	Typography,
	Chip,
	Divider,
	Tooltip,
	Card,
} from '@mui/material';
import { useDispatch } from 'react-redux';
import { setAlert } from '../redux/features/providers/providersSlice';
import { dispatchAlert } from '../redux/Actions/ProvidersAction';

const InstoreAndLocalDelSettings = ({
	locationDetails,
	setLocationDetails = () => {},
	handleChange = (name = '', val = '') => {},
}) => {
	const [isTag, setIsTag] = useState(''),
		[ldTag, setldTag] = useState(''),
		isInputRef = useRef(null),
		ldInputRef = useRef(),
		dispatch = useDispatch();

	const addTag = (setValue, val, field, enterKey = false) => {
		if (!val.includes(',') && !enterKey) {
			setValue(val);
			return;
		}

		const code = val.substring(0, enterKey ? val.length : val.length - 1);
		if (locationDetails?.[field]?.includes(code)) {
			dispatch(setAlert(dispatchAlert(true, 'Duplicate postal code', 'error')));
			return;
		}

		setLocationDetails(prevState => {
			const fieldData =
				prevState?.[field] && Array.isArray(prevState?.[field]) ? prevState?.[field] : [];
			setValue('');

			return {
				...prevState,
				[field]: [...fieldData, code],
			};
		});
	};

	const removeTag = (code, field_name) => {
		setLocationDetails(prevState => ({
			...prevState,
			[field_name]: prevState[field_name].filter(c => c !== code),
		}));
	};

	return (
		<>
			{/* In-store pick up section */}
			<Grid container spacing={1} flex mt={3} mb={3}>
				<Grid item flex={1} xs={4}>
					<Typography variant='subtitle1' fontWeight='bold'>
						In-store pick up
					</Typography>
					<p>WooCommerce and your customers will use this information to contact you</p>
				</Grid>
				<Grid item flex={2} xs={8}>
					<Box component='form'>
						<form noValidate autoComplete='off'>
							<Box
								component='div'
								sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
								<FormGroup>
									<FormControlLabel
										control={
											<Checkbox
												checked={
													locationDetails?.enable_instore_pickup || false
												}
												onChange={e =>
													handleChange(
														'enable_instore_pickup',
														e.target.checked
													)
												}
											/>
										}
										label='Enable in-store pick up'
										title='Enable in-store pick up'
									/>
								</FormGroup>

								<TextField
									label='Offer if address is within (miles)'
									title='Offer if address is within (miles)'
									type='number'
									variant='standard'
									InputLabelProps={{ shrink: true }}
									fullWidth
									value={locationDetails?.instore_pickup_within_address || ''}
									onChange={e =>
										e.target.value.length < 8 &&
										handleChange(
											'instore_pickup_within_address',
											e.target.value
										)
									}
								/>

								{/* In-store pick up match postal codes */}
								<div
									onClick={() => isInputRef.current?.focus()}
									className='postal-code-match-container'
									title='Offer if postal code matches'>
									<label
										className='postal-code-match-label'
										title='Offer if postal code matches'>
										Offer if postal code matches
									</label>

									<div
										style={{
											padding: '2px',
											border: '1px solid #8c8f94',
											borderRadius: '4px',
											marginTop: '0px',
										}}>
										<Stack
											direction='row'
											flexWrap='wrap'
											gap={1}
											alignItems='center'>
											{locationDetails?.instore_pickup_match_postal_codes?.map(
												(item, index) => (
													<Chip
														key={index}
														label={item}
														clickable
														onDelete={() =>
															removeTag(
																item,
																'instore_pickup_match_postal_codes'
															)
														}
													/>
												)
											)}

											<Box flexGrow={1}>
												<input
													type='text'
													value={isTag}
													maxLength={7}
													ref={isInputRef}
													placeholder='Separate options with comma'
													className='postal-code-match-input'
													onChange={e => {
														addTag(
															setIsTag,
															e.target.value,
															'instore_pickup_match_postal_codes'
														);
													}}
													onBlur={e => {
														if (isTag.length) {
															addTag(
																setIsTag,
																isTag,
																'instore_pickup_match_postal_codes',
																true
															);
														}
													}}
													onKeyDown={e => {
														if (e.key === 'Enter') {
															e.preventDefault();
															addTag(
																setIsTag,
																e.target.value,
																'instore_pickup_match_postal_codes',
																true
															);
														}
													}}
												/>
											</Box>
										</Stack>
									</div>
								</div>

								<TextField
									label='Checkout description'
									title='Checkout description'
									variant='standard'
									InputLabelProps={{ shrink: true }}
									inputProps={{ maxLength: 300 }}
									fullWidth
									value={
										locationDetails?.instore_pickup_checkout_description || ''
									}
									onChange={e =>
										handleChange(
											'instore_pickup_checkout_description',
											e.target.value
										)
									}
								/>
							</Box>
						</form>
					</Box>
				</Grid>
			</Grid>

			<Divider variant='fullWidth' />

			{/* Local Delivery section */}
			<Grid container spacing={1} flex mt={3}>
				<Grid item flex={1} xs={4}>
					<Typography variant='subtitle1' fontWeight='bold'>
						Local Delivery
					</Typography>
					<p>WooCommerce and your customers will use this information to contact you</p>
				</Grid>
				<Grid item flex={2} xs={8}>
					<Box component='form'>
						<form noValidate autoComplete='off'>
							<Box
								component='div'
								sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
								<FormGroup>
									<FormControlLabel
										control={
											<Checkbox
												checked={
													locationDetails?.enable_local_delivery || false
												}
												onChange={e =>
													handleChange(
														'enable_local_delivery',
														e.target.checked
													)
												}
											/>
										}
										label='Enable local delivery'
										title='Enable local delivery'
									/>
								</FormGroup>

								<TextField
									label='Offer if address is within (miles):'
									title='Offer if address is within (miles)'
									type='number'
									variant='standard'
									InputLabelProps={{ shrink: true }}
									fullWidth
									value={locationDetails?.local_delivery_within_address || ''}
									onChange={e =>
										e.target.value.length < 8 &&
										handleChange(
											'local_delivery_within_address',
											e.target.value
										)
									}
								/>

								{/* Local delivery match postal codes */}
								<div
									onClick={() => ldInputRef.current?.focus()}
									className='postal-code-match-container'
									title='Offer if postal code matches'>
									<label
										className='postal-code-match-label'
										title='Offer if postal code matches'>
										Offer if postal code matches
									</label>

									<div
										style={{
											padding: '2px',
											border: '1px solid #8c8f94',
											borderRadius: '4px',
											marginTop: '0px',
										}}>
										<Stack
											direction='row'
											flexWrap='wrap'
											gap={1}
											alignItems='center'>
											{locationDetails?.local_delivery_match_postal_codes?.map(
												(item, index) => (
													<Chip
														key={index}
														label={item}
														clickable
														onDelete={() =>
															removeTag(
																item,
																'local_delivery_match_postal_codes'
															)
														}
													/>
												)
											)}

											<Box flexGrow={1}>
												<input
													type='text'
													value={ldTag}
													maxLength={7}
													ref={ldInputRef}
													placeholder='Separate options with comma'
													className='postal-code-match-input'
													onChange={e => {
														addTag(
															setldTag,
															e.target.value,
															'local_delivery_match_postal_codes'
														);
													}}
													onBlur={e => {
														if (ldTag.length) {
															addTag(
																setldTag,
																e.target.value,
																'local_delivery_match_postal_codes',
																true
															);
														}
													}}
													onKeyDown={e => {
														if (e.key === 'Enter') {
															e.preventDefault();
															addTag(
																setldTag,
																e.target.value,
																'local_delivery_match_postal_codes',
																true
															);
														}
													}}
												/>
											</Box>
										</Stack>
									</div>
								</div>

								<TextField
									label='Checkout description'
									title='Checkout description'
									variant='standard'
									InputLabelProps={{ shrink: true }}
									inputProps={{ maxLength: 300 }}
									fullWidth
									value={
										locationDetails?.local_delivery_checkout_description || ''
									}
									onChange={e =>
										handleChange(
											'local_delivery_checkout_description',
											e.target.value
										)
									}
								/>
								<TextField
									label='Local delivery fee'
									title='Local delivery fee'
									variant='standard'
									type='number'
									InputLabelProps={{ shrink: true }}
									inputProps={{ maxLength: 10 }}
									fullWidth
									value={locationDetails?.local_delivery_fee || ''}
									onChange={e =>
										e.target.value.length < 8 &&
										handleChange('local_delivery_fee', e.target.value)
									}
								/>

								{/* Suppress other rates */}
								<FormGroup>
									<FormControlLabel
										control={
											<Checkbox
												checked={
													locationDetails?.suppress_other_rates || false
												}
												onChange={e =>
													handleChange(
														'suppress_other_rates',
														e.target.checked
													)
												}
											/>
										}
										title='Suppress other rates'
										label={
											<Typography>
												<Box display='flex' alignItems='center' gap={1}>
													Suppress other rates{' '}
													<Card variant='elevation' sx={{ p: 0.5 }}>
														<Tooltip
															title='This setting only supresses rates that would otherwise be returned by this app.'
															placement='top'>
															[ ? ]
														</Tooltip>
													</Card>
												</Box>
											</Typography>
										}
									/>
								</FormGroup>
							</Box>
						</form>
					</Box>
				</Grid>
			</Grid>
		</>
	);
};

export default InstoreAndLocalDelSettings;
