import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import InfoIcon from '@mui/icons-material/Info';
import {
	Box,
	Button,
	Card,
	FormControl,
	FormHelperText,
	OutlinedInput,
	Typography,
} from '@mui/material';
import { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { Spinner } from '../../index';
import ConnectionSettingsButtons from '../../ConnectionSettingsButtons';
import { useGetCountriesStatesQuery } from '../../../redux/Actions/WooCommerceDataAction';
import RegistrationWizard from './Wizard/RegistrationWizard';

const initialState = {
	nickname: '',
	api_type: 'integrator',
	client_id: '',
	client_secret: '',
	account_number: '',
};

/**
 * One line of the registered account's details. These are a record of what FedEx holds, not
 * something the merchant edits here, so they carry no character counter and no validation.
 */
const ReadOnlyField = ({ label, value }) => (
	<FormControl fullWidth>
		<FormHelperText sx={{ ml: 0 }}>{label}</FormHelperText>
		<OutlinedInput size='small' value={value || ''} title={label} disabled readOnly />
	</FormControl>
);

const ConnectionSettings = ({
	connSettings,
	setConnSettings,
	isLoading,
	setErrorsMsg,
	setOwnsFooter,
}) => {
	const admin_obj = eniture_rtsq || {};
	const { eniture_api_key_status } = useSelector(state => state.plan);
	const { modal } = useSelector(state => state.providers);
	const { data: countriesData } = useGetCountriesStatesQuery({ url: admin_obj?.eniture_rtsq_rest_url });
	const [reconnecting, setReconnecting] = useState(false);
	const [saved, setSaved] = useState(null);
	const isEdit = modal?.data?.action === 'edit';

	const wasRegistered = saved?.api_type === 'integrator' && !!saved?.client_id;
	const alreadyRegistered = wasRegistered && !reconnecting;
	const countryName =
		(countriesData?.data || []).find(c => c.code === connSettings?.country)?.name ||
		connSettings?.country;

	useEffect(() => {
		if (setOwnsFooter) setOwnsFooter(true);
	}, [setOwnsFooter]);

	// An existing connection arrives asynchronously, so the snapshot has to wait for it. Taking it
	// on mount would read the empty object the modal starts with and mistake a registered account
	// for a new one.
	useEffect(() => {
		if (saved) return;
		if (isEdit && Object.keys(connSettings || {}).length === 0) return;

		const merged = { ...initialState, ...connSettings };
		setSaved(merged);
		setConnSettings({ ...merged, api_type: 'integrator' });
	}, [connSettings, saved, isEdit, setConnSettings]);

	if (isLoading) return <Spinner />;

	return (
		<>
			<Box my={2}>
				<Card
					variant='elevation'
					title='FedEx 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 account to use this application.
						If you do not have one, contact FedEx at 800-463-3339 or{' '}
						<a
							href='https://www.fedex.com/en-us/create-account.html'
							target='_blank'
							rel='noopener noreferrer'
							style={{ textDecoration: 'none' }}>
							register online
						</a>
						.
					</Typography>
				</Card>
			</Box>

			<Box my={2}>
				<Card
					variant='elevation'
					title='FedEx service marks'
					sx={{ p: 1, display: 'flex', justifyContent: 'space-between', gap: 2 }}>
					<InfoIcon />
					<Typography variant='subtitle2' sx={{ flexGrow: 1, textWrap: 'wrap !important' }}>
						FedEx service marks are owned by Federal Express Corporation and are used by
						permission.
					</Typography>
				</Card>
			</Box>

			<Box my={3} width={100}>
				<Card variant=''>
					<img
						src={`${admin_obj?.eniture_rtsq_url}/build/assets/fedex.png`}
						alt='provider icon'
						title='FedEx'
						style={{ width: '100px', 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'>
					<Box component='div' sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
						{alreadyRegistered && (
							<>
								<Box
									sx={{
										border: 1,
										borderColor: 'success.main',
										borderRadius: 1,
										overflow: 'hidden',
									}}>
									<Box
										sx={{
											bgcolor: 'success.main',
											color: 'common.white',
											px: 2,
											py: 1,
											display: 'flex',
											alignItems: 'center',
											gap: 1,
										}}>
										<CheckCircleIcon fontSize='small' />
										<Typography variant='subtitle2' fontWeight='bold'>
											FedEx Account Connected Successfully
										</Typography>
									</Box>
									<Typography variant='body2' sx={{ px: 2, py: 1.5 }}>
										Your FedEx account credentials have been verified and saved.
									</Typography>
								</Box>

								<ReadOnlyField
									label='FedEx Account Number'
									value={connSettings.account_number}
								/>

								<Box sx={{ display: 'flex', gap: 2 }}>
									<ReadOnlyField
										label='Address'
										value={[connSettings.address, connSettings.address_2]
											.filter(Boolean)
											.join(', ')}
									/>
									<ReadOnlyField label='City' value={connSettings.city} />
								</Box>

								<Box sx={{ display: 'flex', gap: 2 }}>
									<ReadOnlyField
										label='State/Province'
										value={connSettings.state}
									/>
									<ReadOnlyField
										label='ZIP/Postal Code'
										value={connSettings.zip}
									/>
								</Box>

								<ReadOnlyField label='Country' value={countryName} />

								<Box
									sx={{
										display: 'flex',
										gap: 2,
										justifyContent: 'flex-end',
										mt: 1,
									}}>
									<ConnectionSettingsButtons
										connectionSettings={connSettings}
										isLoading={isLoading}
										setErrorsMsg={setErrorsMsg}
										showSave={false}
									/>
									<Button
										variant='contained'
										title='Reconnect Account'
										sx={{ textTransform: 'capitalize' }}
										onClick={() => setReconnecting(true)}>
										Reconnect Account
									</Button>
								</Box>
							</>
						)}

						{!alreadyRegistered && (
							<RegistrationWizard
								connSettings={connSettings}
								setConnSettings={setConnSettings}
								isReconnect={reconnecting}
							/>
						)}

					</Box>
				</form>
			</Box>
		</>
	);
};

export default ConnectionSettings;
