/**
 * LoggedIn form component.
 *
 * @returns {JSX.Element}
 */
import { useDispatch, useSelector } from "react-redux";
import { useEffect, useState } from "react";
import { __ } from "@wordpress/i18n";

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

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

const ruleID = "CustomReferrers";

export default function CustomReferrers({id = ruleID}) {
	const dispatch = useDispatch();
	const rule = useSelector((state) =>
		state.ruleSets.find((rule) => rule.id === id),
	);
	const [option, setOption] = useState(rule.config?.args?.operator || "exact");
	const [link, setLink] = useState(rule.config?.args?.url || "");

	useEffect(() => {
		dispatch(
			setRuleConfig({
				id: id,
				config: {
					ruleType: "referrer",
					args: {
						operator: option,
						url: link,
						id: ruleID,
					},
				},
			}),
		);
	}, [option, link]);

	return (
		<div>
			<Label title={__("Referral website address", "dxp")} />
			<div className="dxp-mb-4">
				<Select value={option} onChange={(e) => setOption(e.target.value)}>
					{options.map((option, index) => (
						<option key={index} value={option.value}>
							{option.label}
						</option>
					))}
				</Select>
			</div>
			<div>
				<Input
					type="text"
					variant="small"
					value={link}
					placeholder={__("Custom Referral Website", "dxp")}
					onChange={(e) => setLink(e.target.value)}
				/>
				<p>{__("Enter the desired website referral url.", "dxp")}</p>
			</div>
		</div>
	);
}

const options = [
	{
		label: __("Website Is Exactly"),
		value: "exact",
	},
	{
		label: __("Website address contains the following string"),
		value: "contains",
	},
	{
		label: __("Website Is Different From"),
		value: "opposite",
	},
	{
		label: __("Website address does NOT contain the following string"),
		value: "not_contain",
	},
];
