/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable react/button-has-type */
import type { FormEvent } from 'react';
import { useEffect, useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate, useParams } from 'react-router-dom';

import SignUpLogo from '../../Components/Layout/SignUpLogo';
import Button from '../../Components/UI/Button/Button';
import styles from '../../Components/UI/Images/Logo/BmimLogo.module.scss';
import { acceptInvitation, fetchInvitationData } from '../../ReduxState/invites/invitesSlice';
import type { AppDispatch, RootState } from '../../ReduxState/store';
import type { UserModel } from '../../Store/User/user-context.helper';
import scss from './AcceptInvitee.module.scss';
import type { InvitedUserInterface } from '../Account/Pages/ManageUsers/Components/ManageUsersPage';
import { getInvitePermission } from '../../utils/getUserPermissions';

const AcceptInvitee = (): JSX.Element | null => {
	const params = useParams();
	const navigate = useNavigate();
	const userLoggedIn: boolean = useSelector((state: RootState) => state.login.isLoggedIn);
	const user: UserModel = useSelector((state: RootState) => state.login.user);
	const invitesList: InvitedUserInterface[] | null = useSelector(
		(state: RootState) => state.invites.invitesList
	);
	const dispatch = useDispatch<AppDispatch>();
	const activeInvite: { [key: string]: string } | null | undefined = useSelector(
		(state: RootState) => state.invites.selectedInvitee
	);
	const [isOlderThan14Days, setIsOlderThan14Days] = useState<boolean>(false);

	const acceptHandler = (event: FormEvent): void => {
		event.preventDefault();
		console.log('acceptHandler', activeInvite);
		if (activeInvite) {
			dispatch(acceptInvitation({ inviteUuid: activeInvite.invite_uuid as string }));
			// navigate('/dashboard');
			// do it with a reload
			setTimeout(() => {
				window.location.href = '/dashboard';
			}, 400);
		}
	};

	const declineHandler = () => {
		localStorage.removeItem('pendingInvitation');
		return navigate('/joinOrAddCompany');
	};

	useEffect(() => {
		const storageParams = JSON.parse(localStorage.getItem('pendingInvitation') as string);
		if (user && storageParams) {
			dispatch(fetchInvitationData({ inviteUuid: storageParams.uuid as string }));
		} else if (!userLoggedIn && storageParams) {
			navigate('/accept-invite');
		} else {
			setTimeout(() => {
				if (params && params.uuid && params.uuid !== '') {
					localStorage.setItem('pendingInvitation', JSON.stringify(params));
				}
			}, 100);
		}
	}, [userLoggedIn]);

	useEffect(() => {
		if (activeInvite) {
			// Convert the string to a Date object
			const recordDate = new Date(activeInvite.record_extended || activeInvite.record_created);

			// Get the current date
			const now = new Date();

			// Calculate the difference in milliseconds
			// @ts-ignore
			const diffMs = now - recordDate;

			// Calculate 14 days in milliseconds
			const fourteenDaysMs = 14 * 24 * 60 * 60 * 1000;

			// Check if the record is older than 14 days
			setIsOlderThan14Days(diffMs > fourteenDaysMs);
		}
	}, [activeInvite]);

	// const prevInvitesListRef = useRef<InvitedUserInterface[] | null>(invitesList);
	// useEffect(() => {
	// 	// if invitesList has changed the invitation is considered accepted
	// 	if (prevInvitesListRef.current !== undefined && invitesList !== prevInvitesListRef.current) {
	// 		// window.location.reload();
	// 		window.location.href = '/dashboard';
	// 	}
	// 	// Update the previous value ref
	// 	prevInvitesListRef.current = invitesList;
	// }, [invitesList]);

	const logoStyle = {
		margin: '35px'
	};

	if (isOlderThan14Days) {
		return (
			<div className={scss.container}>
				<header className={scss.header}>
					{/* <BmimLogo bmimClass={styles.logo} bmimLogoName="/bmim-cash-flow-logo-s.png" /> */}
					<div style={logoStyle}>
						<SignUpLogo logoClass={styles.logo} />
					</div>
				</header>
				<main className={scss.main}>
					<h3 style={{ textTransform: 'none' }}>Invitation expired</h3>
					<div>
						Please contact <b>{activeInvite?.company_name}</b> to receive new invitation.
					</div>
					<div>
						<div className={scss.nextButton}>
							<Button
								id="nextToLanding"
								link="/joinOrAddCompany"
								onClick={declineHandler}
								type="button"
								value="Proceed with login"
								whiteBtn
							/>
						</div>
					</div>
				</main>
			</div>
		);
	}

	if (activeInvite && activeInvite.accepted)
		// invitetion already accepted
		return (
			<div className={scss.container}>
				<header className={scss.header}>
					<div style={logoStyle}>
						<SignUpLogo logoClass={styles.logo} />
					</div>
				</header>
				<main className={scss.main}>
					<h3>Invite already accepted</h3>
					<p>
						You have already accepted this invite. Please click the continue button below to
						proceed.
					</p>
					<p>
						if you have any questions or concerns please contact support at{' '}
						<a href="mailto:support@bmim.co.uk">support@bmim.co.uk</a>
					</p>
					<div className={scss.nextButton}>
						<div className={scss.nextButton}>
							<Button
								id="nextToLanding"
								link="/joinOrAddCompany"
								onClick={declineHandler}
								type="submit"
								value="Continue to Dashboard"
								whiteBtn={false}
							/>
						</div>
					</div>
				</main>
			</div>
		);

	if (activeInvite && activeInvite.record_created)
		return (
			<div className={scss.container}>
				<header className={scss.header}>
					{/* <BmimLogo bmimClass={styles.logo} bmimLogoName="/bmim-cash-flow-logo-s.png" /> */}
					<div style={logoStyle}>
						<SignUpLogo logoClass={styles.logo} />
					</div>
				</header>
				<main className={scss.main}>
					<div className="h3">Accept the invite</div>
					<p>
						You have been invited as:{' '}
						<span className={scss.accent}>
							{getInvitePermission(activeInvite?.invite_permissions)}
						</span>
						<br />
						to the company: <span className={scss.accent}>{activeInvite?.company_name}</span>
					</p>
					<div className={scss.nextButton}>
						{/* <button className={scss.container__button} onClick={acceptHandler}>
						Accept invitation
					</button> */}
						{/* <button className={scss.container__button} onClick={declineHandler}>
						Skip for now
					</button> */}
						<Button
							id="chooseCompanyType"
							link="/joinOrAddCompany"
							onClick={acceptHandler}
							type="submit"
							value="Accept invitation"
							whiteBtn={false}
						/>

						<div className={scss.nextButton}>
							<Button
								id="nextToLanding"
								link="/joinOrAddCompany"
								onClick={declineHandler}
								type="button"
								value="Skip for now"
								whiteBtn
							/>
						</div>
					</div>
				</main>
			</div>
		);

	// invitetion not found or error
	return (
		<div className={scss.container}>
			<header className={scss.header}>
				<div style={logoStyle}>
					<SignUpLogo logoClass={styles.logo} />
				</div>
			</header>
			<main className={scss.main}>
				<h3>Issue with the invite</h3>
				<p>There have been issues retrieving your invitation. Please try again later.</p>
				<p>
					if the issue persists contact support at{' '}
					<a href="mailto:support@bmim.co.uk">support@bmim.co.uk</a>
				</p>
				<div className={scss.nextButton}>
					<div className={scss.nextButton}>
						<Button
							id="nextToLanding"
							link="/joinOrAddCompany"
							onClick={declineHandler}
							type="button"
							value="Skip for now"
							whiteBtn={false}
						/>
					</div>
				</div>
			</main>
		</div>
	);
};

export default AcceptInvitee;
