/* eslint-disable jsx-a11y/no-static-element-interactions */
/* eslint-disable react/button-has-type */
/* eslint-disable jsx-a11y/no-noninteractive-element-interactions */
/* eslint-disable @typescript-eslint/no-unused-vars */
import type { FormEvent } from 'react';
import type React from 'react';
import { useContext, useDeferredValue, useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { NavLink, useNavigate } from 'react-router-dom';

import environment from '../../../Environments/environment';
import type { CompanyDbModel } from '../../../Pages/Companies/Components/CompaniesComponents.helper';
import type { FinancialsModel } from '../../../Pages/Financials/Components/FinancialsForm/FinancialsForm.helper';
import type { RootState } from '../../../ReduxState/store';
import type { GlobalStateModel } from '../../../Store/global/GlobalState-context';
import { GlobalStateContext } from '../../../Store/global/GlobalState-context';
import type { UserModel } from '../../../Store/User/user-context.helper';
import SignUpLogo from '../SignUpLogo';
import CloseNavArrowSvg from './Components/CloseNavArrowSvg';
import styles from './NavBar.module.scss';
import type { Props } from './NavBarHelper';
import { InsightSvg, DatabaseSvg, ToolsSvg, AboutSvg } from './NavBarHelper';
import { set } from 'react-hook-form';

const NavBar: React.FC<Props> = ({ isOpen, isOpenChanged }: Props): JSX.Element => {
	console.log('is it open', isOpen);
	const user: UserModel = useSelector((state: RootState) => state.login.user);
	const selectedCompany = useSelector(
		(state: RootState): CompanyDbModel | null => state.companies.selectedCompany
	);
	const selectedFinancials = useSelector(
		(state: RootState): FinancialsModel[] | null => state.financials.selectedFinancials
	);
	const navigate = useNavigate();
	const {
		dashboard,
		financials,
		companies,
		moneyForCeos,
		moneyForGrowth,
		tools,
		cashFlowSummary,
		database
	} = environment.frontendRoutes;

	const globalContext: GlobalStateModel = useContext(GlobalStateContext);
	const deferredIsNavbarOpen = globalContext.isNavbarOpen;
	const deferredFirstFinancial = useDeferredValue(
		JSON.parse(localStorage.getItem('first-financial') as string)
	);
	const deferredSecondFinancial = useDeferredValue(
		JSON.parse(localStorage.getItem('second-financial') as string)
	);
	const deferredThirdFinancial = useDeferredValue(
		JSON.parse(localStorage.getItem('third-financial') as string)
	);
	const deferredSelectedFinancials = useDeferredValue(
		JSON.parse(localStorage.getItem('selected-financials') as string)
	);
	const currentRoute = window.location.pathname;
	const [moneyForCeoLink, setMoneyForCeoLink] = useState(currentRoute);
	const [moneyForGrowthLink, setMoneyForGrowthLink] = useState(currentRoute);
	const [cashFlowAnalysisLink, setCashFlowAnalysisLink] = useState(currentRoute);
	const [isPopupShown, setIsPopupShown] = useState<boolean>(false);
	const [logo, setLogo] = useState('appLogo'); // Replace with your default image path
	const [checked, setChecked] = useState(false);
	console.log('selected company logo', logo);

	useEffect(() => {
		if (selectedCompany?.branding?.logo && !checked) {
			fetch(logo, { method: 'HEAD' }) // Use HEAD for a quick check
				.then((res) => {
					if (res.ok) {
						// setImageExists(true);
						console.log('Logo exists:', logo);
						setLogo(selectedCompany?.branding?.logo || 'appLogo');
					} else {
						// setImageExists(false);
						console.log('Logo does not exist, using default.');
						setLogo('appLogo');
					}
					setChecked(true);
				})
				.catch(() => {
					console.log('Error while checking logo, using default.');
					// setImageExists(false);
					setLogo('appLogo');
					setChecked(true);
				});
		} else {
			setChecked(false);
			setLogo('appLogo');
		}
	}, [selectedCompany?.branding?.logo]);

	useEffect(() => {
		if (document.body.offsetWidth <= 1280) {
			globalContext.closeNavBarHandler(false);
		} else {
			globalContext.closeNavBarHandler(true);
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, []);

	function areToolsAvailable(event: string): void {
		if (deferredFirstFinancial && deferredSecondFinancial && deferredThirdFinancial) {
			setMoneyForGrowthLink(moneyForGrowth);
			setMoneyForCeoLink(moneyForCeos);
			setCashFlowAnalysisLink(cashFlowSummary);
		} else if (deferredFirstFinancial && deferredSecondFinancial) {
			setMoneyForGrowthLink(moneyForGrowth);
			setMoneyForCeoLink(moneyForCeos);
			setCashFlowAnalysisLink(currentRoute);
		} else if (deferredFirstFinancial) {
			setMoneyForGrowthLink(moneyForGrowth);
			setMoneyForCeoLink(currentRoute);
			setCashFlowAnalysisLink(currentRoute);
		} else {
			setCashFlowAnalysisLink('');
			setMoneyForCeoLink('');
			setMoneyForGrowthLink('');
		}
	}

	function closeNavHandler(): void {
		// globalContext.closeNavBarHandler(!deferredIsNavbarOpen);
		isOpenChanged();
	}

	function setSwitchHandler(event: FormEvent): void {
		const { id } = event.currentTarget;
		const planId = selectedCompany ? selectedCompany.plan.id : 0;
		if (
			!selectedFinancials ||
			(id === 'moneyMultiplierForCeos' && selectedFinancials.length < 2) ||
			(id === 'moneyForGrowth' && selectedFinancials.length < 1) ||
			// if plan is lower than 3 allow for user to navigate to tool page in order to display upgrade message
			(id === 'cashFlowAnalysis' && selectedFinancials.length < 3 && (planId === 3 || planId <= 1))
		) {
			let pathname = `${financials}`;
			if (id === 'moneyMultiplierForCeos') pathname = `${pathname}?tool=moneyMultiplier`;
			if (id === 'cashFlowAnalysis') pathname = `${pathname}?tool=cashFlowAnalysis`;
			navigate(pathname);
		}
	}

	function dashboardHandler() {
		if (!selectedFinancials || selectedFinancials.length === 0) {
			navigate(financials);
		}
	}

	function financialPopupHandler(): void {
		console.log('financials clicked');
	}

	return (
		<>
			{user && (
				<div className={styles.container}>
					<div className={[styles.navWrapper, !isOpen ? styles.hidden : ''].join(' ')}>
						<header className={styles.header}>
							<div className={[styles.logoStyle, !isOpen ? styles.hidden : ''].join(' ')}>
								{logo === 'appLogo' ? (
									<SignUpLogo logoClass={styles.logo} />
								) : (
									<img src={logo} alt="Company Logo" className={styles.logo} />
								)}
							</div>
						</header>
						<nav className={styles.navbar}>
							<ul>
								<li className={styles.insights} onClick={dashboardHandler}>
									<NavLink
										className={({ isActive }) => (isActive ? styles.active : undefined)}
										to={dashboard}
									>
										<div className={styles.iconNavLink}>
											<InsightSvg />
											<h4>Dashboard</h4>
										</div>
									</NavLink>
								</li>
								<li className={styles.database}>
									<NavLink
										className={({ isActive }) => (isActive ? styles.active : undefined)}
										to={companies}
									>
										<div className={styles.iconNavLink}>
											<DatabaseSvg />
											<h4>Database</h4>
										</div>
									</NavLink>
								</li>
								<li className={styles.childItem}>
									<NavLink
										className={({ isActive }) => (isActive ? styles.active : undefined)}
										to={companies}
									>
										Companies
									</NavLink>
								</li>
								<li className={styles.childItem}>
									<NavLink
										className={({ isActive }) => (isActive ? styles.active : undefined)}
										to={financials}
									>
										Financials
									</NavLink>
								</li>
							</ul>
							<ul>
								<li className={styles.tools}>
									<NavLink
										className={({ isActive }) => (isActive ? styles.active : undefined)}
										to={tools}
									>
										<div className={styles.iconNavLink}>
											<ToolsSvg />
											<h4>Tools</h4>
										</div>
									</NavLink>
								</li>

								<li
									className={styles.childItem}
									id="moneyMultiplierForCeos"
									onClick={setSwitchHandler}
								>
									<NavLink
										className={({ isActive }) => (isActive ? styles.active : undefined)}
										to={moneyForCeos}
									>
										Money Multiplier for CEOs
									</NavLink>
								</li>
								<li className={styles.childItem} id="moneyForGrowth" onClick={setSwitchHandler}>
									<NavLink
										className={({ isActive }) => (isActive ? styles.active : undefined)}
										to={moneyForGrowth}
									>
										Money for Growth
									</NavLink>
								</li>
								<li className={styles.childItem} id="cashFlowAnalysis" onClick={setSwitchHandler}>
									<NavLink
										className={({ isActive }) => (isActive ? styles.active : undefined)}
										to={cashFlowSummary}
									>
										Cash Flow Analytics
									</NavLink>
								</li>
							</ul>
						</nav>
						<footer className={styles.about}>
							<div>
								<AboutSvg />
								<h4>
									<a
										href="https://www.moneyxplier.com/"
										target="_blank"
										rel="noreferrer"
										style={{ textTransform: 'none' }}
									>
										About moneyXplier®
									</a>
								</h4>
							</div>
						</footer>
					</div>
					<button
						className={!isOpen ? styles.closeNavButton : styles.openNavButton}
						onClick={closeNavHandler}
					>
						{isOpen ? (
							<CloseNavArrowSvg className={styles.openButton} />
						) : (
							<CloseNavArrowSvg className={styles.closedButton} />
						)}
					</button>
					{isPopupShown && (
						<div className={styles.popupMessage}>
							<p>
								Please go to{' '}
								<small className={styles.popupMessage__financials} onClick={financialPopupHandler}>
									Financials
								</small>{' '}
								and select financials
							</p>
						</div>
					)}
				</div>
			)}
		</>
	);
};

export default NavBar;
