import {
	Box,
	Divider,
	FormControl,
	FormHelperText,
	Grid,
	InputAdornment,
	MenuItem,
	OutlinedInput,
	Select,
	Typography,
} from '@mui/material';
import { useDispatch, useSelector } from 'react-redux';
import { InstoreAndLocalDelSettings } from '../components';
import { useGetLocationAddressMutation } from '../redux/Actions/LocationActions';
import { dispatchAlert } from '../redux/Actions/ProvidersAction';
import { setAlert } from '../redux/features/providers/providersSlice';

const LocationModal = ({
	locationDetails = {},
	setLocationDetails = () => {},
	handleChange = (name, val) => {},
	errorsMsg = {},
	setErrorsMsg = () => {},
}) => {
	const admin_obj = eniture_rtsq || {};
	const [getLocationAddress, { isLoading }] = useGetLocationAddressMutation();
	const { alert } = useSelector(state => state.providers);
	const dispatch = useDispatch();

	const handleGetGoogleLocation = zip => {
		if (!zip || zip.length < 5) return;

		const payload = {
			action: 'get_location_address',
			url: admin_obj?.eniture_rtsq_rest_url,
			origin_zip: zip,
			destination_address: '',
		};

		getLocationAddress(payload)
			.unwrap()
			.then(res => {
				dispatch(setAlert({ ...alert, open: false }));

				if (res?.error) {
					setLocationDetails(prevState => ({
						...prevState,
						city: '',
						cities: [],
						state: '',
						country: '',
					}));
					setTimeout(
						() => dispatch(setAlert(dispatchAlert(true, res?.message, 'error'))),
						100
					);

					return;
				}

				const cities = res?.data?.city;
				setLocationDetails(prevState => ({
					...prevState,
					city: cities[0],
					cities,
					state: res?.data?.state,
					country: res?.data?.country,
				}));
			})
			.catch(err => console.log('getLocationAddress error', err));
	};

	return (
		<form noValidate autoComplete='off'>
			<Grid container spacing={1} flex mt={3} mb={3}>
				<Grid item flex={1} xs={4}>
					<Typography variant='subtitle1' fontWeight='bold'>
						{locationDetails?.type == 1 ? 'Warehouse' : 'Drop ship'}
					</Typography>
					<p>WooCommerce and your customers will use this information to contact you.</p>
				</Grid>
				<Grid item flex={2} xs={8}>
					<Box component='form'>
						<Box
							component='div'
							sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
							<InputField
								label='Nickname'
								value={locationDetails?.nickname || ''}
								onChange={handleChange}
								required={false}
							/>
							<InputField
								label='Address'
								value={locationDetails?.address || ''}
								onChange={handleChange}
								required={false}
							/>
							<InputField
								label='Apartment'
								value={locationDetails?.apartment || ''}
								onChange={handleChange}
								required={false}
							/>
							<InputField
								label='Postal Code'
								name='zip'
								maxLength={10}
								value={locationDetails?.zip || ''}
								onChange={(name, val) => {
									if (val.length) setErrorsMsg(prev => ({ ...prev, zip: '' }));

									handleChange(name, val);
									handleGetGoogleLocation(val);
								}}
								disabled={isLoading}
								error={errorsMsg?.zip?.length}
								helperText={errorsMsg?.zip || ''}
							/>

							{locationDetails?.cities?.length > 1 ? (
								<FormControl>
									<label htmlFor='city' title='City' className='city-list-label'>
										City *
									</label>
									<Select
										id='city'
										title='City'
										displayEmpty
										size='small'
										InputLabelProps={{ shrink: true }}
										inputProps={{ style: { padding: '5px 10px' } }}
										fullWidth
										required
										disabled={isLoading}
										value={locationDetails?.city}
										onChange={e => handleChange('city', e.target.value)}>
										{locationDetails?.cities?.map((city, index) => (
											<MenuItem key={index} value={city}>
												{city}
											</MenuItem>
										))}
									</Select>
								</FormControl>
							) : (
								<InputField
									label='City'
									maxLength={30}
									value={locationDetails?.city || ''}
									onChange={(name, val) => {
										if (val.match(/^[a-zA-Z\s]*$/i)) {
											setErrorsMsg(prev => ({ ...prev, city: '' }));
											handleChange(name, val);
										}
									}}
									disabled={isLoading}
									error={errorsMsg?.city?.length}
									helperText={errorsMsg?.city || ''}
								/>
							)}

							<InputField
								label='State'
								maxLength={2}
								value={locationDetails?.state || ''}
								onChange={(name, val) => {
									if (val.match(/^[a-zA-Z\s]*$/i)) {
										setErrorsMsg(prev => ({ ...prev, state: '' }));
										handleChange(name, val.toUpperCase());
									}
								}}
								disabled={isLoading}
								error={errorsMsg?.state?.length}
								helperText={errorsMsg?.state || ''}
							/>
							<InputField
								label='Country'
								maxLength={2}
								value={locationDetails?.country || ''}
								onChange={(name, val) => {
									if (val.match(/^[a-zA-Z\s]*$/i)) {
										setErrorsMsg(prev => ({ ...prev, country: '' }));
										handleChange(name, val.toUpperCase());
									}
								}}
								disabled={isLoading}
								error={errorsMsg?.country?.length}
								helperText={errorsMsg?.country || ''}
							/>

							{/* Handling fee / markup */}
							<InputField
								label='Handling fee / markup'
								value={locationDetails?.origin_markup || ''}
								maxLength={7}
								name='origin_markup'
								onChange={(name, val) =>
									val.match(/^-?[0-9.]*%?$/) && handleChange(name, val)
								}
								required={false}
								helperText='Enter an amount (e.g. 5.00) or a percentage (e.g. 5.0%).'
								endAdornment={false}
							/>
						</Box>
					</Box>
				</Grid>
			</Grid>

			<Divider variant='fullWidth' />

			<InstoreAndLocalDelSettings
				locationDetails={locationDetails}
				setLocationDetails={setLocationDetails}
				handleChange={handleChange}
			/>
		</form>
	);
};

export const InputField = ({
	label,
	value,
	maxLength = 50,
	name = '',
	required = true,
	onChange = (name, val) => {},
	...props
}) => {
	return (
		<FormControl>
			<FormHelperText>
				{label}
				<span
					style={{
						color: 'red',
						fontSize: '14px',
						display: 'inline-block',
						marginLeft: '5px',
					}}>
					{required ? '*' : ''}
				</span>
			</FormHelperText>
			<OutlinedInput
				fullWidth
				size='small'
				required={required}
				title={label}
				value={value || ''}
				onChange={e => onChange(name || label?.toLowerCase(), e.target.value)}
				endAdornment={
					<InputAdornment position='end'>{`${(value || '').length}/${maxLength}`}</InputAdornment>
				}
				aria-describedby='outlined-weight-helper-text'
				inputProps={{ 'aria-label': 'weight', maxLength }}
				{...props}
			/>

			{(props?.error || name === 'origin_markup') && (
				<FormHelperText sx={{ color: name !== 'origin_markup' && 'red' }}>
					{props?.helperText || ''}
				</FormHelperText>
			)}
		</FormControl>
	);
};

export default LocationModal;
