/**
 * LoggedIn form component.
 *
 * @returns {JSX.Element}
 */
// State action for update/set rule config.
import {__} from "@wordpress/i18n";
import {useDispatch, useSelector} from "react-redux";
import {useEffect, useState} from "react";

// State action for update/set rule config.
import {setRuleConfig} from "@app/modules/PersonaForm/store/PersonaFormStore";

// Components.
import Label from "@app/components/Label";
import Input from "@app/components/Input";

const ruleID = "DynamicLink";

export default function DynamicLink({id = ruleID}) {
	const dispatch = useDispatch();
	const rule = useSelector((state) =>
		state.ruleSets.find((rule) => rule.id === id),
	);

	const [paramKey, setParamKey] = useState(rule.config?.args?.key || "");
	const [paramValue, setParamValue] = useState(rule.config?.args?.value || "");

	useEffect(() => {
		dispatch(
			setRuleConfig({
				id: id,
				config: {
					ruleType: "dynamic_link",
					args: {
						key: paramKey,
						value: paramValue,
						id: ruleID,
					},
				},
			}),
		);
	}, [paramKey, paramValue]);

	return (
		<div>
			<div className="dxp-mb-4">
				<Label title={__("Parameter Name", "dxp")} />
				<Input
					type="text"
					variant="small"
					value={paramKey}
					placeholder={__("eg: utm_campaign", "dxp")}
					onChange={(e) => setParamKey(e.target.value)}
				/>
			</div>
			<div>
				<Label title={__("Parameter Value", "dxp")} />
				<Input
					type="text"
					variant="small"
					value={paramValue}
					placeholder={__("Add an optional value", "dxp")}
					onChange={(e) => setParamValue(e.target.value)}
				/>
			</div>
			{paramKey && (
				<div>
					{__("Your current config will target the following link:", "dxp")}
					<pre>
						<code>
							?{paramKey}={paramValue}
						</code>
					</pre>
					<pre className="dxp-text-xs">
						EX.: {window.location.origin}?{paramKey}={paramValue}
					</pre>
				</div>
			)}
		</div>
	);
}
