import InfoIcon from '@mui/icons-material/Info';
import {
	Box,
	Card,
	FormControl,
	FormControlLabel,
	FormHelperText,
	Link,
	MenuItem,
	Radio,
	RadioGroup,
	Select,
	Typography,
} from '@mui/material';
import { useEffect } from 'react';
import { useSelector } from 'react-redux';
import { Spinner } from '../../index';
import { InputField } from '../../LocationModal';

const initialState = {
	nickname: '',
	account_type: 'ltl_freight',
	shipper_account_number: '',
	third_party_account_number: '',
	account_name: '',
	address: '',
	city: '',
	state: '',
	zip_code: '',
	country: '',
	test_account_number: 'shipper',
};

/**
 * Name, label, length limit, placeholder and whether the field is required, in screen order.
 */
const ACCOUNT_FIELDS = [
	['shipper_account_number', 'FedEx Freight Account Number', 50, 'e.g. 209033858', true],
	['third_party_account_number', 'Third-party FedEx Freight Account Number', 50, 'e.g. 987654321', false],
	['account_name', 'Account name', 100, 'e.g. ABC Logistics LLC', false],
];

const ADDRESS_ROWS = [
	[
		['city', 'City', 100, 'City e.g. Memphis'],
		['state', 'State/Province', 2, 'State/Province e.g. TN'],
	],
	[
		['zip_code', 'ZIP/Postal code', 50, 'ZIP/Postal code e.g. 38116'],
		['country', 'Country', 2, 'Country e.g. US'],
	],
];

const ConnectionSettings = ({ connSettings, setConnSettings, isLoading, errorsMsg }) => {
	const admin_obj = eniture_rtsq || {};
	const { eniture_api_key_status } = useSelector(state => state.plan);

	useEffect(() => {
		setConnSettings(prevState => ({
			...initialState,
			...prevState,
		}));
	}, []);

	if (isLoading) return <Spinner />;

	const set = (name, val) => setConnSettings(prev => ({ ...prev, [name]: val }));
	const isDirect = connSettings.account_type === 'freight_direct';

	const field = ([name, label, maxLength, placeholder, required = false]) => (
		<InputField
			key={name}
			name={name}
			label={label}
			maxLength={maxLength}
			value={connSettings[name]}
			onChange={(_, val) => set(name, val)}
			required={required}
			placeholder={placeholder}
			autoComplete='off'
			inputProps={{
				id: `eniture-rtsq-fedex-freight-${name}`,
				'aria-label': label,
				maxLength,
				spellCheck: false,
			}}
			error={Boolean(errorsMsg?.[name])}
			helperText={errorsMsg?.[name] || ''}
		/>
	);

	return (
		<>
			<Box my={2} sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
				<Card
					variant='elevation'
					title='FedEx Freight account note'
					sx={{ p: 1, display: 'flex', justifyContent: 'space-between', gap: 2 }}>
					<InfoIcon />
					<Typography variant='subtitle2' sx={{ flexGrow: 1, textWrap: 'wrap !important' }}>
						<strong>Note!</strong> You must have a FedEx Freight account to use this
						application. If you don’t have one, contact FedEx Freight at 866-393-4585 or{' '}
						<a
							href='https://fedexfreight.com/en-us/rate-ship/open-account'
							target='_blank'
							rel='noreferrer'
							style={{ textDecoration: 'none' }}>
							register online
						</a>
						.
					</Typography>
				</Card>
				<Card
					variant='elevation'
					title='FedEx Freight service marks'
					sx={{ p: 1, display: 'flex', justifyContent: 'space-between', gap: 2 }}>
					<InfoIcon />
					<Typography variant='subtitle2' sx={{ flexGrow: 1, textWrap: 'wrap !important' }}>
						FedEx Freight service marks are owned by FedEx Freight Holding Company, Inc. and
						are used by permission.
					</Typography>
				</Card>
			</Box>

			<Box my={3} width={100}>
				<Card variant=''>
					<img
						src={`${admin_obj?.eniture_rtsq_url}/build/assets/carrier_logos/fedex-freight.png`}
						alt='provider icon'
						title='FedEx Freight'
						style={{ width: '90px', objectFit: 'contain' }}
					/>
				</Card>
			</Box>

			<Box component='form'>
				{eniture_api_key_status === 'error' && (
					<Typography
						color='error'
						variant='subtitle2'
						title='Invalid Eniture API Key'
						sx={{ textWrap: 'wrap !important' }}
						mb={2}>
						<strong>Note!</strong> Your Eniture API Key is missing or invalid. Kindly
						update your API Key in the Eniture API Connection tab.
					</Typography>
				)}

				<form autoComplete='off' onSubmit={e => e.preventDefault()}>
					<Box component='div' sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
						{field(['nickname', 'Nickname', 50, '', true])}

						<FormControl size='small'>
							<FormHelperText id='eniture-rtsq-fedex-freight-account-type-label'>
								Account type
							</FormHelperText>
							<Select
								labelId='eniture-rtsq-fedex-freight-account-type-label'
								id='eniture-rtsq-fedex-freight-account-type'
								name='account_type'
								inputProps={{ 'aria-label': 'Account type' }}
								value={isDirect ? 'freight_direct' : 'ltl_freight'}
								onChange={e => set('account_type', e.target.value)}>
								<MenuItem value='ltl_freight'>LTL Freight</MenuItem>
								<MenuItem value='freight_direct'>Freight Direct</MenuItem>
							</Select>
						</FormControl>

						{ACCOUNT_FIELDS.map(field)}

						{field(['address', 'Address', 255, 'Street Address e.g. 123 Main St, Suite 200', true])}

						{ADDRESS_ROWS.map((row, i) => (
							<Box key={i} sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 2 }}>
								{row.map(field)}
							</Box>
						))}

						{isDirect && (
							<Typography variant='body2'>
								<Link
									href='https://www.fedexfreight.com/en-us/services/freight-direct'
									target='_blank'
									rel='noreferrer'>
									What is Freight Direct?
								</Link>
							</Typography>
						)}

						<FormControl>
							<RadioGroup
								row
								aria-label='Which account number Test Connection checks'
								name='eniture_rtsq_fedex_freight_test_account_number'
								value={connSettings.test_account_number === 'third_party' ? 'third_party' : 'shipper'}
								onChange={e => set('test_account_number', e.target.value)}>
								<FormControlLabel
									value='shipper'
									control={<Radio />}
									label='Test FedEx Freight Account Number'
								/>
								<FormControlLabel
									value='third_party'
									control={<Radio />}
									label='Test Third-party FedEx Freight Account Number'
								/>
							</RadioGroup>
							{errorsMsg?.third_party_account_number && (
								<FormHelperText sx={{ color: 'red' }}>
									{errorsMsg.third_party_account_number}
								</FormHelperText>
							)}
						</FormControl>
					</Box>
				</form>
			</Box>
		</>
	);
};

export default ConnectionSettings;
