import { Alert, Box, FormControl, FormControlLabel, FormLabel, MenuItem, Radio, RadioGroup, TextField, Typography } from '@mui/material';
import { useEffect } from 'react';
import { useSelector } from 'react-redux';
import { Spinner } from '../../index';
import { InputField } from '../../LocationModal';

const initialState = {
	nickname: '', client_id: '', client_secret: '', username: '', password: '',
	payment_type: 'shipper', payer_zip: '', payer_country_code: 'US', dim_weight_base_account: false,
};

const ConnectionSettings = ({ connSettings, setConnSettings, isLoading, errorsMsg }) => {
	const { eniture_api_key_status } = useSelector(state => state.plan);
	useEffect(() => { setConnSettings(prev => ({ ...initialState, ...prev })); }, []);
	if (isLoading) return <Spinner />;
	const update = (name, value) => setConnSettings(prev => ({ ...prev, [name]: value }));
	// Retain the existing boolean setting, including values saved as 0/1 by older clients.
	const dimensionsBased = [true, 1, '1', 'true'].includes(connSettings.dim_weight_base_account);
	return (
		<Box component='form' id='rtsq-tforce-connection' autoComplete='off' onSubmit={event => event.preventDefault()} display='flex' flexDirection='column' gap={2} my={2}>
			<Alert severity='info'>
				<strong>Note!</strong> You must have an LTL freight enabled TForce account to use this application. If you do not have one, call 800-333-7400, or{' '}
				<a href='https://www.tforcefreight.com/ltl/apps/home/' target='_blank' rel='noopener noreferrer'>register</a> online.
			</Alert>
			<img src={`${eniture_rtsq?.eniture_rtsq_url}/build/assets/carrier_logos/tforce.png`} alt='TForce Freight' style={{ width: 80, objectFit: 'contain' }} />
			<Typography variant='body2'>Client ID and client secret are required. Enter a username and password if your account requires them.</Typography>
			{eniture_api_key_status === 'error' && <Typography color='error'>Update your Eniture API Key in the Eniture API Connection tab.</Typography>}
			{[
				['nickname', 'Nickname'], ['client_id', 'Client ID'], ['client_secret', 'Client secret'],
				['username', 'Username'], ['password', 'Password'],
			].map(([name, label]) => (
				<InputField key={name} name={name} label={label}
					value={connSettings[name]} onChange={update} required={!['username', 'password'].includes(name)} maxLength={name === 'nickname' ? 50 : 100}
					type={['client_secret', 'password'].includes(name) ? 'password' : 'text'}
					autoComplete={['client_secret', 'password'].includes(name) ? 'new-password' : 'off'}
					inputProps={{ id: `rtsq-tforce-${name}`, name: `rtsq_tforce_${name}`, 'aria-label': label,
						maxLength: name === 'nickname' ? 50 : 100, autoCapitalize: 'none', spellCheck: false }}
					error={Boolean(errorsMsg?.[name])} helperText={errorsMsg?.[name] || ''} />
			))}
			<FormControl fullWidth>
			<FormLabel id='tforce-relationship-label' sx={{ mb: 0.5 }}>Relationship to shipper</FormLabel>
			<TextField select SelectProps={{ inputProps: { 'aria-labelledby': 'tforce-relationship-label' } }}
				helperText='Select how you identify yourself when getting quotes on tforcefreight.com.'
				value={connSettings.payment_type || 'shipper'} onChange={e => update('payment_type', e.target.value)}>
				<MenuItem value='shipper'>Shipper</MenuItem><MenuItem value='thirdparty'>Third party</MenuItem>
			</TextField>
			</FormControl>
			{connSettings.payment_type === 'thirdparty' && <>
				<TextField select label='Third party country or territory' value={connSettings.payer_country_code || 'US'} onChange={e => update('payer_country_code', e.target.value)}>
					{[['US', 'United States'], ['CA', 'Canada'], ['GU', 'Guam'], ['MX', 'Mexico'], ['PR', 'Puerto Rico'], ['VI', 'US Virgin Islands']].map(([code, label]) => <MenuItem key={code} value={code}>{label}</MenuItem>)}
				</TextField>
				<InputField name='payer_zip' label='Third party postal code' value={connSettings.payer_zip} onChange={update} maxLength={10} error={Boolean(errorsMsg?.payer_zip)} helperText={errorsMsg?.payer_zip || 'For the United States, enter the five digit ZIP code.'} />
			</>}
			<FormControl>
				<FormLabel id='tforce-rating-basis'>TForce rates my freight based on weight and:</FormLabel>
				<RadioGroup aria-labelledby='tforce-rating-basis' name='rtsq_tforce_rating_basis'
					value={dimensionsBased ? 'dimensions' : 'freight_class'} onChange={e => update('dim_weight_base_account', e.target.value === 'dimensions')}>
					<FormControlLabel value='freight_class' control={<Radio />} label='Freight class' />
					<FormControlLabel value='dimensions' control={<Radio />} label='Dimensions' />
				</RadioGroup>
			</FormControl>
		</Box>
	);
};
export default ConnectionSettings;
