import { useEffect, useState } from "react";

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

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

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

	const initialState = {
		dimensionsSelect: [],
		values: {},
	};

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

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

	const templateDimensions = getTemplateDimensions(analytics.groups, template);

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

		if (selection.includes("all")) {
			dimensionsSelect = dimensionOptions.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 dimensionOptions = [
		{
			name: "all",
			value: "all",
			title: "Select All",
		},
	];
	analytics.dimensions?.forEach((dimension) => {
		if (!templateDimensions.includes(dimension.name)) {
			const option = {
				name: dimension.name,
				value: dimension.name,
				title: dimension.name,
			};
			dimensionOptions.push(option);
		}
	});

	return (
		<>
			<TemplateDimensions dimensionNames={templateDimensions} {...{ analytics, state, setDimension, disabled }} />
			{dimensionOptions.length > 1 && (
				<>
					<S.FieldsDivider />
					<FieldsBehavior
						title="Add More Dimensions (Optional)"
						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 StructuredDataAnalytics;
