import { useRef, useState } from 'react';
import {
	Box,
	Checkbox,
	FormControl,
	FormControlLabel,
	FormHelperText,
	MenuItem,
	Radio,
	RadioGroup,
	Select,
	TextField,
	Typography,
} from '@mui/material';
import { InputField } from '../../../LocationModal';

const DELIVERY_ORDER = ['EMAIL', 'SMS', 'CALL'];
const DELIVERY_LABELS = { EMAIL: 'Email', SMS: 'SMS', CALL: 'Voice call' };

/**
 * FedEx requires the agreement to be readable in full before it can be accepted, so the checkbox
 * stays disabled until the reader reaches the end of the document.
 */
export const EulaStep = ({ eulaUrl, accepted, onAccept }) => {
	const [reachedEnd, setReachedEnd] = useState(false);
	const frame = useRef(null);

	return (
		<Box>
			<Typography variant='body2' mb={1}>
				Read the FedEx End User License Agreement (EULA) and click the checkbox, &quot;I have read and agree to the FedEx End User License Agreement&quot;.
			</Typography>
			<Box
				ref={frame}
				onScroll={e => {
					const { scrollTop, scrollHeight, clientHeight } = e.currentTarget;
					if (!reachedEnd && scrollTop + clientHeight >= scrollHeight - 60) setReachedEnd(true);
				}}
				sx={{ height: 320, overflowY: 'auto', border: '1px solid #ccc', borderRadius: 1, mb: 2 }}>
				<embed src={`${eulaUrl}#toolbar=0&navpanes=0`} type='application/pdf' style={{ width: '100%', height: 6000 }} />
			</Box>

			<FormControlLabel
				control={
					<Checkbox checked={accepted} disabled={!reachedEnd} onChange={e => onAccept(e.target.checked)} />
				}
				label='I have read and agree to the FedEx End User License Agreement. I confirm that I am authorized to accept this agreement on behalf of myself or the legal entity I represent.'
			/>
		</Box>
	);
};

/**
 * The account and the address FedEx holds for it. Everything here is checked against FedEx's own
 * record, so it has to match their billing address exactly.
 */
export const AccountStep = ({ state, errors, onChange, countries = [] }) => (
	<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
		<InputField
			label='Nickname'
			maxLength={50}
			value={state.nickname}
			onChange={(_, v) => onChange('nickname', v)}
			required={true}
			error={!!errors.nickname}
			helperText={errors.nickname || ''}
		/>
		<InputField
			label='FedEx Account Number'
			maxLength={50}
			value={state.account_number}
			onChange={(_, v) => onChange('account_number', v)}
			required={true}
			error={!!errors.account_number}
			helperText={errors.account_number || ''}
		/>
		<InputField
			label='Customer Name'
			maxLength={100}
			value={state.customer_name}
			onChange={(_, v) => onChange('customer_name', v)}
			required={true}
			error={!!errors.customer_name}
			helperText={errors.customer_name || ''}
		/>

		<FormControl fullWidth>
			<FormHelperText sx={{ ml: 0 }}>Residential Address?</FormHelperText>
			<Select
				size='small'
				value={state.residential_address ? 'yes' : 'no'}
				onChange={e => onChange('residential_address', e.target.value === 'yes')}>
				<MenuItem value='no'>No</MenuItem>
				<MenuItem value='yes'>Yes</MenuItem>
			</Select>
		</FormControl>

		<InputField
			label='Street Line 1'
			maxLength={100}
			value={state.address}
			onChange={(_, v) => onChange('address', v)}
			required={true}
			error={!!errors.address}
			helperText={errors.address || ''}
		/>
		<InputField
			label='Street Line 2'
			maxLength={100}
			value={state.address_2}
			onChange={(_, v) => onChange('address_2', v)}
			required={false}
		/>
		<InputField
			label='City'
			maxLength={50}
			value={state.city}
			onChange={(_, v) => onChange('city', v)}
			required={true}
			error={!!errors.city}
			helperText={errors.city || ''}
		/>

		<InputField
			label='State'
			maxLength={2}
			value={state.state}
			onChange={(_, v) => {
				if (v.match(/^[a-zA-Z]*$/)) onChange('state', v.toUpperCase());
			}}
			required={true}
			error={!!errors.state}
			helperText={errors.state || 'Enter the standard two-character abbreviation'}
		/>

		<InputField
			label='Postal Code'
			maxLength={15}
			value={state.zip}
			onChange={(_, v) => onChange('zip', v)}
			required={true}
			error={!!errors.zip}
			helperText={errors.zip || ''}
		/>

		<FormControl fullWidth>
			<FormHelperText sx={{ ml: 0 }}>Country *</FormHelperText>
			<Select
				size='small'
				value={state.country || 'US'}
				onChange={e => {
					onChange('country', e.target.value);
					onChange('state', '');
				}}>
				{['US', 'CA', 'MX'].map(code => (
					<MenuItem key={code} value={code}>
						{countries.find(c => c.code === code)?.name || code}
					</MenuItem>
				))}
			</Select>
		</FormControl>
	</Box>
);

/**
 * FedEx says which proofs this account can use, so only those are offered.
 */
export const VerificationChoiceStep = ({ state, options, onChange }) => {
	const canInvoice = !!options?.invoice;
	const canCode = (options?.secureCode || []).length > 0;

	return (
		<Box>
			<Typography variant='subtitle1' fontWeight='bold' mb={1}>
				Choose how to confirm your identity
			</Typography>
			<RadioGroup
				value={state.validation_type || (canCode ? 'code' : 'invoice')}
				onChange={e => onChange('validation_type', e.target.value)}>
				{canCode && (
					<FormControlLabel value='code' control={<Radio />} label='Security code validation' />
				)}
				{canInvoice && (
					<FormControlLabel value='invoice' control={<Radio />} label='Invoice validation' />
				)}
			</RadioGroup>
			{!canCode && !canInvoice && (
				<Typography variant='body2' color='error'>
					FedEx did not offer a verification method for this account.
				</Typography>
			)}
		</Box>
	);
};

/**
 * Either where to send the security code, or the invoice being used as proof.
 */
export const ProofStep = ({ state, errors, options, phoneNumber, onChange }) => {
	if (state.validation_type === 'invoice') {
		return (
			<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
				<Typography variant='subtitle1' fontWeight='bold'>
					Invoice validation
				</Typography>
				<InputField
					label='Invoice number'
					maxLength={50}
					value={state.invoice_number}
					onChange={(_, v) => onChange('invoice_number', v)}
					required={true}
					error={!!errors.invoice_number}
					helperText={errors.invoice_number || ''}
				/>
				<TextField
					label='Invoice date'
					size='small'
					placeholder='YYYY-MM-DD'
					InputLabelProps={{ shrink: true }}
					value={state.invoice_date || ''}
					onChange={e => onChange('invoice_date', e.target.value)}
					error={!!errors.invoice_date}
					helperText={errors.invoice_date || 'Format YYYY-MM-DD'}
				/>
				<InputField
					label='Invoice amount'
					maxLength={20}
					value={state.invoice_amount}
					onChange={(_, v) => onChange('invoice_amount', v)}
					required={true}
					error={!!errors.invoice_amount}
					helperText={errors.invoice_amount || ''}
				/>
				<FormControl fullWidth>
					<FormHelperText sx={{ ml: 0 }}>Currency</FormHelperText>
					<Select
						size='small'
						value={state.invoice_currency || 'USD'}
						onChange={e => onChange('invoice_currency', e.target.value)}>
						{['USD', 'CAD', 'MXN'].map(c => (
							<MenuItem key={c} value={c}>
								{c}
							</MenuItem>
						))}
					</Select>
				</FormControl>
			</Box>
		);
	}

	const choices = [...(options?.secureCode || [])].sort(
		(a, b) => DELIVERY_ORDER.indexOf(a) - DELIVERY_ORDER.indexOf(b)
	);

	return (
		<Box>
			<Typography variant='subtitle1' fontWeight='bold' mb={1}>
				Where should FedEx send the security code?
			</Typography>
			<RadioGroup
				value={state.pin_option || choices[0] || ''}
				onChange={e => onChange('pin_option', e.target.value)}>
				{choices.map(opt => (
					<FormControlLabel
						key={opt}
						value={opt}
						control={<Radio />}
						label={
							(opt === 'SMS' || opt === 'CALL') && phoneNumber
								? `${DELIVERY_LABELS[opt] || opt} — ${phoneNumber}`
								: DELIVERY_LABELS[opt] || opt
						}
					/>
				))}
			</RadioGroup>
		</Box>
	);
};

export const SecureCodeStep = ({ state, errors, onChange }) => (
	<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
		<Typography variant='subtitle1' fontWeight='bold'>
			Enter the security code
		</Typography>
		<Typography variant='body2' color='text.secondary'>
			FedEx has sent a six digit code. Enter it below to finish connecting the account.
		</Typography>
		<InputField
			label='6 digit secure code'
			maxLength={6}
			value={state.secure_pin}
			onChange={(_, v) => onChange('secure_pin', v.replace(/\D/g, ''))}
			required={true}
			error={!!errors.secure_pin}
			helperText={errors.secure_pin || ''}
		/>
	</Box>
);

export const CompleteStep = ({ accountNumber }) => (
	<Box textAlign='center' py={4}>
		<Typography variant='h6' fontWeight='bold' gutterBottom>
			FedEx account connected
		</Typography>
		<Typography variant='body2' color='text.secondary'>
			Account {accountNumber} is registered and ready to quote. Set the services you want to
			offer in Quote settings.
		</Typography>
	</Box>
);
