import React, {useEffect, useReducer, useRef, useState} from "react";
import localizeSettings from "./localizeSettings";
import {__} from "@wordpress/i18n";
import {createPortal} from "react-dom";
import DisplayShopLabelTooltip from "../components/DisplayShopLabelTooltip";
import DisplayShopLabelNotice from "../components/DisplayShopLabelNotice";
import SchemaConditionTooltip from "../components/SchemaConditionTooltip";
import ProductConditionTooltip from "../components/ProductConditionTooltip";
import LockIcon from "../components/LockIcon";
import {FreemiusOverlay} from "../components/FreemiusOverlay";

const {conditions, globalSettings} = localizeSettings;

type State = {
	hulk_woo_pcm_productCondition: string;
	hulk_woo_pcm_productConditionCustom: string;
	hulk_woo_pcm_productConditionCustomGroup: string;
	hulk_woo_pcm_productConditionLabel: string;
	hulk_woo_pcm_productConditionShopLabel: string;
};

type Action = Partial<State>;

const ProductQuickEditMetaSettings = () => {
	const elementRef = useRef<HTMLDivElement | null>(null);
	const [count, setCount] = useState(0);
	const [settings, setSettings] = useState<Action>({});

	useEffect(() => {
		const $ = (window as any).jQuery;

		function handler(this: any) {
			const elementTr = this as HTMLTableRowElement;
			elementRef.current = elementTr.querySelector(
				"#hulk_woo_pcm_settings",
			);

			setCount((prevState) => prevState + 1);

			if (elementTr.classList.contains("quick-edit-row")) {
				const postId = elementTr
					.getAttribute("id")
					?.replace("post-", "")
					.replace("edit-", "");
				const inlineData = elementTr
					.closest(".wp-list-table")
					?.querySelector(
						`[id='post-${postId}'] .hulk_woo_pcm_inline_data`,
					);
				if (!inlineData) {
					return;
				}
				setSettings({
					hulk_woo_pcm_productCondition:
						inlineData.getAttribute(
							"data-hulk_woo_pcm_productCondition",
						) ?? "",
					hulk_woo_pcm_productConditionCustom:
						inlineData.getAttribute(
							"data-hulk_woo_pcm_productConditionCustom",
						) ?? "",
					hulk_woo_pcm_productConditionCustomGroup:
						inlineData.getAttribute(
							"data-hulk_woo_pcm_productConditionCustomGroup",
						) ?? "",
					hulk_woo_pcm_productConditionLabel:
						inlineData.getAttribute(
							"data-hulk_woo_pcm_productConditionLabel",
						) ?? "",
					hulk_woo_pcm_productConditionShopLabel:
						inlineData.getAttribute(
							"data-hulk_woo_pcm_productConditionShopLabel",
						) ?? "",
				});
			} else {
				setSettings({
					hulk_woo_pcm_productCondition: "",
					hulk_woo_pcm_productConditionCustom: "",
					hulk_woo_pcm_productConditionCustomGroup: "",
					hulk_woo_pcm_productConditionLabel: "",
					hulk_woo_pcm_productConditionShopLabel: "",
				});
			}
		}

		$(document).on("focus.hulk_woo_pcm", ".inline-edit-row", handler);

		return () => {
			$(document).off("focus.hulk_woo_pcm");
		};
	}, []);

	if (count > 0 && elementRef.current) {
		return createPortal(
			<MainComponent settings={settings}/>,
			elementRef.current,
		);
	}

	return null;
};

function MainComponent({settings}: { settings: Action }) {
	const [state, dispatch] = useReducer(
		(prevState: State, action: Action) => ({...prevState, ...action}),
		{
			hulk_woo_pcm_productCondition: "",
			hulk_woo_pcm_productConditionCustom: "",
			hulk_woo_pcm_productConditionCustomGroup: "",
			hulk_woo_pcm_productConditionLabel: "",
			hulk_woo_pcm_productConditionShopLabel: "",
			...settings,
		},
	);

	return (
		<>
			<input
				type="hidden"
				name={`hulk_woo_pcm_productConditionCustomGroup`}
				defaultValue={state.hulk_woo_pcm_productConditionCustomGroup}
			/>
			<input
				type="hidden"
				name={`hulk_woo_pcm_productConditionCustom`}
				defaultValue={state.hulk_woo_pcm_productConditionCustom}
			/>
			<input
				type="hidden"
				name={`hulk_woo_pcm_productConditionLabel`}
				defaultValue={state.hulk_woo_pcm_productConditionLabel}
			/>
			<input
				type="hidden"
				name={`hulk_woo_pcm_productConditionShopLabel`}
				defaultValue={state.hulk_woo_pcm_productConditionShopLabel}
			/>
			<div className="inline-edit-group product_condition_condition_option_field">
				<label className={"alignleft"} htmlFor={`hulk_woo_pcm_option`}>
					<span className="title">
						{__(
							"Product Condition",
							"product-condition-manager-for-woocommerce",
						)}
						<LockIcon className={"ml-[10px]"}/>
					</span>
					<span className="input-text-wrap">
						<FreemiusOverlay>
							<select
								id={`hulk_woo_pcm_option`}
								name={`hulk_woo_pcm_productCondition`}
								value={state.hulk_woo_pcm_productCondition}
								onChange={(event) => {
									dispatch({
										hulk_woo_pcm_productCondition:
										event.target.value,
									});
								}}
							>
								<option value="">
									—{" "}
									{__(
										"No Change",
										"product-condition-manager-for-woocommerce",
									)}{" "}
									—
								</option>
								{Object.entries(conditions).map(
									([group, names]) => (
										<optgroup label={group} key={group}>
											{Object.entries(names).map(
												([key, value]) => (
													<option
														key={`${group}-${key}`}
														value={key}
													>
														{value}
													</option>
												),
											)}
										</optgroup>
									),
								)}
								<option value="other">
									{__(
										"Other",
										"product-condition-manager-for-woocommerce",
									)}
								</option>
							</select>
						</FreemiusOverlay>
					</span>
				</label>
			</div>
			{state.hulk_woo_pcm_productCondition && (
				<>
					{state.hulk_woo_pcm_productCondition === "other" && (
						<div className="inline-edit-group product_condition_condition_option_field">
							<label
								className={"alignleft"}
								htmlFor={`hulk_woo_pcm_productConditionCustom`}
							>
								<span className="title">
									{__(
										"Custom Condition",
										"product-condition-manager-for-woocommerce",
									)}
								</span>
								<span
									className={
										"input-text-wrap mb-2 bg-white p-3 border-solid border-[1px] border-gray-200"
									}
								>
									<span
										className={"mb-3 flex flex-col gap-1"}
									>
										<span className="flex items-center justify-between gap-2">
											<span>
												{__(
													"Schema Offer Item Condition",
													"product-condition-manager-for-woocommerce",
												)}
												<SchemaConditionTooltip/>
											</span>
										</span>
										<select
											id={`hulk_woo_pcm_productConditionCustomGroup`}
											name={`hulk_woo_pcm_productConditionCustomGroup`}
											value={
												state.hulk_woo_pcm_productConditionCustomGroup
											}
											onChange={(event) => {
												dispatch({
													hulk_woo_pcm_productConditionCustomGroup:
													event.target.value,
												});
											}}
										>
											<option value="">
												—{" "}
												{__(
													"No Change",
													"product-condition-manager-for-woocommerce",
												)}{" "}
												—
											</option>
											{Object.entries(conditions).map(
												([group]) => (
													<option
														key={`productConditionCustomGroup-${group}`}
														value={group}
													>
														{group}
													</option>
												),
											)}
										</select>
									</span>
									<span className={"flex flex-col gap-1"}>
										<span>
											{__(
												"Product Custom Condition",
												"product-condition-manager-for-woocommerce",
											)}
										</span>
										<input
											type="text"
											id={`hulk_woo_pcm_productConditionCustom`}
											name={`hulk_woo_pcm_productConditionCustom`}
											value={
												state.hulk_woo_pcm_productConditionCustom
											}
											onChange={(event) => {
												dispatch({
													hulk_woo_pcm_productConditionCustom:
													event.target.value,
												});
											}}
										/>
									</span>
								</span>
							</label>
						</div>
					)}
					<div className="inline-edit-group product_condition_condition_option_field">
						<label
							className={"alignleft"}
							htmlFor={`hulk_woo_pcm_productConditionLabel`}
						>
							<span className="title">
								{__(
									"Display Label",
									"product-condition-manager-for-woocommerce",
								)}
							</span>
							<span className="input-text-wrap flex items-center gap-1">
								<input
									id={`hulk_woo_pcm_productConditionLabel`}
									name={`hulk_woo_pcm_productConditionLabel`}
									value={
										state.hulk_woo_pcm_productConditionLabel
									}
									onChange={(event) => {
										dispatch({
											hulk_woo_pcm_productConditionLabel:
											event.target.value,
										});
									}}
									type="text"
									placeholder={__(
										"Product Condition:",
										"product-condition-manager-for-woocommerce",
									)}
								/>
								<ProductConditionTooltip/>
							</span>
						</label>
					</div>
					<div className="inline-edit-group product_condition_condition_option_field">
						<label
							className={"alignleft"}
							htmlFor={`hulk_woo_pcm_productConditionShopLabel`}
						>
							<span className="title">
								{__(
									"Shop Label",
									"product-condition-manager-for-woocommerce",
								)}
							</span>
							<span className="input-text-wrap flex items-center gap-1">
								<input
									id={`hulk_woo_pcm_productConditionShopLabel`}
									name={`hulk_woo_pcm_productConditionShopLabel`}
									value={
										state.hulk_woo_pcm_productConditionShopLabel
									}
									onChange={(event) => {
										dispatch({
											hulk_woo_pcm_productConditionShopLabel:
											event.target.value,
										});
									}}
									type="text"
									placeholder={__(
										"Product Condition:",
										"product-condition-manager-for-woocommerce",
									)}
									readOnly={!globalSettings.showOnShopPage}
								/>
								<DisplayShopLabelTooltip/>
							</span>
							{!globalSettings.showOnShopPage && (
								<DisplayShopLabelNotice/>
							)}
						</label>
					</div>
				</>
			)}
		</>
	);
}

export default ProductQuickEditMetaSettings;
