/* eslint-disable react/destructuring-assignment */
import AddIcon from '@mui/icons-material/Add';
import { Button, Fab } from '@mui/material';
import Box from '@mui/material/Box';
import classNames from 'classnames';
import { useContext, useEffect, useState } from 'react';
import type React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Link } from 'react-router-dom';

import globalStyle from '../../../Components/GlobalStyles/globals.module.scss';
import environment from '../../../Environments/environment';
import { setSelectedFinancials } from '../../../ReduxState/financials/financialsSlice';
import type { AppDispatch, RootState } from '../../../ReduxState/store';
import type { FinancialsTypeContextModel } from '../../../Store/Financials/financials-form-context-helper';
import { FinancialsFormContext } from '../../../Store/Financials/financialsForm-context';
import { useUiContext } from '../../../Store/UiContext/UiContext';
import type { CompanyDbModel } from '../../Companies/Components/CompaniesComponents.helper';
import styles from '../Financials.module.scss';
import FinancialsCards, { ToolsCards } from './FinancialsCards/FinancialsCards';
import type { FinancialsModel } from './FinancialsForm/FinancialsForm.helper';
import FinancialsList from './FinancialsList';
import FinancialsTableHeader from './FinancialsTableHeader';
import type { FinancialsHomeInterface } from './UI/FinancialsHelper';
import PopupButton from './UI/PopupButton';
import hasEditPermission from '../../../utils/getUserPermissions';
import type { UserModel } from '../../../Store/User/user-context.helper';

const FinancialsHome: React.FC<FinancialsHomeInterface> = (
	props: FinancialsHomeInterface
): JSX.Element => {
	const { moneyForCeos, moneyForGrowth, cashFlowSummary } = environment.frontendRoutes;
	const [selectedTool, setSelectedTool] = useState<string>(ToolsCards.growth);
	const [toolConditionMet, setToolConditionMet] = useState<string>(styles.collapseContainer);
	const [selectedFinancialsList, setSelectedFinancialsList] = useState<Record<
		string,
		boolean
	> | null>(null);
	const [message, setMessage] = useState<string>('');
	const [color, setColor] = useState<string>('green');
	const financialsForm: FinancialsTypeContextModel = useContext(FinancialsFormContext);
	const { manageSubscription } = environment.frontendRoutes;

	const dispatch = useDispatch<AppDispatch>();
	const selectedCompany: CompanyDbModel | null = useSelector(
		(state: RootState) => state.companies.selectedCompany
	);
	const financialsList: FinancialsModel[] | null = useSelector(
		(state: RootState) => state.financials.financialsList
	);
	const selectedFinancials: FinancialsModel[] | null = useSelector(
		(state: RootState) => state.financials.selectedFinancials
	);
	const isPaymentExpired: boolean | null = useSelector(
		(state: RootState) => state.payment.paymentExpired
	);
	const { toastNotification } = useUiContext();

	useEffect((): void => {
		if (!financialsList || financialsList.length === 0) {
			// setMessage('Please add financials:');
			setMessage('');
			return;
		}
		switch (selectedTool) {
			case ToolsCards.multiplier:
				// setMessage('Please select a minimum of 2 sets of financials to use with this tool.');
				setMessage('(You must have at least two sets of financials selected to continue.)');
				break;
			case ToolsCards.growth:
				// setMessage('Please select a minimum of 1 sets of financials to use with this tool.');
				setMessage('(You must have at least one set of financials selected to continue.)');
				break;
			case ToolsCards.cashFlow:
				// setMessage('Please select a minimum of 3 sets of financials to use with this tool.');
				setMessage('(You must have at least three sets of financials selected to continue.)');
				break;

			default:
				setMessage('Please select set of financials to be able to use the tools:');
				break;
		}
	}, [selectedTool]);

	useEffect((): void => {
		let minSelected = null;
		switch (selectedTool) {
			case ToolsCards.multiplier:
				minSelected = 2;
				break;
			case ToolsCards.growth:
				minSelected = 1;
				break;
			case ToolsCards.cashFlow:
				minSelected = 3;
				break;
		}
		if (selectedFinancials && selectedFinancials.length < minSelected!) {
			setColor('red');
		} else {
			setColor('green');
		}
		if (selectedFinancials && minSelected && selectedFinancials.length >= minSelected) {
			// true
			setToolConditionMet(styles.collapseContainerGreen);
		} else {
			// false
			setToolConditionMet(styles.collapseContainer);
		}
	}, [selectedTool, selectedFinancials]);

	const queryParameters = new URLSearchParams(window.location.search);
	const type = queryParameters.get('tool');

	useEffect(() => {
		setSelectedFinancialsList(null);
		switch (type) {
			case ToolsCards.multiplier:
				setSelectedTool(ToolsCards.multiplier);
				break;
			case ToolsCards.cashFlow:
				setSelectedTool(ToolsCards.cashFlow);
				break;
			default:
				setSelectedTool(ToolsCards.growth);
		}
	}, [selectedCompany, type]);

	const goToToolsHandler = (): string => {
		let route = '';
		switch (selectedTool) {
			case ToolsCards.multiplier:
				route = moneyForCeos;
				break;
			case ToolsCards.growth:
				route = moneyForGrowth;
				break;
			case ToolsCards.cashFlow:
				route = cashFlowSummary;
				break;
		}
		return route;
	};

	const nextButtonHandler = (event: React.MouseEvent<HTMLButtonElement>): void => {
		if (!!selectedFinancials && selectedFinancials.length > 0) {
			// below is updating the financials context, which should not be used, and the redux state is already updated
			// when a click on checkbox is done, so the below code should be removed in the future
			dispatch(setSelectedFinancials(selectedFinancialsList));
		} else if (!financialsList || financialsList.length <= 0) {
			toastNotification(
				'info',
				'Please add and then select appropriate financials to use the tools.'
			);
		} else {
			let number = 1;
			if (selectedTool === ToolsCards.cashFlow) {
				number = 3;
			}
			if (selectedTool === ToolsCards.multiplier) {
				number = 2;
			}
			toastNotification(
				'info',
				`Please select ${number} set of financials to see your Financial metrics.`
			);
		}
	};

	return (
		<div className={props.financialsTableContainer}>
			<div>
				<h2 style={{ fontSize: '18px', color: 'var(--primary-color)', fontWeight: '700' }}>
					{selectedCompany?.company_name}
				</h2>
				{/* {financialsList ? ( */}
				{/* <p style={{ fontSize: '16px' }}>{message}</p> */}
				{selectedCompany?.plan.id === 1 && (
					<p style={{ fontSize: '16px' }}>
						Please use the sample financial data below to explore the tools:
					</p>
				)}
				{isPaymentExpired && (
					<p style={{ fontSize: '16px' }}>
						Your subscription plan for{' '}
						<b style={{ color: 'var(--primary-color)' }}>{selectedCompany?.company_name}</b> is
						expred. Your data is still there but you cannot use it until you{' '}
						<Link to={manageSubscription} style={{ color: 'var(--primary-color)' }}>
							Renew subscriptions to proceed with your financials
						</Link>
						<br />
						<br />
						In the meantime you can still use below demo financial data to work with the tools:
					</p>
				)}
				{selectedCompany?.plan.id !== 1 && !isPaymentExpired && (
					<p style={{ fontSize: '16px' }}>Please add your company financials below:</p>
				)}
				{/* ) : (
					<p style={{ fontSize: '16px' }}>
						Please add a minimum of 1 set of financials to be able to use the tools:
					</p>
				)} */}
				{financialsList && (
					<div className={props.financialsTableClass}>
						<FinancialsTableHeader
							class={props.financialsTable}
							isDemoUser={selectedCompany?.plan.title}
							isLastUpdateExist={props.lastUpdate}
						/>
						<FinancialsList
							// addFinancials={props.addFinancials}
							changeHandler={props.changeHandler}
							classNameContainer={props.financialsList}
							classNameForm={props.financialsListForm}
							financialsId={props.financialsId}
							formAdvisor={props.formAdvisor}
							payload={props.payload}
							recordUpdated={props.recordUpdated}
							selectedItem={props.itemForEdit}
							selectedList={setSelectedFinancialsList}
						/>
					</div>
				)}
				{selectedCompany && selectedCompany?.plan.id > 1 && !isPaymentExpired && (
					<Box
						className={props.addIcon}
						onClick={financialsForm.setFinancialsIdHandler}
						sx={{
							'& > :not(style)': {
								m: 1
							}
						}}
					>
						<Fab
							aria-label="add"
							color="primary"
							onClick={() => {
								if (hasEditPermission(selectedCompany)) {
									financialsForm.cancelHandler();
									props.changeHandler();
								} else {
									toastNotification('info', 'You do not have permission to add financials.');
								}
							}}
						>
							<AddIcon />
						</Fab>
						<p>Add financials</p>
					</Box>
				)}
			</div>
			{financialsList && (
				<>
					<PopupButton
						collapseContainer={toolConditionMet}
						selected={`${
							selectedFinancials ? selectedFinancials.length : 0
						} sets of financials selected.`}
						select={message}
					/>
					<FinancialsCards
						selectedTool={selectedTool}
						color={color}
						message={message}
						setSelectedTool={setSelectedTool}
					/>
					<div className={classNames('text-center', globalStyle.bottomPaddingElement)}>
						{selectedFinancials && selectedFinancials.length > 0 ? (
							<button
								className={globalStyle.submitButton}
								onClick={(event) => nextButtonHandler(event)}
								type="submit"
							>
								<Link to={goToToolsHandler()}>Continue to results</Link>
								{/* Next */}
							</button>
						) : (
							<button
								className={globalStyle.cancelButton}
								onClick={(event) => nextButtonHandler(event)}
								type="submit"
							>
								<span style={{ cursor: 'not-allowed', color: 'gray' }}>Continue to results</span>
							</button>
						)}
					</div>
				</>
			)}
		</div>
	);
};

export default FinancialsHome;
