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

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

import InternalPagesAPI from "@app/modules/Rulesets/api/InternalPages";

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

const ruleID = "PageReferrers";

export default function PageReferrers({id = ruleID}) {
	const { loading, error, response, getPages } = InternalPagesAPI();
	const dispatch = useDispatch();
	const rule = useSelector((state) =>
		state.ruleSets.find((rule) => rule.id === id),
	);
	const [internalPageReferrer, setInternalPageReferrer] = useState(
		rule.config?.args?.url || "",
	);
	useEffect(() => {
		getPages();
	}, []);

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

	return (
		<div>
			<Label title={__("Internal Page Referral", "dxp")} />

			<Select
				name="page_referrer"
				value={internalPageReferrer}
				onChange={(e) => setInternalPageReferrer(e.target.value)}
			>
				<option value="">{__("Select a page referral", "dxp")}</option>
				{loading && <option>{__("Loading...", "dxp")}</option>}
				{error && <option>{error}</option>}
				{response &&
					response.map((page, index) => (
						<option key={index} value={page.link}>
							{page.name}
						</option>
					))}
			</Select>
		</div>
	);
}
