/* eslint-disable react/jsx-no-bind */
import type React from 'react';
import { useEffect } from 'react';
import type { FormEvent } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';

import HeaderNoSidebar from '../../Components/Layout/HeaderNoSidebar/HeaderNoSidebar';
import Button from '../../Components/UI/Button/Button';
import environment from '../../Environments/environment';
import { selectCompany } from '../../ReduxState/companies/companiesSlice';
import { fetchFinancialsData } from '../../ReduxState/financials/financialsSlice';
import type { AppDispatch, RootState } from '../../ReduxState/store';
import type { CompanyDbModel } from '../Companies/Components/CompaniesComponents.helper';
import ListOfCompanies from '../Financials/Components/UI/SelectCompany';
import scss from '../Financials/Financials.module.scss';
import styles from './JoinAddCompany.module.scss';
import DeleteAccount from '../Account/Components/DeleteAccount/DeleteAccount';
import type { UserModel } from '../../Store/User/user-context.helper';
import { logout } from '../../ReduxState/login/loginSlice';

const JoinAddCompany: React.FC = (): JSX.Element => {
	const { chooseCompanyType, dashboard, acceptInvitation, manageSubscription } =
		environment.frontendRoutes;
	const awsRedirectUrl =
		process.env.NODE_ENV === 'development'
			? 'http://localhost:8000/auth/signout'
			: 'https://bmim.bitsia.com/auth/signout';

	const linkCognitoSignOut = `https://auth.bmim.co.uk/logout?client_id=68omvr2qnart0t6hf8lpi9b86v&response_type=code&logout_uri=${awsRedirectUrl}`;
	const navigate = useNavigate();
	const className = {
		container: scss.selectCompaniesContainer2,
		box: scss.selectCompaniesBox
	};

	// TODO: check if this was a call initiate by an invite - if yes send them to acceptInvitationWithParam
	useEffect(() => {
		const isAdvisory = JSON.parse(localStorage.getItem('pendingInvitation') as string);
		if (isAdvisory) {
			setTimeout(() => {
				navigate(acceptInvitation);
			}, 100);
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, []);

	/** * NEW start */
	const dispatch = useDispatch<AppDispatch>();
	const accountDeleted: boolean = useSelector((state: RootState) => state.login.accountDeleted);
	const allCompanies: CompanyDbModel[] | null = useSelector(
		(state: RootState) => state.companies.allCompaniesList
	);
	const companies: CompanyDbModel[] | null = useSelector(
		(state: RootState) => state.companies.companiesList
	);
	const selectedCompany: CompanyDbModel | null = useSelector(
		(state: RootState) => state.companies.selectedCompany
	);
	const selectedUser: UserModel | null = useSelector((state: RootState) => state.login.user);
	const nextButtonHandler = (): void => {
		if (selectedCompany) {
			if (selectedCompany.plan) {
				navigate(dashboard);
				dispatch(fetchFinancialsData({ selectedCompany }));
			} else {
				navigate(manageSubscription);
			}
		} else {
			navigate(chooseCompanyType);
		}
	};

	const logoutDeletedUser = (e: FormEvent<Element>): void => {
		e.preventDefault();
		dispatch(logout());
		window.location.href = linkCognitoSignOut;
	};

	const getParagrahContent = () => {
		if (accountDeleted) {
			return 'Your account has been permanently deleted. We’re sorry to see you go.';
		}

		console.log('companies', companies, 'allCompanies', allCompanies, 'selectedUser', selectedUser);

		if (
			(!companies || companies.length === 0) &&
			((allCompanies && allCompanies.length > 0) || selectedUser?.hasPermanentlyDeletedCompanies)
		) {
			return 'There is no company associated with this user account. If you think this is an error, please arrange for an invite to be sent to you by an admin user. Alternatively, please create a new company or proceed to delete to your user account.';
		}
		if (!companies || companies.length === 0) {
			return `Thank you for signing up with us. As your first step please take a minute to create your first company.`;
		}
		if (companies.length === 1) {
			return (
				`Your company ${companies[0].company_name} has an existing account. ` +
				'Do you want to join your company’s account or create a new one?'
			);
		}
		return (
			'You own accounts for multiple companies.\n' +
			'Would you like to proceed with one of your existing company profile or create a new one?'
		);
	};

	const selectDefaultCompanyHandler = (): void => {
		if (companies && companies.length === 1) {
			const defaultCompany = companies[0];
			dispatch(selectCompany(defaultCompany));
			dispatch(
				fetchFinancialsData({
					selectedCompany: {
						...defaultCompany,
						plan: defaultCompany.plan
					}
				})
			);
			navigate(dashboard);
		}
	};
	/** * NEW end */

	if (accountDeleted) {
		return (
			<div className={styles.container}>
				<HeaderNoSidebar
					heading={companies ? 'Choose your path' : 'Welcome'}
					paragraf={getParagrahContent()}
				/>
				<p>
					If this was a mistake please contact{' '}
					<a href="mailto:support@bmim.co.uk">support@bmim.co.uk</a>.
				</p>
				<Button
					id="logOut"
					link={linkCognitoSignOut}
					onClick={(e) => logoutDeletedUser(e)}
					type="submit"
					value="Log out"
				/>
			</div>
		);
	}

	return companies ? (
		<div className={styles.container}>
			<HeaderNoSidebar
				heading={companies ? 'Choose your path' : 'Welcome'}
				paragraf={getParagrahContent()}
			/>
			{companies && companies.length === 1 && (
				<Button
					id="joinExistingCompany"
					link={dashboard}
					onClick={selectDefaultCompanyHandler}
					type="submit"
					value="Continue with existing company"
				/>
			)}

			{companies && companies.length > 1 && (
				<ListOfCompanies
					className={className}
					labelPlaceholder="Select company to view financials"
				/>
			)}

			{companies && companies.length > 0 && (
				<div className={styles.underline}>
					<p style={{ border: 0 }}>
						<span>or</span>
					</p>
				</div>
			)}
			<Button
				id="chooseCompanyType"
				link={chooseCompanyType}
				onClick={() => {}}
				type="submit"
				value="Add company"
				whiteBtn
			/>
			{(!companies || companies.length === 0) &&
				((allCompanies && allCompanies.length > 0) ||
					selectedUser?.hasPermanentlyDeletedCompanies) && (
					<>
						<div className={styles.underline}>
							<p style={{ border: 0 }}>
								<span>or</span>
							</p>
						</div>

						<DeleteAccount
							displayAs="button"
							selectedUser={selectedUser}
							allCompanyData={allCompanies}
							companyData={companies}
						/>
					</>
				)}

			<div className={styles.nextButton}>
				{companies && companies.length > 1 && (
					<Button
						id="nextToLanding"
						link={dashboard}
						onClick={nextButtonHandler}
						type="button"
						value="Next"
						whiteBtn={false}
					/>
				)}
			</div>
		</div>
	) : (
		<></>
	);
};

export default JoinAddCompany;
