/* eslint-disable react/destructuring-assignment */
import type { SelectChangeEvent } from '@mui/material/Select';
import { useEffect, useState } from 'react';
import type React from 'react';
import type { ChangeEvent, FormEvent } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';

import { DUMMY_ARRAY_ROLES } from '../../Components/DatabaseHelper';
import Dropdown from '../../Components/UI/Dropdown/Dropdown';
import DropdownForPrefix from '../../Components/UI/Dropdown/DropdownForPrefix';
import InputElement from '../../Components/UI/Input/Input';
import environment from '../../Environments/environment';
import { createCompany, updateCompany } from '../../ReduxState/companies/companiesSlice';
import type { AppDispatch, RootState } from '../../ReduxState/store';
// import { AccountContext } from '../../Store/Account/account-context';
// import type { AccountContextModel } from '../../Store/Account/AccountContextModel';
import type { UserModel } from '../../Store/User/user-context.helper';
import companyDropdownPredefinedValues from '../Companies/Companies.helper';
import type { CompanyDbModel } from '../Companies/Components/CompaniesComponents.helper';
import cardStyles from '../Financials/Components/FinancialsCards/FinancialsCards.module.scss';
import styles from './ChooseCompanyType.module.scss';
import type { CompanyTypeInterface } from './companyTypeHelper';
import Countries from './Countries';
import type { ChooseCompanyTypeInterface } from './ValidationHelper';
import inputStyles from '../../Components/UI/Input/Input.module.scss';
import DeleteCompany from '../Account/Components/DeleteCompany/DeleteCompany';
// import { FormControl, MenuItem, Select } from '@mui/material';
import globalStyle from '../../Components/GlobalStyles/globals.module.scss';
import { fetchUserData } from '../../ReduxState/login/loginSlice';

const ChooseCompanyTypeForm: React.FC<ChooseCompanyTypeInterface> = (
	props: ChooseCompanyTypeInterface
): JSX.Element => {
	// const accountContext: AccountContextModel = useContext(AccountContext);
	const navigate = useNavigate();
	/** NEW start */
	const dispatch = useDispatch<AppDispatch>();
	const selectedUser = useSelector((state: RootState): UserModel | null => state.login.user);
	const companiesList = useSelector(
		(state: RootState): CompanyDbModel[] | null => state.companies.companiesList
	);
	const editCompany = companiesList
		? companiesList.find((company) => company.company_id === props.companyEditId)
		: null;
	/** NEW  end */

	const [errorHandleClasses, setErrorHandleClasses] = useState({
		company: '',
		companyAddress: '',
		name: '',
		email: '',
		prefix: '',
		phoneNumber: '',
		industryId: '',
		companyRegNumber: '',
		role: ''
	});

	const getIndustryId = () => {
		const t = companyDropdownPredefinedValues.industry.find(
			(industry) => editCompany?.industry_id === industry.id
		);
		return t?.label || 'null';
	};

	const getIndustryType = () => {
		if (editCompany?.industry_type && typeof editCompany.industry_type === 'object')
			return editCompany.industry_type;
		return {
			value: 'Services',
			label: '0'
		};
	};

	const getCurrency = () => {
		if (editCompany?.currency_symbol && typeof editCompany.currency_symbol === 'object')
			return editCompany.currency_symbol;
		return {
			value: 'GBP',
			label: '£'
		};
	};

	const [companyTypeSubmit, setCompanyTypeSubmit] = useState<CompanyTypeInterface>({
		companyId: editCompany?.company_id || null,
		name: selectedUser?.name || '',
		company: editCompany?.company_name || '',
		prefix: editCompany?.prefix || '',
		phoneNumber: editCompany?.phone_number || '',
		companyType: 'Single Company',
		// industryId: editCompany?.industry_id === 0 ? 0 : editCompany?.industry_id || '',
		industryId: getIndustryId(),
		email: selectedUser?.email || '',
		companyRegNumber: editCompany?.company_reg_number || '',
		companyAddress: editCompany?.company_address || '',
		industryType: getIndustryType(),
		currency: getCurrency(),
		role: editCompany?.role || 'CEO'
	});

	const { frontendRoutes } = environment;
	const [isSetDisplayPrefix, setIsSetDisplayPrefix] = useState<boolean>(false);
	const [displayPrefix, setDisplayPrefix] = useState<boolean>(false);
	const [open, setOpen] = useState<boolean>(false);
	const roles = DUMMY_ARRAY_ROLES;

	const isEmbeded = () => props.embeded;

	const goBack = () => {
		if (props.setCompanyEditId) {
			props.setCompanyEditId(null);
		}

		if (!isEmbeded() || props.goBackToPage) {
			navigate(-1);
		} else if (props.setSwitchToForm) {
			props.setSwitchToForm(false);
		}
	};

	useEffect(() => {
		if (!isSetDisplayPrefix) {
			setIsSetDisplayPrefix(true);
			setDisplayPrefix(true);
			return;
		}
		if (!displayPrefix) {
			setOpen(true);
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [displayPrefix]);

	function getPrefixHandler(event: SelectChangeEvent<string>): void {
		setDisplayPrefix(true);
		setCompanyTypeSubmit((prevState) => ({
			...prevState,
			prefix: event.target.value
		}));
	}
	function nameHandler(event: ChangeEvent<HTMLInputElement>): void {
		setCompanyTypeSubmit((prevState) => ({
			...prevState,
			name: event.target.value
		}));
	}
	function numberHandler(event: ChangeEvent<HTMLInputElement>): void {
		setCompanyTypeSubmit((prevState) => ({
			...prevState,
			phoneNumber: event.target.value
		}));
	}
	function companyHandler(event: ChangeEvent<HTMLInputElement>): void {
		setCompanyTypeSubmit((prevState) => ({
			...prevState,
			company: event.target.value
		}));
		// companyContext.companyNameHandler(event);
	}
	function industryHandler(event: SelectChangeEvent<string>): void {
		setCompanyTypeSubmit((prevState) => ({
			...prevState,
			industryId: event.target.value
		}));
		// companyContext.industryHandler(event);
	}
	function emailHandler(event: SelectChangeEvent<string>): void {
		setCompanyTypeSubmit((prevState) => ({
			...prevState,
			email: event.target.value
		}));
	}
	function companyAddressHandler(event: SelectChangeEvent<string>): void {
		setCompanyTypeSubmit((prevState) => ({
			...prevState,
			companyAddress: event.target.value
		}));
	}
	function industryTypeHandler(event: SelectChangeEvent): void {
		setCompanyTypeSubmit((prevState) => ({
			...prevState,
			industryType: {
				value: event.target.value,
				label: event.target.name
			}
		}));
		// companyContext.industryTypeHandler(event);
	}
	function roleHandler(event: SelectChangeEvent): void {
		setCompanyTypeSubmit((prevState) => ({
			...prevState,
			role: event.target.value
		}));
		// companyContext.roleHandler(event);
	}
	function currencyHandler(event: SelectChangeEvent): void {
		// companyContext.currencyHandler(event);
		setCompanyTypeSubmit((prevState) => ({
			...prevState,
			currency: {
				value: event.target.value,
				label: ''
			}
		}));
	}
	function companyRegNumberHandler(event: ChangeEvent<HTMLInputElement>): void {
		// companyContext.companyRegNumberHandler(event);
		setCompanyTypeSubmit((prevState) => ({
			...prevState,
			companyRegNumber: event.target.value
		}));
	}

	function validateEmail(email: string) {
		return !!String(email)
			.toLowerCase()
			.match(
				/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
			);
	}

	function submitHandler(event: FormEvent): void {
		event.preventDefault();
		console.log('companyTypeSubmit', companyTypeSubmit);
		if (companyTypeSubmit.company === '') {
			setErrorHandleClasses((prevState) => ({
				...prevState,
				company: styles.errorCompany
			}));
		}
		if (companyTypeSubmit.name === '') {
			setErrorHandleClasses((prevState) => ({
				...prevState,
				name: styles.errorName
			}));
		}
		if (companyTypeSubmit.companyAddress === '') {
			setErrorHandleClasses((prevState) => ({
				...prevState,
				companyAddress: styles.errorName
			}));
		}
		if (!validateEmail(companyTypeSubmit.email)) {
			setErrorHandleClasses((prevState) => ({
				...prevState,
				email: styles.errorName
			}));
		}
		if (companyTypeSubmit.prefix === '') {
			setErrorHandleClasses((prevState) => ({
				...prevState,
				prefix: styles.errorPrefix
			}));
		}
		if (companyTypeSubmit.phoneNumber === '') {
			setErrorHandleClasses((prevState) => ({
				...prevState,
				phoneNumber: styles.errorNumber
			}));
		}
		if (companyTypeSubmit.industryId === '') {
			setErrorHandleClasses((prevState) => ({
				...prevState,
				industryId: styles.errorIndustry
			}));
		}
		// if (companyTypeSubmit.companyRegNumber === '') {
		// 	setErrorHandleClasses((prevState) => ({
		// 		...prevState,
		// 		companyRegNumber: styles.errorIndustry
		// 	}));
		// }

		if (
			companyTypeSubmit.company !== '' &&
			companyTypeSubmit.name !== '' &&
			companyTypeSubmit.phoneNumber !== '' &&
			companyTypeSubmit.prefix !== '' &&
			companyTypeSubmit.industryId !== ''
		) {
			const industry = companyDropdownPredefinedValues.industry.find(
				(ind) => companyTypeSubmit.industryId === ind.value
			);
			console.log('FC passed, industry', industry, companyTypeSubmit.industryId);

			if (industry) {
				const payload = { ...companyTypeSubmit, industryId: industry.id as number };

				if (props.companyEditId) {
					dispatch(updateCompany(payload))
						.then(() => {
							if (props.setCompanyEditId) props.setCompanyEditId(null);
							// successs navigate to Manage Subscription page/step
							goBack();
						})
						.catch((error) => {
							// TODO: throw an error/display error modal
							console.log('throwing error');
							console.error(error);
						});
					return;
				}

				dispatch(createCompany(payload))
					.then(() => {
						dispatch(fetchUserData()).then(() => {
							// successs navigate to Manage Subscription page/step
							navigate(frontendRoutes.manageSubscription);
						});
					})
					.catch((error) => {
						// TODO: throw an error/display error modal
						console.log('throwing error');
						console.error(error);
					});
			} else {
				// TODO: throw an error/display error modal
			}
		}
	}

	return (
		// eslint-disable-next-line jsx-a11y/no-static-element-interactions
		<div
			className={[cardStyles.cardsContainer, isEmbeded() ? cardStyles.embed : ''].join(' ')}
			onClick={() =>
				setErrorHandleClasses({
					company: '',
					phoneNumber: '',
					name: '',
					prefix: '',
					industryId: '',
					companyAddress: '',
					email: '',
					companyRegNumber: '',
					role: ''
				})
			}
		>
			<form
				className={[
					cardStyles.form,
					styles.cardForm,
					styles.container,
					isEmbeded() ? styles.embed : ''
				].join(' ')}
				onSubmit={submitHandler}
			>
				{!isEmbeded() && (
					<>
						<div className={['row w-100', styles.noborder].join(' ')}>
							<div className="col-12 col-lg-6">Personal Information:</div>
						</div>
						<div className="row w-100">
							<div className="col-12 col-lg-6">
								<InputElement
									// eslint-disable-next-line react/jsx-no-bind
									changeHandler={nameHandler}
									classNameContainer={errorHandleClasses.name}
									disabled={!!(selectedUser?.name && selectedUser.name !== '')}
									id={props.nameInputId}
									inputValue={companyTypeSubmit.name}
									label={props.nameInputLabel}
									placeholder={props.nameInputPlaceholder}
									type={props.nameInputType}
								/>
							</div>
							<div className="col-12 col-lg-6">
								<InputElement
									// eslint-disable-next-line react/jsx-no-bind
									changeHandler={emailHandler}
									classNameContainer={errorHandleClasses.email}
									disabled={!!(selectedUser?.email && selectedUser.email !== '')}
									id={props.emailInputId}
									inputValue={companyTypeSubmit.email}
									label={props.emailInputLabel}
									placeholder={props.emailInputPlaceholder}
									type={props.emailInputType}
								/>
							</div>
						</div>
					</>
				)}

				{!isEmbeded() && (
					<div className={['row w-100', styles.noborder].join(' ')}>
						<div className="col-12 col-lg-6">Company Information:</div>
					</div>
				)}
				<div className="row w-100">
					<div className="col-12 col-lg-6">
						<InputElement
							// eslint-disable-next-line react/jsx-no-bind
							changeHandler={companyHandler}
							classNameContainer={errorHandleClasses.company}
							disabled={false}
							id={props.companyInputId}
							inputValue={companyTypeSubmit.company}
							label={props.companyInputLabel}
							placeholder={props.companyInputPlaceholder}
							type={props.companyInputType}
						/>
					</div>
					<div className="col-12 col-lg-6">
						<InputElement
							// eslint-disable-next-line react/jsx-no-bind
							changeHandler={companyAddressHandler}
							classNameContainer={errorHandleClasses.companyAddress}
							disabled={false}
							id={props.companyAddressInputId}
							inputValue={companyTypeSubmit.companyAddress}
							label={props.companyAddressInputLabel}
							placeholder={props.companyAddressInputPlaceholder}
							type={props.companyAddressInputType}
						/>
					</div>
				</div>
				<div className="row w-100">
					<div className={['col-2', styles.country].join(' ')}>
						<div className={styles.shortDropdown}>
							{!displayPrefix && (
								<DropdownForPrefix
									// eslint-disable-next-line react/jsx-no-bind
									handleChange={getPrefixHandler}
									id="prefix"
									items={Countries}
									label={props.phonePrefixInputLabel}
									labelInputInline={false}
									open={open}
									value={companyTypeSubmit.prefix}
								/>
							)}
							{displayPrefix && (
								<div className={styles.inputAsDropdown}>
									<InputElement
										changeHandler={() => {
											setDisplayPrefix(false);
										}}
										classNameContainer={errorHandleClasses.prefix}
										clickHandler={() => {
											setDisplayPrefix(false);
										}}
										disabled={false}
										id="prefix"
										inputValue={companyTypeSubmit.prefix}
										label={props.phonePrefixInputLabel}
										placeholder="+44"
										type="text"
									/>
								</div>
							)}
						</div>
					</div>
					<div className={['col-10 col-lg-4', styles.phone].join(' ')}>
						<InputElement
							// eslint-disable-next-line react/jsx-no-bind
							changeHandler={numberHandler}
							classNameContainer={errorHandleClasses.phoneNumber}
							disabled={false}
							id={props.phoneNumberInputId}
							inputValue={companyTypeSubmit.phoneNumber !== '' ? companyTypeSubmit.phoneNumber : ''}
							label={props.phoneNumberInputLabel}
							placeholder={props.phoneNumberInputPlaceholder}
							type={props.phoneNumberInputType}
						/>
					</div>
					<div className="col-12 col-lg-6">
						<Dropdown
							// eslint-disable-next-line react/jsx-no-bind
							classNameContainer={errorHandleClasses.industryId}
							// eslint-disable-next-line react/jsx-no-bind
							handleChange={industryHandler}
							id={props.industryInputId}
							items={companyDropdownPredefinedValues.industry}
							label={props.industryInputLabel}
							labelInputInline={false}
							// value={companyContext.industry as string}
							// value={getIndustryTypeId()}
							value={companyTypeSubmit.industryId as string}
						/>
					</div>
					<div className="col-12 col-lg-6">
						<Dropdown
							// eslint-disable-next-line react/jsx-no-bind
							handleChange={industryTypeHandler}
							id={props.industryTypeInputId}
							items={companyDropdownPredefinedValues.industryType}
							label={props.industryTypeInputLabel}
							labelInputInline={false}
							value={(companyTypeSubmit.industryType as any).value as string}
							// value="All Other"
						/>
					</div>
					<div className="col-12 col-lg-6">
						<Dropdown
							// eslint-disable-next-line react/jsx-no-bind
							handleChange={currencyHandler}
							id={props.currencyInputId}
							items={companyDropdownPredefinedValues.currency}
							label={props.currencyInputLabel}
							labelInputInline={false}
							value={companyTypeSubmit.currency.value as string}
						/>
					</div>
					<div
						className="col-12 col-lg-6"
						style={{
							marginTop: '10px'
						}}
					>
						<InputElement
							// eslint-disable-next-line react/jsx-no-bind
							changeHandler={companyRegNumberHandler}
							classNameContainer={errorHandleClasses.companyRegNumber}
							disabled={false}
							id={props.companyRegNumberId}
							inputValue={companyTypeSubmit.companyRegNumber}
							label={props.companyRegNumberLabel}
							placeholder={props.companyRegNumberPlaceholder}
							type={props.companyRegNumberType}
						/>
					</div>
					<div
						className="col-12 col-lg-6"
						style={{
							marginTop: '10px'
						}}
					>
						<Dropdown
							// eslint-disable-next-line react/jsx-no-bind
							classNameContainer={errorHandleClasses.role}
							// eslint-disable-next-line react/jsx-no-bind
							handleChange={roleHandler}
							id={props.roleInputId}
							items={roles}
							label={props.roleInputLabel}
							labelInputInline={false}
							value={companyTypeSubmit.role || 'CEO'}
						/>
					</div>
				</div>
				<div
					className={['row', styles.cards].join(' ')}
					style={{
						display: 'none'
					}}
				/>
				{/* <div className="row">
					<button type="button" onClick={() => goBack()} className={styles.goBackBtn}>
						Go back
					</button>
					<button className={styles.button} id={props.submitButtonId} type="submit">
						{props.svg} {props.submitButtonValue}
					</button>
				</div> */}
				<div
					style={{
						display: 'flex',
						width: '100%',
						marginTop: '40px',
						padding: '12px',
						justifyContent: 'space-between',
						alignItems: 'center'
					}}
				>
					{editCompany && <DeleteCompany companyData={editCompany} />}
					{!editCompany && <div />}

					<div className={inputStyles.buttonContainer} style={{ marginTop: '0px' }}>
						<button className={globalStyle.cancelButton} onClick={() => goBack()} type="reset">
							<span>Cancel</span>
						</button>
						<button
							id={props.submitButtonId}
							className={globalStyle.submitButton}
							// onClick={submitHandler}
							type="submit"
						>
							{editCompany && <span>Save changes</span>}
							{!editCompany && <span>Save</span>}
						</button>
					</div>
				</div>
			</form>
		</div>
	);
};

export default ChooseCompanyTypeForm;
