import { useEffect, useRef, useState } from "react";

import { FieldsBehavior, NoteField } from "@ax/components";

import type { IAnalyticsFieldProps, IState } from "..";
import * as S from "../style";
import { DimensionsGroup, DimensionsSelection } from "./atoms";

const initialState: IState = {
	contentSelect: "",
	groupSelect: "",
	dimensionsSelect: [],
	values: {},
};

const PageAnalytics = (props: IAnalyticsFieldProps): JSX.Element => {
	const { value, onChange, analytics, disabled } = props;

	const [state, setState] = useState<IState>(value || initialState);

	const isMountRef = useRef(true);

	// biome-ignore lint/correctness/useExhaustiveDependencies: onChange is not memoized by parent, adding it causes infinite loop
	useEffect(() => {
		if (isMountRef.current) {
			isMountRef.current = false;
			return;
		}
		onChange?.(state);
	}, [state]);

	const handleContentSelect = (contentSelect: string) => {
		setState({ ...initialState, contentSelect });
	};

	const handleGroupSelect = (groupSelect: string) => {
		setState((prev: IState) => ({ ...prev, groupSelect, values: {} }));
	};

	const handleDimensionsSelect = (selection: string[]) => {
		const values: Record<string, string> = {};
		let dimensionsSelect = selection;

		if (selection.includes("all")) {
			dimensionsSelect = analytics.dimensions?.map((dimension) => dimension.name) ?? [];
		}

		dimensionsSelect.forEach((dimension) => {
			values[dimension] = state.values[dimension];
		});
		setState((prev: IState) => ({ ...prev, dimensionsSelect, values }));
	};

	const setDimension = (value: Record<string, string>) => {
		setState((prev: IState) => ({ ...prev, values: { ...prev.values, ...value } }));
	};

	const contentOptions = [
		{
			label: "Dimensions Group",
			value: "group",
		},
		{
			label: "Individual Dimensions",
			value: "individual",
		},
	];

	const groupOptions =
		analytics.groups?.map((group) => ({
			label: group.name,
			value: group.name,
		})) ?? [];

	const noteText = (
		<>
			Select <strong>Dimension Group</strong> if you want to select one of the groups you created in the global settings
			(based on the page content).
			<br />
			<br />
			Select <strong>Individual Dimensions</strong> if you want to select the dimensions to track manually.
		</>
	);

	const isGroup = state.contentSelect === "group";
	const isIndividual = state.contentSelect === "individual";

	const dimensionOptions = [
		{
			name: "all",
			value: "all",
			title: "Select All",
		},
		...(analytics.dimensions?.map((dimension) => ({
			name: dimension.name,
			value: dimension.name,
			title: dimension.name,
		})) ?? []),
	];

	return (
		<>
			<NoteField value={{ text: noteText }} />
			<S.FieldWrapper>
				<FieldsBehavior
					title="Content Dimension"
					fieldType="Select"
					options={contentOptions}
					value={state.contentSelect}
					onChange={handleContentSelect}
					placeholder="Select Dimensions Options"
					disabled={disabled}
				/>
			</S.FieldWrapper>
			{isGroup && (
				<>
					<FieldsBehavior
						title="Select Group"
						fieldType="Select"
						options={groupOptions}
						value={state.groupSelect}
						onChange={handleGroupSelect}
						placeholder="Select Group"
						disabled={disabled}
					/>
					{!!state.groupSelect && <DimensionsGroup {...{ analytics, state, setDimension, disabled }} />}
				</>
			)}
			{isIndividual && (
				<>
					<FieldsBehavior
						title="Select Dimensions"
						fieldType="MultiCheckSelect"
						options={dimensionOptions}
						value={state.dimensionsSelect}
						onChange={handleDimensionsSelect}
						selectAllOption="all"
						placeholder="Select Dimensions"
						disabled={disabled}
						floating
					/>
					{state.dimensionsSelect.length > 0 && (
						<DimensionsSelection {...{ analytics, state, setDimension, disabled }} />
					)}
				</>
			)}
		</>
	);
};

export default PageAnalytics;
