import { memo, useCallback } from "react";

import type { ILanguage, ISite } from "@ax/types";

import * as S from "./style";

const MultiCheckSelectGroup = (props: IMultiCheckSelectGroupProps) => {
	const {
		value,
		onChange,
		site,
		elements,
		note,
		disabled,
		error,
		handleValidation,
		languages,
		contentLanguages,
		contentType = "data",
	} = props;

	const completedValue = value ?? {};

	const handleElementChange = useCallback(
		(elementKey: string, val: any[]) => {
			const newValue = { ...completedValue };
			if (val.length > 0) {
				newValue[elementKey] = val;
			} else {
				delete newValue[elementKey];
			}

			onChange(newValue);
			error && handleValidation && handleValidation(newValue);
		},
		[completedValue, onChange, error, handleValidation],
	);

	return (
		<>
			{note && <S.StyledNoteField value={{ text: note }} />}
			{elements?.map((element) => {
				const { placeholder, source, key, mandatory, isGlobal, allOption } = element;

				const val = (completedValue[key] as any[]) ?? [];
				const fromSite = isGlobal ? null : site;

				return (
					<S.StyledMultiCheckSelect
						key={key}
						mandatory={mandatory}
						value={val}
						onChange={(newVal: string | any[]) => handleElementChange(key, newVal as any[])}
						site={fromSite}
						placeholder={placeholder}
						source={source}
						disabled={disabled}
						contentType={contentType}
						languages={languages}
						contentLanguages={contentLanguages}
						allOption={allOption}
					/>
				);
			})}
		</>
	);
};

interface IElement {
	key: string;
	placeholder: string;
	source: string;
	mandatory?: boolean;
	allOption?: boolean;
	isGlobal?: boolean;
}

export interface IMultiCheckSelectGroupProps {
	value: Record<string, unknown[]> | Record<string, never> | undefined | null;
	elements: IElement[];
	onChange: (value: Record<string, unknown[]> | Record<string, never>) => void;
	site?: ISite;
	note?: string;
	error?: boolean;
	handleValidation?: (value: Record<string, unknown>, validators?: Record<string, unknown>) => void;
	disabled?: boolean;
	contentType: "data" | "formCategory";
	languages: ILanguage[];
	contentLanguages?: "current" | "all" | string[];
}

export default memo(MultiCheckSelectGroup);
