/* eslint-disable react/jsx-no-bind */
/* eslint-disable react/destructuring-assignment */
/* eslint-disable react/no-unused-prop-types */
import BorderColorIcon from '@mui/icons-material/BorderColor';
import ContentPasteIcon from '@mui/icons-material/ContentPaste';
import DeleteIcon from '@mui/icons-material/Delete';
import { Button } from '@mui/material';
import axios from 'axios';
import { useContext, useDeferredValue, useEffect, useState } from 'react';
import type React from 'react';
import type { ChangeEvent, FormEvent } from 'react';
import { useDispatch, useSelector } from 'react-redux';

import environment from '../../../Environments/environment';
import {
	deleteFinancialData,
	setFinancialItemForEdit,
	setSelectedFinancial
} 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 type { GlobalStateModel } from '../../../Store/global/GlobalState-context';
import { GlobalStateContext } from '../../../Store/global/GlobalState-context';
import { useUiContext } from '../../../Store/UiContext/UiContext';
import type { CompanyDbModel } from '../../Companies/Components/CompaniesComponents.helper';
import type { FinancialsModel } from './FinancialsForm/FinancialsForm.helper';
import hasEditPermission from '../../../utils/getUserPermissions';

interface FinancialsListInterface {
	classNameContainer: string;
	payload: string;
	classNameForm: string;
	recordUpdated: string;
	financialsId: string;
	changeHandler: () => void;
	selectedItem: (event: FinancialsModel) => void;
	formAdvisor: string;
	selectedList?: (state: any) => void;
}

const { apiUrl, backendRoutes } = environment;

const FinancialsList: React.FC<FinancialsListInterface> = (
	props: FinancialsListInterface
): JSX.Element => {
	/** NEW start */
	const dispatch = useDispatch<AppDispatch>();
	const { toastNotification, confirmModal } = useUiContext();

	const selectedCompany = useSelector(
		(state: RootState): CompanyDbModel | null => state.companies.selectedCompany
	);
	const financialsList = useSelector(
		(state: RootState): FinancialsModel[] | null => state.financials.financialsList
	);
	const selectedFinancials = useSelector(
		(state: RootState): FinancialsModel[] | null => state.financials.selectedFinancials
	);

	const isSelected = (financialId: string): boolean => {
		if (selectedFinancials) {
			const selected = selectedFinancials.find(
				(financial) => financial.financials_id === financialId
			);
			return !!selected;
		}
		return false;
	};
	/** NEW end */

	const [financialsListItems, setFinancialsListItems] = useState<FinancialsModel[] | string>([]);
	const financialsForm: FinancialsTypeContextModel = useContext(FinancialsFormContext);

	const globalContext: GlobalStateModel = useContext<GlobalStateModel>(GlobalStateContext);

	const deferredPayload = useDeferredValue(props.payload);
	const selectedCompanyStorage: CompanyDbModel = JSON.parse(
		localStorage.getItem('selected-company') as string
	);

	const [checkedFinancials, setCheckedFinancials] = useState<any>({});
	function selectFinancialsHandler(event: ChangeEvent<HTMLInputElement>): void {
		const item = event.target.parentElement?.id as string;
		const { name, checked } = event.target;

		dispatch(setSelectedFinancial({ financial_id: name, checked }));
	}

	function editHandler(event: FormEvent<HTMLButtonElement>): void {
		if (!hasEditPermission(selectedCompany)) {
			toastNotification('info', 'You do not have permission to edit financials');
			return;
		}
		const id: string | undefined = event.currentTarget.parentElement?.parentElement?.id;
		const itemForEdit: FinancialsModel | string | undefined = (
			financialsList as FinancialsModel[]
		).find((item) => item.financials_id === id);
		// set financial entry for edit:
		financialsForm.editHandler(itemForEdit);
		dispatch(setFinancialItemForEdit(itemForEdit));
		// display the form:
		props.changeHandler();
	}

	async function deleteHandler(event: FormEvent<HTMLButtonElement>): Promise<void> {
		if (!hasEditPermission(selectedCompany)) {
			toastNotification('info', 'You do not have permission to delete financial data');
			return;
		}
		const id: string | undefined = event.currentTarget.parentElement?.parentElement?.id;
		const isConfirmed = await confirmModal({
			title: 'Confirm financial data deletion',
			message: 'Are you sure you want to delete this financial period data?'
		});

		if (isConfirmed && id !== '') {
			const payload = { company_id: selectedCompany?.company_id, financials_id: id };
			dispatch(deleteFinancialData(payload));
		}
	}

	return (
		<div className={props.classNameContainer}>
			<form className={props.classNameForm}>
				{financialsList ? (
					financialsList.map((item, index) =>
						item.input ? (
							// eslint-disable-next-line react/no-array-index-key
							<label key={index} id={item.financials_id}>
								<input
									checked={isSelected(item.financials_id)}
									id={index.toString()}
									name={item.financials_id}
									onChange={selectFinancialsHandler}
									type="checkbox"
								/>
								<p data-company-name="companyName">
									{`${item.input?.['Month Start']}
                                ${item.input?.['Year Start']} -
                                ${item.input?.['Month Ending']}
                                ${item.input?.['Year Ending']}`}
								</p>
								<p>{props.recordUpdated?.split('GMT')}</p>
								{/* {selectedCompany && parseInt(selectedCompany.company_id, 10) > 1 ? ( */}
								{selectedCompany && selectedCompany?.plan?.id > 1 ? (
									<p>
										<Button onClick={editHandler} startIcon={<BorderColorIcon />} />
										<Button onClick={deleteHandler} startIcon={<DeleteIcon />} />
									</p>
								) : (
									<p>
										<Button onClick={editHandler} startIcon={<ContentPasteIcon />} />
									</p>
								)}
							</label>
						) : (
							''
						)
					)
				) : (
					// eslint-disable-next-line jsx-a11y/label-has-associated-control, jsx-a11y/label-has-for
					<label />
				)}
			</form>
		</div>
	);
};
export default FinancialsList;
