import React, { useState } from "react";
import { useModal, usePermission } from "@ax/hooks";
import { trimText } from "@ax/helpers";
import { ActionMenu, HiddenField, Icon } from "@ax/components";
import { FormContent, ISite } from "@ax/types";

import FormModal from "./FormModal";

import * as S from "./style";

const FormContainer = (props: IFormContainerProps): JSX.Element => {
	const { value, onChange, goTo, title, disabled, editorID, className, site, formCategories } = props;

	const { title: formTitle } = value || { title: "" };

	const isEmpty = !value;

	const { isOpen, toggleModal } = useModal();
	const [selectedForm, setSelectedForm] = useState<FormContent | null>(value || null);

	const addFormPermission = site ? "forms.addFormsToPage" : "global.forms.addFormsToPage";
	const overwriteFormPermission = site ? "forms.overwriteDataForms" : "global.forms.overwriteDataForms";
	const isAllowedToAddForm = usePermission(addFormPermission);
	const isAllowedToOverwriteForm = usePermission(overwriteFormPermission);

	const handleClick = () => {
		if (!disabled && value?.editorID && isAllowedToOverwriteForm) {
			goTo(value.editorID);
		}
	};

	const handleSelectForm = () => {
		if (selectedForm) {
			onChange(selectedForm);
			isOpen && toggleModal();
		}
	};

	const actionMenuOptions = isAllowedToAddForm
		? [
				{
					label: "replace",
					icon: "change",
					action: toggleModal,
				},
			]
		: [];

	return (
		<>
			{isEmpty ? (
				<HiddenField title={title} showField={toggleModal} disabled={!isAllowedToAddForm} hasMultipleOptions={true} />
			) : (
				<S.Component
					disabled={disabled || !isAllowedToOverwriteForm}
					className={`editorId-${editorID} ${className}`}
					onClick={handleClick}
					data-testid="form-container"
				>
					<S.IconWrapper data-testid="icon-wrapper">
						<Icon name="form" />
					</S.IconWrapper>
					<S.Title disabled={disabled || (!isAllowedToOverwriteForm && !isAllowedToAddForm)}>
						{trimText(formTitle, 25)}
					</S.Title>
					<S.HiddenButtonsWrapper>
						<ActionMenu options={actionMenuOptions} icon="more" />
					</S.HiddenButtonsWrapper>
				</S.Component>
			)}
			{isOpen && (
				<FormModal
					isOpen={isOpen}
					toggleModal={toggleModal}
					site={site?.id || null}
					selectedForm={selectedForm}
					setSelectedForm={setSelectedForm}
					selectForm={handleSelectForm}
					categories={formCategories}
				/>
			)}
		</>
	);
};

export interface IFormContainerProps {
	value?: FormContent | null;
	onChange(value: FormContent): void;
	goTo(editorID: number): void;
	disabled?: boolean;
	editorID: number;
	className?: string;
	title: string;
	site: ISite | null;
	formCategories?: string[];
}

export default FormContainer;
