import { memo, useCallback } from "react";

import { FieldsBehavior, TextField, Wysiwyg } from "@ax/components";
import type { IHeadingField, ISelectOption, ISite } from "@ax/types";

import * as S from "./style";

const HeadingField = (props: IHeadingFieldProps): JSX.Element => {
	const { value, onChange, options, showAdvanced, default: defaultValue, toolbar = false, title, site } = props;

	const contentValue = value?.content ?? defaultValue?.content ?? "";
	const tagValue = value?.tag ?? defaultValue?.tag ?? "";

	const handleChange = useCallback(
		(newValue: string) => {
			onChange({ content: newValue, tag: tagValue });
		},
		[onChange, tagValue],
	);

	const handleSelectChange = useCallback(
		(newValue: string) => {
			onChange({ content: contentValue, tag: newValue });
		},
		[onChange, contentValue],
	);

	return (
		<>
			{toolbar ? (
				<Wysiwyg site={site} inline={true} value={contentValue} onChange={handleChange} />
			) : (
				<TextField value={contentValue} onChange={handleChange} />
			)}
			{showAdvanced && (
				<S.AdvancedWrapper data-testid="text-field-advanced-wrapper">
					<FieldsBehavior fieldType="Select" options={options} value={tagValue} onChange={handleSelectChange} />
				</S.AdvancedWrapper>
			)}
		</>
	);
};

interface IHeadingFieldProps {
	value: IHeadingField;
	title: string;
	onChange: (value: IHeadingField) => void;
	options: ISelectOption[];
	showAdvanced: boolean;
	default: IHeadingField;
	site: ISite;
	toolbar?: boolean;
}

export default memo(HeadingField);
