/* eslint-disable react/jsx-no-bind */
/* eslint-disable @typescript-eslint/no-unused-vars */
import { Accordion, AccordionDetails, AccordionSummary, Typography } from '@mui/material';
import type { ChangeEvent, FormEvent } from 'react';
import type React from 'react';
import { useContext, useDeferredValue, useEffect, useState } from 'react';
import { useSelector } from 'react-redux';

import type { RootState } from '../../../ReduxState/store';
import type { FinancialsContextModel } from '../../../Store/Financials/financials-context';
import { FinancialsContext } from '../../../Store/Financials/financials-context';
import type { IndustryModel } from '../../../Store/Financials/financialsContext.helper';
import type { MoneyGrowContextModel } from '../../../Store/MoneyForGrowth/MoneyForGrowth-Contex';
import { MoneyGrowthContext } from '../../../Store/MoneyForGrowth/MoneyForGrowth-Contex';
import type { CompanyDbModel } from '../../Companies/Components/CompaniesComponents.helper';
import type { FinancialsModel } from '../../Financials/Components/FinancialsForm/FinancialsForm.helper';
import ArrowSvg from '../../Financials/Components/UI/ArrowSvg';
import ReloadSvg from '../../Financials/Components/UI/ReloadSvg';
import findRightIndustryIndexHandler from '../../MoneyForCeosBusiness/Components/MoneyForBusiness.helper';
import styles from './MoneyForGrowthHeader.module.scss';
import hasEditPermission from '../../../utils/getUserPermissions';
import { useUiContext } from '../../../Store/UiContext/UiContext';
import ToolsTitleNavigation from '../../ToolsNavigation/ToolsTitleNavigation/ToolsTitleNavigation';
import ToolsIntroAccordion from '../../ToolsNavigation/ToolsIntroAccordion/ToolsIntroAccordion';
import Button from '../../../Components/UI/Button/Button';

interface MoneyForGrowthHeaderInterface {
	revenue: number;
	setRevenue: React.Dispatch<React.SetStateAction<number>>;
	print?: boolean;
}

const MoneyForGrowthHeader: React.FC<MoneyForGrowthHeaderInterface> = (
	props: MoneyForGrowthHeaderInterface
): JSX.Element => {
	const print = props.print;
	const { toastNotification } = useUiContext();
	const [revenueInputValue, setRevenueInputValue] = useState(props.revenue);
	const selectedCompany = useSelector(
		(state: RootState): CompanyDbModel | null => state.companies.selectedCompany
	);
	const selectedFinancials = useSelector(
		(state: RootState): FinancialsModel[] | null => state.financials.selectedFinancials
	);

	const moneyGrowthContext: MoneyGrowContextModel = useContext(MoneyGrowthContext);

	function clickHandler(): void {
		// moneyGrowthContext.updateIncreaseRevenueUpdatedHandler(moneyGrowthContext.increasedRevenue);
		props.setRevenue(revenueInputValue);
	}

	function arrowUpHandler(): void {
		// moneyGrowthContext.incrementRevenueHandler();
		if (!hasEditPermission(selectedCompany)) {
			toastNotification('info', 'You do not have permission to modify reports');
			return;
		}
		// props.setRevenue((prevState) => +(prevState + 0.1).toFixed(2));
		setRevenueInputValue((prevState) => +(prevState + 0.1).toFixed(2));
	}

	function arrowDownHandler(): void {
		// moneyGrowthContext.decrementRevenueHandler();
		// props.setRevenue((prevState) => (+prevState > 0 ? +(prevState - 0.1).toFixed(2) : 0));
		if (!hasEditPermission(selectedCompany)) {
			toastNotification('info', 'You do not have permission to modify reports');
			return;
		}
		// props.setRevenue((prevState) => +(prevState - 0.1).toFixed(2));
		setRevenueInputValue((prevState) => +(prevState - 0.1).toFixed(2));
	}

	function changeHandler(event: ChangeEvent<HTMLInputElement>): void {
		if (!hasEditPermission(selectedCompany)) {
			toastNotification('info', 'You do not have permission to modify reports');
			return;
		}
		const regex = /^[\-\.,0-9]+$/;
		if (regex.test(event.target.value)) {
			// moneyGrowthContext.getRevenueIncreaseValue(+event.target.value);
			// @ts-ignore
			// props.setRevenue(event.target.value);
			setRevenueInputValue(event.target.value);
		}
	}
	const firstFinancial = useDeferredValue(
		JSON.parse(localStorage.getItem('first-financial') as string)
	);
	const secondFinancial = useDeferredValue(
		JSON.parse(localStorage.getItem('second-financial') as string)
	);
	const [ebitdaInput, setEbitdaInput] = useState<number>(1);
	const [selectedIndustry, setSelectedIndustry] = useState<IndustryModel | undefined>(undefined);
	const financialContext: FinancialsContextModel = useContext(FinancialsContext);
	const accordionContent = `
		<p class="subtitle">What is this for?</p>
		Understand how much working capital and retained profit your business needs to support
		your revenue growth — and whether your current business model is cash-positive or
		cash-burning.
		<p class="subtitle">What will I get?</p>
		<ul>
			<li>A clear cash impact of your growth target</li>
			<li>Your retained profit and funding shortfall (if any)</li>
			<li>How much banks could lend based on your numbers</li>
			<li>A recommended growth path (e.g., Zig-zag vs. straight-line growth)</li>
		</ul>
		<p class="subtitle">How do I start?</p>
		Enter or adjust your revenue growth target → Review changes in gross margin, EBIT, and
		retained profit → See if you have enough cash to support this growth → Use the output to
		plan funding or adjust growth strategy.
		<p class="subtitle">💡 Strategy Tip</p>
		<i>Grow without draining your cash.</i> High growth isn’t always healthy growth. Ensure
		your expansion plans keep you cash-positive by checking your retained profits, funding
		needs, and lending potential before committing to a target.
	`;

	useEffect(() => {
		if (selectedCompany && selectedFinancials && selectedFinancials.length > 1) {
			findRightIndustryIndexHandler(
				selectedCompany,
				selectedFinancials[1],
				setSelectedIndustry,
				selectedFinancials[0],
				financialContext,
				setEbitdaInput
			);
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [selectedCompany, selectedFinancials]);

	return (
		<div className={styles.container}>
			<ToolsTitleNavigation
				title="Growth Planner"
				stepNumber={1}
				maxSteps={1}
				introText="Is your growth strategy financially sustainable?"
			/>

			<ToolsIntroAccordion content={accordionContent} ctaTitle="Analyse my growth plan" />

			<div className={`${styles.ebitdaMultiple} ${print ? styles.print : ''}`}>
				<h3 style={{ textTransform: 'none' }}>For a revenue increase of</h3>
				<input
					className={styles.ebitdaInput}
					id="priceIncrease"
					onChange={changeHandler}
					placeholder="0.00"
					type="text"
					// value={props.revenue}
					value={revenueInputValue}
				/>
				<ArrowSvg clickHandler={arrowUpHandler} svgClass={styles.arrowUp} />
				<ArrowSvg clickHandler={arrowDownHandler} svgClass={styles.arrowDown} />
				{!print && (
					<Button
						id="UpdateResults"
						onClick={clickHandler}
						buttonClass={styles.submitButton}
						type="submit"
						value="Update results"
						link="#"
						svg={<ReloadSvg className={styles.saveButtonIcon} />}
					/>
				)}
			</div>
		</div>
	);
};
export default MoneyForGrowthHeader;
