import React, { useEffect, useState } from "react";
import {
	_CONTENTGATE_DASHBOARD_,
	ConditionOption,
	ConditionType,
	ContentTarget,
	GroupCondition,
	LogicGroup,
	Rule,
	ValueCondition,
} from "../../../types";
import { MoveDown, MoveRight, Plus, Trash2, X } from "lucide-react";
import { __ } from "@wordpress/i18n";
import ConditionFieldDropdown from "../dropdowns/ConditionFieldDropdown";
import ConditionRow from "./ConditionRow";
import AccessControlSection from "./AccessControlSection";
import AdvancedLogicGates from "./AdvancedLogicGates";
import { Button } from "../../ui/Button";
import { updateConditionOpenStatus } from "../../../api/restriction.api";

type Props = {
	group: LogicGroup;
	onGroupUpdate: (updatedGroup: LogicGroup) => void;
	onGroupRemove: () => void;
	isNested: boolean;
	accessControl: string;
	onAccessControlChange: (newAccessControl: string) => void;
	contentTargets: ContentTarget[];
	onContentTargetsChange: (newContentTargets: ContentTarget[]) => void;
	rule: Rule;
};

const getConditionType = (conditionType: string) => {
	const typeMap: Record<string, string> = {
		roles: "multiselect",
		user_state: "checkbox",
	};
	return typeMap[conditionType] || "text";
};

const RuleCondition = ({
	group,
	onGroupUpdate,
	onGroupRemove,
	isNested,
	accessControl,
	onAccessControlChange,
	contentTargets,
	onContentTargetsChange,
	rule,
}: Props) => {
	const [conditions, setConditions] = useState<ConditionType[]>([]);
	const [logicGate, setLogicGate] = useState(group.logic_gate || "AND");
	const isAdvancedLogicEnabled = Boolean(
		rule?.is_advanced_logic_enabled || false,
	);
	const [isConditionOpen, setIsConditionOpen] = useState(false);

	useEffect(() => {
		if (group.conditions && group.conditions.length > 0) {
			const initialConditions: ConditionType[] = group.conditions.map(
				(cond) => {
					if (cond.type === "group") {
						return {
							type: "group",
							id: cond.id,
							group: cond,
						};
					} else {
						let conditionValue = cond.value;
						const conditionType = getConditionType(cond.type);

						if (cond.type === "user_state") {
							if (Array.isArray(conditionValue)) {
								conditionValue = conditionValue[0] || "";
							}
							if (conditionValue === "logged_in") {
								conditionValue = "logged-in";
							} else if (conditionValue === "logged_out") {
								conditionValue = "logged-out";
							}
						} else if (!conditionValue) {
							conditionValue =
								conditionType === "multiselect" ? [] : "";
						}

						return {
							type: "condition",
							id: cond.id || `x${Date.now()}`,
							value: cond.type,
							label: cond.type,
							inputType: conditionType,
							operator: "is",
							conditionValue: conditionValue,
						};
					}
				},
			);

			setConditions(initialConditions);
		} else {
			setConditions([]);
		}

		if (!isAdvancedLogicEnabled) {
			setLogicGate("AND");
		} else if (group.logic_gate) {
			setLogicGate(group.logic_gate);
		}
	}, [group.id, isAdvancedLogicEnabled]);

	// Force logic gate to AND when advanced logic is disabled (in case it changes dynamically)
	useEffect(() => {
		if (!isAdvancedLogicEnabled && logicGate !== "AND") {
			setLogicGate("AND");
		}
	}, [isAdvancedLogicEnabled, logicGate]);

	const handleAfterConditionSelection = (option: ConditionOption) => {
		let initialValue: any = "";
		if (option.type === "multiselect") {
			initialValue = [];
		} else if (
			option.type === "checkbox" &&
			option.value !== "user_state"
		) {
			initialValue = [];
		}

		const newCondition: ConditionType = {
			type: "condition",
			id: `x${Date.now()}`,
			value: option.value,
			label: option.label,
			inputType: option.type,
			operator: "is",
			conditionValue: initialValue,
		};
		setConditions([...conditions, newCondition]);
	};

	const handleConditionUpdate = (updatedCondition: ValueCondition) => {
		setConditions(
			conditions.map((cond) =>
				cond.id === updatedCondition.id ? updatedCondition : cond,
			),
		);
	};

	const handleConditionRemove = (conditionId: string) => {
		setConditions(conditions.filter((cond) => cond.id !== conditionId));
	};

	const handleAddGroup = () => {
		const groupId = `x${Date.now()}`;
		const newGroup: GroupCondition = {
			type: "group",
			id: groupId,
			group: {
				id: groupId,
				type: "group",
				logic_gate: "AND",
				conditions: [],
			},
		};
		setConditions([...conditions, newGroup]);
	};

	const handleGroupUpdate = (groupId: string, updatedGroup: LogicGroup) => {
		setConditions(
			conditions.map((cond) =>
				cond.id === groupId ? { ...cond, group: updatedGroup } : cond,
			),
		);
	};

	const handleGroupRemove = (groupId: string) => {
		setConditions(conditions.filter((cond) => cond.id !== groupId));
	};

	// Notify parent of changes whenever conditions or logicGate changes
	useEffect(() => {
		// Build the updated group structure
		// Note: Flattening is now handled on the backend API side when advanced logic is disabled
		const conditionsToSerialize = conditions.map((cond) => {
			if (cond.type === "group") {
				return cond.group;
			} else {
				let conditionValue: string | string[] | null =
					cond.conditionValue;
				conditionValue = Array.isArray(conditionValue)
					? conditionValue
					: conditionValue
						? [conditionValue]
						: [];
				if (cond.value === "user_state") {
					conditionValue = Array.isArray(conditionValue)
						? conditionValue[0] || ""
						: conditionValue || "";
				} else if (
					cond.inputType === "multiselect" ||
					cond.inputType === "checkbox"
				) {
					conditionValue = Array.isArray(conditionValue)
						? conditionValue
						: conditionValue
							? [conditionValue]
							: [];
				} else if (
					cond.operator === "empty" ||
					cond.operator === "not empty"
				) {
					conditionValue = null;
				}

				return {
					type: cond.value,
					id: cond.id,
					value: conditionValue,
				};
			}
		});

		const updatedGroup = {
			id: group.id,
			type: "group",
			logic_gate: isAdvancedLogicEnabled ? logicGate : "AND", // Force AND when advanced logic is disabled
			conditions: conditionsToSerialize,
		};
		onGroupUpdate(updatedGroup);
	}, [conditions, logicGate, group.id, isAdvancedLogicEnabled]);

	useEffect(() => {
		if (_CONTENTGATE_DASHBOARD_.conditionOpen && rule.is_default) {
			console.log(_CONTENTGATE_DASHBOARD_.conditionOpen);
			console.log(rule.is_default);
			setIsConditionOpen(true);
			updateConditionOpenStatus();
		}
	}, []);

	return (
		<>
			{isAdvancedLogicEnabled && (
				<AdvancedLogicGates
					logicGate={logicGate}
					onLogicGateChange={setLogicGate}
				/>
			)}
			<div className="flex gap-2 items-center xl:items-start flex-col xl:flex-row">
				<div className="max-w-full xl:max-w-[480px] xl1:max-w-[560px] w-full">
					{conditions.length > 0 && (
						<div className="p-6 pr-[14px] border rounded-md relative flex flex-col gap-6">
							<span className="uppercase border rounded-[4px] px-3 py-0 h-6 content-center absolute top-[-15px] left-[-15px] bg-white font-medium">
								{__("IF", "contentgate")}
							</span>

							<div className="contentgate-conditions-list  flex flex-col gap-[52px]">
								{conditions.map((condition, index) => {
									const showLogicGate = index > 0;
									if (condition.type === "group") {
										// Only show nested groups when advanced logic is enabled
										if (!isAdvancedLogicEnabled) {
											return null;
										}
										return (
											<div
												key={condition.id}
												className="contentgate-condition-wrapper flex items-center gap-3 relative"
											>
												{showLogicGate && (
													<div
														className={`contentgate-condition-logic-gate-wrapper contentgate-logic-group-rule-${logicGate} ${
															conditions.length ===
															1
																? "contentgate-single-condition"
																: ""
														} uppercase border rounded-[4px] px-3 py-0 h-6 content-center absolute top-[-40px] left-[-39px] bg-white font-medium`}
													>
														<div
															className={`contentgate-condition-logic-gate-button contentgate-sub-logic-group-rule-${logicGate}`}
														>
															{logicGate}
														</div>
													</div>
												)}
												<div className="py-4 rounded flex-1">
													<RuleCondition
														group={condition.group}
														onGroupUpdate={(
															updatedGroup,
														) =>
															handleGroupUpdate(
																condition.id,
																updatedGroup,
															)
														}
														onGroupRemove={() =>
															handleGroupRemove(
																condition.id,
															)
														}
														isNested={true}
														rule={rule}
														accessControl={
															accessControl
														}
														onAccessControlChange={
															onAccessControlChange
														}
														contentTargets={
															contentTargets
														}
														onContentTargetsChange={
															onContentTargetsChange
														}
													/>
												</div>
												<Button
													type="button"
													size="lg"
													className="contentgate-target-remove h-5 text-[#505050] hover:text-destructive-500 py-1 px-0 bg-transparent"
													onClick={() =>
														handleGroupRemove(
															condition.id,
														)
													}
													aria-label={__(
														"Remove",
														"contentgate",
													)}
												>
													<Trash2 />
												</Button>
											</div>
										);
									} else {
										return (
											<div
												key={condition.id}
												className="contentgate-condition-wrapper flex items-center gap-3 relative"
											>
												{showLogicGate && (
													<div
														className={`contentgate-condition-logic-gate-wrapper contentgate-logic-group-rule-${logicGate} ${
															conditions.length ===
															1
																? "contentgate-single-condition"
																: ""
														} uppercase border rounded-[4px] px-3 py-0 h-6 content-center absolute top-[-40px] left-[-39px] bg-white font-medium`}
													>
														<div
															className={`contentgate-condition-logic-gate-button contentgate-sub-logic-group-rule-${logicGate}`}
														>
															{logicGate}
														</div>
													</div>
												)}
												<ConditionRow
													condition={condition}
													onUpdate={
														handleConditionUpdate
													}
													existingConditions={
														conditions
													}
												/>
												<Button
													type="button"
													size="lg"
													className="contentgate-target-remove h-5 text-[#505050] hover:text-destructive-500 py-1 px-0 bg-transparent"
													onClick={() =>
														handleConditionRemove(
															condition.id,
														)
													}
													aria-label={__(
														"Remove",
														"contentgate",
													)}
												>
													<Trash2 />
												</Button>
											</div>
										);
									}
								})}
							</div>
							{conditions.length > 0 && (
								<div className="flex item-center gap-6">
									<ConditionFieldDropdown
										trigger={
											<button className="bg-[#F5F6FE] text-primary text-sm flex items-center gap-2 rounded-md px-3 py-1.5 hover:bg-[#F5F6FE]/80 focus:outline-none disabled:opacity-50 disabled:pointer-events-none">
												<Plus size={14} />
												<span className="font-semibold">
													{__(
														"Condition",
														"contentgate",
													)}
												</span>
											</button>
										}
										onSelect={handleAfterConditionSelection}
										existingConditions={conditions}
									/>

									{isAdvancedLogicEnabled && (
										<Button
											type="button"
											onClick={handleAddGroup}
											className="bg-secondary text-gray-600 px-3 py-1.5 text-sm"
										>
											<Plus size={14} />
											<span className="font-semibold">
												{__("Group", "contentgate")}
											</span>
										</Button>
									)}
								</div>
							)}

							{rule && rule?.is_global && (
								<div className="contentgate-condition-wrapper contentgate-global-migration-notice">
									<p className="contentgate-notice-wrap">
										<span style={{ fontWeight: "bold" }}>
											Note:
										</span>
										{__(
											" For partial content restriction with the above condition, use the ",
											"contentgate",
										)}
										{true &&
											__(
												"— Content Restriction block instead",
												"contentgate",
											)}
										.
									</p>
								</div>
							)}
						</div>
					)}
				</div>

				{!isNested && conditions.length > 0 && accessControl && (
					<>
						<MoveRight
							size={20}
							className="mt-[22px] hidden xl:block text-[#9CA3AF] sticky top-[140px]"
						/>
						<MoveDown
							size={20}
							className="block xl:hidden text-[#9CA3AF]"
						/>
						<AccessControlSection
							accessControl={accessControl}
							onAccessControlChange={onAccessControlChange}
							contentTargets={contentTargets}
							onContentTargetsChange={onContentTargetsChange}
							rule={rule}
							conditions={conditions}
						/>
					</>
				)}
			</div>

			{conditions.length === 0 && (
				<div className="flex item-center gap-6">
					<ConditionFieldDropdown
						trigger={
							<button className="bg-secondary text-primary text-sm flex items-center gap-2 rounded-md px-3 py-1.5 hover:bg-secondary/80 focus:outline-none disabled:opacity-50 disabled:pointer-events-none">
								<Plus size={14} />
								<span className="font-semibold">
									{__("Condition", "contentgate")}
								</span>
							</button>
						}
						onSelect={handleAfterConditionSelection}
						existingConditions={conditions}
						open={isConditionOpen}
						onOpenChange={setIsConditionOpen}
					/>

					{isAdvancedLogicEnabled && (
						<Button
							type="button"
							onClick={handleAddGroup}
							className="bg-secondary text-gray-600 px-3 py-1.5 text-sm"
						>
							<Plus size={14} />
							<span className="font-semibold">
								{__("Group", "contentgate")}
							</span>
						</Button>
					)}
				</div>
			)}
		</>
	);
};

export default RuleCondition;
