import { useEffect, useState } from 'react';
import { Box, Button, Card, Stack, TextField, Typography } from '@mui/material';
import { useDispatch } from 'react-redux';
import { setAlert } from '../redux/features/providers/providersSlice';
import { dispatchAlert } from '../redux/Actions/ProvidersAction';
import { useGenerateSupportPinMutation, useGetSupportPinQuery } from '../redux/Actions/SupportAction';

/**
 * The panel the PIN sits in. Kept to the surrounding card's 4px radius and given the same
 * hairline the plugin's outlined controls use, so it reads as part of the page rather than
 * as a card borrowed from somewhere else.
 */
const pinPanel = { p: 2, mt: 2, bgcolor: '#f6f7f7', borderColor: '#e0e0e0' };

/**
 * A PIN is nineteen characters, so the field is sized for its contents instead of stretching
 * the width of the card.
 */
const pinField = { maxWidth: 320 };

const Support = () => {
	const admin_obj = eniture_rtsq || {};
	const rest_url = admin_obj?.eniture_rtsq_rest_url;
	const dispatch = useDispatch();
	const [copied, setCopied] = useState(false);

	const { data: stored, isLoading } = useGetSupportPinQuery(rest_url);
	const [generateSupportPin, { isLoading: isGenerating }] = useGenerateSupportPinMutation();

	const pin = stored?.data?.pin || '';
	const expiry = stored?.data?.expiry || '';
	const expired = Boolean(stored?.data?.expired);

	useEffect(() => {
		setCopied(false);
	}, [pin]);

	const generate = async () => {
		try {
			const resp = await generateSupportPin(rest_url).unwrap();

			if (resp?.error) {
				dispatch(setAlert(dispatchAlert(true, resp?.message, 'error')));
			}
		} catch (error) {
			dispatch(
				setAlert(dispatchAlert(true, 'Unable to generate a Support PIN. Please try again.', 'error'))
			);
		}
	};

	const copyPin = async () => {
		try {
			await navigator.clipboard.writeText(pin);
			setCopied(true);
		} catch (error) {
			const field = document.getElementById('en-rtsq-support-pin');

			if (field) {
				field.select();
				field.setSelectionRange(0, 99999);
				document.execCommand('copy');
				setCopied(true);
				return;
			}

			dispatch(
				setAlert(dispatchAlert(true, 'Unable to copy the Support PIN. Please copy it manually.', 'error'))
			);
		}
	};

	return (
		<>
			<Typography variant='h6' fontWeight='bold' mb={2}>
				Support
			</Typography>

			<Card variant='elevation' sx={{ p: 2 }} component='div'>
				<Typography variant='body1' fontWeight='bold'>
					Chat Support
				</Typography>

				<Typography variant='body2' mt={1}>
					Generate a Support PIN to share in Eniture Technology's chatbot for
					authentication purposes. The chatbot will inform you when it is required.
				</Typography>

				<Typography variant='body2' color='textSecondary' mt={1}>
					Generating a new Support PIN invalidates the previous one.
				</Typography>

				<Box mt={2}>
					<Button
						variant='contained'
						sx={{ textTransform: 'none' }}
						onClick={generate}
						disabled={isGenerating}>
						{isGenerating ? 'Generating…' : 'Generate a new Support PIN'}
					</Button>
				</Box>

				{isLoading || !pin ? null : (
					<Card variant='outlined' sx={pinPanel}>
						<Typography variant='body2' fontWeight='bold' mb={1}>
							Your Support PIN
						</Typography>

						<TextField
							id='en-rtsq-support-pin'
							value={pin}
							fullWidth
							sx={pinField}
							inputProps={{ readOnly: true, onFocus: e => e.target.select() }}
						/>

						<Box mt={2}>
							<Button
								variant='outlined'
								sx={{ textTransform: 'none' }}
								onClick={copyPin}>
								{copied ? 'Copied' : 'Copy Support PIN'}
							</Button>
						</Box>

						<Typography
							variant='body2'
							color={expired ? 'error' : 'textSecondary'}
							mt={2}>
							{expired ? 'Expired on: ' : 'Expires: '}
							{expiry}
						</Typography>
					</Card>
				)}
			</Card>
		</>
	);
};

export default Support;
