/**
 * External dependencies.
 */
import { useState, useEffect, useMemo, useRef } from "@wordpress/element";

/**
 * Internal dependencies.
 */
import { showPromiseToast, showPromiseToastRefresh, deepEqual } from "../../../utils";
import {
	fetchOptions,
	saveOptions,
	runUpdate,
	fetchData,
	updateSortValues,
	fetchSyncingData,
	refreshFields,
	fetchVideoSizes,
} from "../../../api/settings";
import SettingsLayout from "../../layout/SettingsLayout";
import {
	SettingsCard,
	SkeletonCard,
	MultiSelectInput,
	SelectInput,
	TextInput,
	ToggleInput,
	SyncingBanner,
	SettingsButtons,
} from "../../templates";
import { useSyncData } from "../../../context/SyncContext";
import useUnsavedChangesWarning from "../../../hooks/useUnsavedChangesWarning";
import { useSettingsDirty } from "../../../context/SettingsDirtyContext";

const DataOptions = () => {
	const [processing, setProcessing] = useState(true);
	const [isLoading, setIsLoading] = useState(false);
	const { syncData, handleTriggerSync } = useSyncData();

	const [options, setOptions] = useState({
		"data-options": {},
		"general-settings": {},
	});

	// State and Ref for unsaved changes detection
	const { isDirty, setIsDirty } = useSettingsDirty();
	const initialOptionsRef = useRef(null);

	const [data, setData] = useState({});
	const [videoSizes, setVideoSizes] = useState([]);
	const [loadingVideoSizes, setLoadingVideoSizes] = useState(true);

	const projectCriteriaFieldsOptions = useMemo(() => {
		if (!data?.fields?.project) return [];

		// Get the selected name field ID
		const selectedNameFieldId = options?.["data-options"]?.["project-name-field"];

		return (data.fields.project || [])
			.filter(
				(field) =>
					field.rest_code !== "show_on_website" &&
					field.rest_code !== "roles"
			)
			.map((field) => {
				const isDisabled = selectedNameFieldId && field.id.toString() === selectedNameFieldId.toString();
				return {
					key: field.id,
					label: field.name,
					disabled: isDisabled, // Mark the selected name field as disabled
				};
			})
			.concat([
				{
					key: "location",
					label: "Location Data",
				},
			]);
	}, [data?.fields?.project, options?.["data-options"]?.["project-name-field"]]);

	// Options for the project name field dropdown (only single line fields)
	const projectNameFieldOptions = useMemo(() => {
		if (!data?.fields?.project) return {};

		return Object.fromEntries(
			(data.fields.project || [])
				.filter((field) => 
					// Only include single line fields
					field.field_display_type === 'singleLine'
				)
				.map((field) => [field.id.toString(), field.name])
		);
	}, [data?.fields?.project]);

	const projectSortByOptions = useMemo(() => {
		if (!data?.fields?.project) return {};

		return Object.fromEntries(
			(data.fields.project || [])
				.filter(
					(field) =>
						field.rest_code !== "show_on_website" &&
						field.rest_code !== "roles"
				)
				.map((field) => [field.id.toString(), field.name])
		);
	}, [data?.fields?.project]);

	const employeeCriteriaFieldsOptions = useMemo(() => {
		if (!data?.fields?.employee) return [];

		return (data.fields.employee || [])
			.filter(
				(field) =>
					field.rest_code !== "show_on_website" &&
					field.rest_code !== "roles"
			)
			.map((field) => ({
				key: field.id,
				label: field.name,
				disabled:
					field.rest_code === "first_name" ||
					field.rest_code === "last_name", // Mark the field as disabled if rest_code is 'first_name' or 'last_name'
			}));
	}, [data?.fields?.employee]);

	const employeeSortByOptions = useMemo(() => {
		if (!data?.fields?.employee) return {};

		return Object.fromEntries(
			(data.fields.employee || [])
				.filter(
					(field) =>
						field.rest_code !== "show_on_website" &&
						field.rest_code !== "roles"
				)
				.map((field) => [field.id.toString(), field.name])
		);
	}, [data?.fields?.employee]);

	const textAssetCriteriaFieldsOptions = useMemo(() => {
		if (!data?.fields?.textAsset) return [];

		return (data.fields.textAsset || [])
			.filter(
				(field) =>
					field.rest_code !== "show_on_website" &&
					field.rest_code !== "code" &&
					field.metadata === 0 // Only show Text Fields, not Reference Fields
			)
			.map((field) => ({
				key: field.id,
				label: field.name,
				disabled:
					field.rest_code === "name" ||
					field.rest_code === "body_text", // Mark required fields as disabled
			}));
	}, [data?.fields?.textAsset]);

	const roleCriteriaFieldsOptions = useMemo(() => {
		if (!data?.["grid-columns"]) return [];

		return (data["grid-columns"] || [])
			.filter((field) => field.name !== "Role Sync Id")
			.map((role) => ({
				key: role.id,
				label: role.name,
			}));
	}, [data?.["grid-columns"]]);

	const updateOption = (value, id) => {
		setOptions({
			...options,
			"data-options": {
				...options["data-options"],
				[id]: value,
			},
		});
	};

	const onSave = () => {
		if (!processing) {
			setIsLoading(true);
			
			// Clear the auto-set flag when user saves (they've now reviewed the setting)
			let optionsToSave = options;
			if (options["data-options"] && options["data-options"]["project-name-field-auto-set"]) {
				optionsToSave = { ...options };
				optionsToSave["data-options"] = { ...options["data-options"] };
				delete optionsToSave["data-options"]["project-name-field-auto-set"];
				setOptions(optionsToSave); // Update local state to hide notice immediately
			}
			
			const res = saveOptions({ options: optionsToSave })
				.then((response) => {
					// Check if we need to refresh after showing success toast
					const shouldRefresh = response && response._shouldRefresh;
					
					// Now directly reset dirty state after saveOptions succeeds
					initialOptionsRef.current = JSON.parse(JSON.stringify(optionsToSave)); // Deep copy
					setIsDirty(false);
					
					// Auto-refresh for first-run CPT enablement
					if (shouldRefresh) {
						setTimeout(() => {
							window.location.reload();
						}, 1000); // Give time for success toast to show
					}
				})
				.catch((error) => {
					// Log or handle errors from saveOptions
					console.error("Error during save:", error);
					// Toast might show error from showPromiseToast anyway
				})
				.finally(() => {
					setIsLoading(false);
				}); 

			// Show toast based on the initial saveOptions promise
			showPromiseToast(res, "Saving...", "Settings updated!");
		}
	};

	const onRun = () => {
		if (!processing) {
			setIsLoading(true);
			// First, save the options
			const savePromise = saveOptions({ options });

			// Show saving toast
			showPromiseToast(savePromise, "Saving settings...", "Settings saved!");

			// After saving succeeds, reset dirty state and trigger sync
			savePromise.then((response) => {
				// Check if we need to refresh after showing success toast
				const shouldRefresh = response && response._shouldRefresh;
				
				// Reset dirty state first
				initialOptionsRef.current = JSON.parse(JSON.stringify(options));
				setIsDirty(false);

				// Auto-refresh for first-run CPT enablement (before sync starts)
				if (shouldRefresh) {
					setTimeout(() => {
						window.location.reload();
					}, 1000); // Give time for success toast to show
					return; // Skip sync if refreshing
				}

				// Now trigger the sync using the context function
				handleTriggerSync(); // Context handles its own toasts/notifications
			}).catch((error) => {
				// Handle potential errors from saveOptions
				console.error("Error saving settings before sync:", error);
				// Toast for saving error is handled by showPromiseToast above
			}).finally(() => {
				// Stop loading indicator regardless of sync trigger outcome (context manages sync loading)
				setIsLoading(false);
			});
		}
	};

	// Effect to automatically include selected project name field in project criteria fields
	// Only triggers when the project name field changes, not when criteria fields change
	useEffect(() => {
		const selectedNameFieldId = options?.["data-options"]?.["project-name-field"];
		const currentCriteriaFields = options?.["data-options"]?.["project-criteria-fields"] || [];
		
		// Only proceed if we have data loaded and a selected name field
		if (selectedNameFieldId && data?.fields?.project && !processing) {
			const selectedNameFieldIdStr = selectedNameFieldId.toString();
			
			if (!currentCriteriaFields.includes(selectedNameFieldIdStr)) {
				// Add the selected name field to criteria fields if it's not already included
				const updatedCriteriaFields = [...currentCriteriaFields, selectedNameFieldIdStr];
				setOptions(prevOptions => ({
					...prevOptions,
					"data-options": {
						...prevOptions["data-options"],
						"project-criteria-fields": updatedCriteriaFields
					}
				}));
			}
		}
	}, [options?.["data-options"]?.["project-name-field"], data?.fields?.project, processing]);

	// Additional useEffect to ensure the field is included after options are fully loaded
	// Only triggers when processing status changes or when the project name field changes

	useEffect(() => {
		// Run this after initial processing is complete and we have both data and options
		if (!processing && data?.fields?.project && options?.["data-options"]) {
			const selectedNameFieldId = options["data-options"]["project-name-field"];
			const currentCriteriaFields = options["data-options"]["project-criteria-fields"] || [];
			
			if (selectedNameFieldId) {
				const selectedNameFieldIdStr = selectedNameFieldId.toString();
				if (!currentCriteriaFields.includes(selectedNameFieldIdStr)) {
					const updatedCriteriaFields = [...currentCriteriaFields, selectedNameFieldIdStr];
					setOptions(prevOptions => ({
						...prevOptions,
						"data-options": {
							...prevOptions["data-options"],
							"project-criteria-fields": updatedCriteriaFields
						}
					}));
				}
			}
		}
	}, [processing, data?.fields?.project, options?.["data-options"]?.["project-name-field"]]);

	useEffect(() => {
		const updateOptions = (settings) =>
			setOptions({ ...options, ...settings });

		const loadData = async () => {
			try {
				// First, try to refresh fields from OpenAsset to get the latest data
				try {
					await refreshFields();
				} catch (refreshError) {
					// If refresh fails, log the error but continue with cached data
					console.warn('Failed to refresh fields, using cached data:', refreshError);
				}

				const optionsRes = await fetchOptions({ updateOptions });
				const dataRes = await fetchData();
				
				setData(dataRes);
				setProcessing(false);
				
				return optionsRes;
			} catch (error) {
				console.error("Error loading data:", error);
				setProcessing(false);
				throw error;
			}
		};

		const promise = loadData();
		showPromiseToast(promise, "Loading...", "Loaded!");
	}, []);

	// Fetch video sizes
	useEffect(() => {
		const loadVideoSizes = async () => {
			try {
				const sizesData = await fetchVideoSizes();
				setVideoSizes(sizesData || []);
			} catch (sizesError) {
				console.warn('Failed to fetch video sizes:', sizesError);
				setVideoSizes([]);
			} finally {
				setLoadingVideoSizes(false);
			}
		};

		loadVideoSizes();
	}, []);

	// Effect to initialize the initial options ref after data is loaded
	useEffect(() => {
		if (!processing && initialOptionsRef.current === null) {
			initialOptionsRef.current = JSON.parse(JSON.stringify(options)); // Deep copy
		}
	}, [processing, options]);

	// Effect to check if options have changed from the initial state
	useEffect(() => {
		if (!processing && initialOptionsRef.current !== null) {
			const newDirtyState = !deepEqual(options, initialOptionsRef.current);
			setIsDirty(newDirtyState);
		}
	}, [options, processing]);

	// Call the hook to manage warnings
	useUnsavedChangesWarning(isDirty);

	return (
		<SettingsLayout
			onSave={onSave}
			onRun={onRun}
			isLoading={isLoading || syncData.syncRunning == 1}
		>
			<div className='space-y-6'>
				{/* Page Header */}
				<div>
					<h1 className='text-2xl font-oa-bold text-oa-text-primary'>
						Data Options
					</h1>
					<p className='text-oa-sm text-oa-text-tertiary mt-1'>
						Set the information in OpenAsset that you would like to be available to your website
					</p>
				</div>

				{/* Loading State - Show skeleton cards */}
				{processing ? (
					<>
						<SkeletonCard hasIcon={false} />
						<SkeletonCard hasIcon={false} />
						<SkeletonCard hasIcon={false} />
					</>
				) : (
					<SettingsCard
						onSave={onSave}
						onRun={onRun}
						isLoading={isLoading || syncData.syncRunning == 1}
					>

			{/* Project Name Field Auto-Configured Notice - Shown at top for visibility */}
			{options["data-options"] && options["data-options"]["project-name-field-auto-set"] && (
				<div className="my-4 p-4 bg-yellow-50 border border-yellow-200 rounded-lg flex items-start justify-between mx-3 sm:mx-0 max-w-none sm:max-w-[80%]">
					<div className="flex-1">
						<div className="flex items-center">
							<span className="text-yellow-800 font-semibold">Project Name Field Configured</span>
						</div>
						<p className="mt-1 text-sm text-yellow-700">
							Your Project Name Field was automatically set to "Name" during the plugin update. 
							You can change this in the "Project Name Field" setting below if you use a custom field.
						</p>
					</div>
					<button
						onClick={() => {
							// Dismiss notice by clearing flag
							const updatedOptions = { ...options };
							delete updatedOptions["data-options"]["project-name-field-auto-set"];
							setOptions(updatedOptions);
							// Save to persist dismissal
							saveOptions({ options: updatedOptions });
						}}
						className="ml-4 text-yellow-600 hover:text-yellow-800 text-xl leading-none"
						aria-label="Dismiss notice"
					>
						✕
					</button>
				</div>
			)}

			<div className='border-b w-100 border-[#E6E6E6] pt-0 max-w-none sm:max-w-[80%] mx-3 sm:mx-0'></div>

				<h2 className='text-xl font-semibold leading-7 text-gray-900 px-3 sm:px-0'>
					File Options
				</h2>
				<div className='px-3 sm:px-0'>
					{data["fields"] && data["fields"]["project"] ? (
						<MultiSelectInput
							id='file-options'
							label='File Fields'
							values={options["data-options"]["file-options"]}
							options={[
								{
									key: "copyright_holder",
									label: "Copyright holder",
								},
								{
									key: "photographer",
									label: "Photographer",
								},
								{
									key: "caption",
									label: "Caption",
								},
								{
									key: "description",
									label: "Description",
								},
								...(data["fields"]["files"] || [])
									.filter(
										(field) =>
											field.rest_code !== "show_on_website" &&
											field.rest_code !== "use_as_featured_website_image"
									)
									.map((field) => ({
										key: field.id.toString(),
										label: field.name,
									})),
							]}
							setOption={updateOption}
						/>
					) : (
						<div className='py-5'>
							<div className='flex justify-center items-center'>
								<div className='animate-spin rounded-full h-16 w-16 border-b-2 border-gray-900'></div>
							</div>
						</div>
					)}
				</div>				

				{options["general-settings"] &&
					options["general-settings"]["project-show"] === "yes" && (
						<>
							<div className='border-b w-100 border-[#E6E6E6] pt-0 max-w-none sm:max-w-[80%] mx-3 sm:mx-0'></div>
							<h2 className='text-xl font-semibold leading-7 text-gray-900 px-3 sm:px-0'>
								Project Options
							</h2>
							{/* Project Name Field Selector */}
							<div className='px-3 sm:px-0 max-w-none sm:max-w-[80%]'>
								{data["fields"] && data["fields"]["project"] ? (
									<>
										<div className="flex items-center gap-2 mb-2">
											<label className="font-semibold">Project Name Field</label>
											{options["data-options"]["project-name-field-auto-set"] && (
												<span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
													Auto-configured
												</span>
											)}
										</div>
										
										<SelectInput
											id='project-name-field'
											label='' // Label shown above
											value={
												options["data-options"]["project-name-field"] || ""
											}
											options={projectNameFieldOptions}
											setOption={updateOption}
											placeholder="Select field to use as project name"
										/>
										
										{options["data-options"]["project-name-field-auto-set"] && (
											<div className="mt-2 p-3 bg-blue-50 border border-blue-200 rounded text-sm">
												<p className="text-blue-800">
													ℹ️ This field was automatically set to "Name" during your plugin update.
													Projects will continue syncing as before. You can change this if you use a different field for project titles.
												</p>
											</div>
										)}
										
									<p className="text-gray-500 italic text-xs mt-2 mb-2">
										This field will be used as the project title and URL slug in WordPress. 
										If no field is selected, the "Name" field will be used automatically. 
										Only projects with a value in this field will be synced.
									</p>
									</>
								) : (
									<div className='py-5'>
										<div className='flex justify-center items-center'>
											<div className='animate-spin rounded-full h-16 w-16 border-b-2 border-gray-900'></div>
										</div>
										<p className='text-center mt-3'>
											Loading Fields
										</p>
									</div>
								)}
							</div>
							{/* <div className='block sm:flex gap-10 sm:max-w-[80%] px-3 sm:px-0'> */}
							<div className='px-3 sm:px-0'>
								{data["fields"] && data["fields"]["project"] ? (
									<MultiSelectInput
										id='project-criteria-fields'
										label='Project Fields'
										values={
											options["data-options"][
												"project-criteria-fields"
											]
										}
										options={projectCriteriaFieldsOptions}
										setOption={updateOption}
									/>
								) : (
									<div className='py-5'>
										<div className='flex justify-center items-center'>
											<div className='animate-spin rounded-full h-16 w-16 border-b-2 border-gray-900'></div>
										</div>
										<p className='text-center mt-3'>
											Loading Fields
										</p>
									</div>
								)}
							</div>
							{/* <div className='hidden sm:block w-[1px] h-100 bg-[#D9D9D9]' />
				<div className='mt-5 sm:hidden w-100'></div> */}
							{/* keywords were here */}
							{/* </div> */}
							<div className='px-3 sm:px-0'>
								{data["project-keyword-categories"] ? (
									<MultiSelectInput
										id='project-criteria-keyword-categories'
										label='Project Keyword Categories'
										values={
											options["data-options"][
												"project-criteria-keyword-categories"
											]
										}
										options={(
											data[
												"project-keyword-categories"
											] || []
										).map((keyword) => ({
											key: keyword.id,
											label: keyword.name,
										}))}
										setOption={updateOption}
									/>
								) : (
									<div className='py-5'>
										<div className='flex justify-center items-center'>
											<div className='animate-spin rounded-full h-16 w-16 border-b-2 border-gray-900'></div>
										</div>
										<p className='text-center mt-3'>
											Loading Fields
										</p>
									</div>
								)}
							</div>
							<div className='flex flex-col sm:items-end sm:grid grid-cols-2 gap-x-10 gap-y-6 max-w-none sm:max-w-[80%] px-3 sm:px-0'>
								{data["fields"] &&
									data["fields"]["project"] && (
										<SelectInput
											id='project-sort-by'
											label='Sort projects by'
											value={
												options["data-options"][
													"project-sort-by"
												]
											}
											options={projectSortByOptions}
											setOption={updateOption}
										/>
									)}
								<SelectInput
									id='project-order-by'
									label='Order projects by'
									value={
										options["data-options"][
											"project-order-by"
										]
									}
									options={{
										Asc: "Ascending",
										Desc: "Descending",
									}}
									setOption={updateOption}
								/>
							</div>

							<div className='border-b w-100 border-[#E6E6E6] pt-0 max-w-none sm:max-w-[80%] mx-3 sm:mx-0'></div>

							<h2 className='text-xl font-semibold leading-7 text-gray-900 px-3 sm:px-0'>
								Project Images
							</h2>
							<div className='sm:flex gap-x-10 max-w-[80%]'>
								<div className='flex-1 space-y-6'>
									<SelectInput
										id='project-images-tagged-show-on-website'
										label='Only get images that are selected to "Show on Website"'
										value={options["data-options"]["project-images-tagged-show-on-website"]}
										options={{
											yes: "Yes",
											no: "No",
										}}
										setOption={updateOption}
									/>
									<SelectInput
										id='project-get-hero-images-default'
										label='Enable Featured Image Sync for Projects?'
										description="When enabled, the plugin will fetch the Project's hero image from OpenAsset and set it as the WordPress Featured Image during sync. This must be enabled for any featured image (including custom-tagged ones) to appear on Project posts."
										value={options["data-options"]["project-get-hero-images-default"] || "yes"}
										options={{
											yes: "Yes",
											no: "No",
										}}
										setOption={updateOption}
									/>
									<SelectInput
										id='project-use-featured-website-image-field'
										label='Use tagged OpenAsset image as Featured Image?'
										description="If enabled, the plugin will look for a Project image tagged with use_as_featured_website_image = yes on OpenAsset and use it as the featured image instead of the hero image."
										helpText="This only works if 'Get Hero Images by default' is also turned on. If no such image is found, the default hero image will be used."
										value={options["data-options"]["project-use-featured-website-image-field"] || "no"}
										options={{
											yes: "Yes",
											no: "No",
										}}
										setOption={updateOption}
									/>
								</div>
								<div className='flex-1 space-y-6'>
									<TextInput
										id='maximum-images-per-project'
										type='number'
										label='Maximum Images Per Project'
										value={
											options["data-options"][
												"maximum-images-per-project"
											]
										}
										setOption={updateOption}
									/>
									<SelectInput
										id='project-images-sort-by'
										label='Sort images by'
										value={
											options["data-options"][
												"project-images-sort-by"
											]
										}
										options={{
											created: "Created At",
											uploaded: "Uploaded At",
											updated: "Updated At",
											rank: "Rank",
											project_display_order:
												"Project File Display Order",
										}}
										setOption={updateOption}
									/>
									<SelectInput
										id='project-images-order-by'
										label='Order images by'
										value={
											options["data-options"][
												"project-images-order-by"
											]
										}
										options={{
											Asc: "Ascending",
											Desc: "Descending",
										}}
										setOption={updateOption}
									/>
								</div>
							</div>

							<div className='border-b w-100 border-[#E6E6E6] pt-4 max-w-none sm:max-w-[80%] mx-3 sm:mx-0'></div>

				<h2 className='text-xl font-semibold leading-7 text-gray-900 px-3 sm:px-0'>
					Project Videos
				</h2>
				<div className='px-3 sm:px-0 max-w-[80%]'>
					<ToggleInput
						id='project-sync-videos'
						label='Sync Videos for Projects?'
						description='Enable syncing of MP4 videos from OpenAsset. Videos will be available in your WordPress Media Library and can be used in project galleries, page builders, or anywhere else in WordPress.'
						value={options["data-options"]["project-sync-videos"] === "yes"}
						setOption={(value, id) => updateOption(value ? "yes" : "no", id)}
					/>
				</div>

				{options["data-options"]["project-sync-videos"] === "yes" && (
					<div className='px-3 sm:px-0 space-y-6 max-w-[80%]'>
						<ToggleInput
							id='project-videos-tagged-show-on-website'
							label='Only get videos that are selected to "Show on Website"'
							value={(options["data-options"]["project-videos-tagged-show-on-website"] || "yes") === "yes"}
							setOption={(value, id) => updateOption(value ? "yes" : "no", id)}
						/>
						
						<div>
							<label className='text-sm font-semibold leading-6 text-gray-900 block mb-2'>
								Video Size to Sync
							</label>
							{loadingVideoSizes ? (
								<p className='text-blue-500 italic text-xs'>
									Loading available video sizes...
								</p>
							) : videoSizes.length === 0 ? (
								<p className='text-gray-500 italic text-xs'>
									No video sizes found. Make sure you have video files in OpenAsset.
								</p>
							) : (
											<div>
												<p className='text-sm text-gray-500 mb-3'>
													Select which video size to download from OpenAsset. Larger sizes provide better quality but use more storage and bandwidth.
												</p>
												<div className='grid grid-cols-1 sm:grid-cols-2 gap-3 border border-gray-200 rounded-md p-4 bg-gray-50'>
													{videoSizes.map((size) => {
														const isSelected = options["data-options"]["project-video-size"] === size.id;
														return (
															<label 
																key={size.id} 
																className='flex items-start gap-3 cursor-pointer hover:bg-white p-2 rounded transition-colors'
															>
																<input
																	type="radio"
																	name="project-video-size"
																	checked={isSelected}
																	onChange={() => updateOption(size.id, "project-video-size")}
																	className='mt-0.5 h-4 w-4 border-gray-300 text-[#247070] focus:ring-[#247070]'
																/>
																<div className='flex-1'>
																	<div className='font-medium text-sm text-gray-900'>{size.name}</div>
																	<div className='text-xs text-gray-500'>
																		{size.width} × {size.height} • {size.file_format?.toUpperCase()}
																	</div>
																</div>
															</label>
														);
													})}
												</div>
												{options["data-options"]["project-video-size"] && (
													<p className='text-xs text-green-600 mt-2'>
														✓ {videoSizes.find(s => s.id === options["data-options"]["project-video-size"])?.name || 'Video size'} selected
													</p>
												)}
												{!options["data-options"]["project-video-size"] && (
													<p className='text-xs text-amber-600 mt-2'>
														⚠️ No video size selected. Please select a size to sync videos.
													</p>
												)}
											</div>
							)}
						</div>

						<TextInput
							id='maximum-videos-per-project'
							type='number'
							label='Maximum Videos Per Project'
							description="Videos are larger files than images. Consider bandwidth and storage when setting this limit."
							value={options["data-options"]["maximum-videos-per-project"] || "5"}
							setOption={updateOption}
						/>
					</div>
				)}
					</>
				)}

				{options["general-settings"] &&
					options["general-settings"]["employee-show"] === "yes" && (
						<>
							<div className='border-b w-100 border-[#E6E6E6] pt-0 max-w-none sm:max-w-[80%] mx-3 sm:mx-0'></div>

							<h2 className='text-xl font-semibold leading-7 text-gray-900 px-3 sm:px-0'>
								Employee Options
							</h2>
							<div className='px-3 sm:px-0'>
								{data["fields"] &&
								data["fields"]["employee"] ? (
									<MultiSelectInput
										id='employee-criteria-fields'
										label='Employee Fields'
										values={
											options["data-options"][
												"employee-criteria-fields"
											]
										}
										options={employeeCriteriaFieldsOptions}
										setOption={updateOption}
									/>
								) : (
									<div className='py-5'>
										<div className='flex justify-center items-center'>
											<div className='animate-spin rounded-full h-16 w-16 border-b-2 border-gray-900'></div>
										</div>
										<p className='text-center mt-3'>
											Loading Fields
										</p>
									</div>
								)}
							</div>

							<div className='flex flex-col sm:items-end sm:grid grid-cols-2 gap-x-10 gap-y-6 max-w-none sm:max-w-[80%] px-3 sm:px-0'>
								{data["fields"] &&
									data["fields"]["employee"] && (
										<SelectInput
											id='employee-sort-by'
											label='Sort employees by'
											value={
												options["data-options"][
													"employee-sort-by"
												]
											}
											options={employeeSortByOptions}
											setOption={updateOption}
										/>
									)}
								<SelectInput
									id='employee-order-by'
									label='Order employees by'
									value={
										options["data-options"][
											"employee-order-by"
										]
									}
									options={{
										Asc: "Ascending",
										Desc: "Descending",
									}}
									setOption={updateOption}
								/>
							</div>

							<div className='border-b w-100 border-[#E6E6E6] pt-0 max-w-none sm:max-w-[80%] mx-3 sm:mx-0'></div>

							<h2 className='text-xl font-semibold leading-7 text-gray-900 px-3 sm:px-0'>
								Employee Images
							</h2>
							<div className='sm:flex gap-x-10 max-w-[80%]'>
								<div className='flex-1 space-y-6'>
									<SelectInput
										id='employee-images-tagged-show-on-website'
										label='Only get images that are selected to "Show on Website"'
										value={options["data-options"]["employee-images-tagged-show-on-website"]}
										options={{
											yes: "Yes",
											no: "No",
										}}
										setOption={updateOption}
									/>
									<SelectInput
										id='employee-get-primary-photos-default'
										label='Enable Featured Image Sync for Employees?'
										description="When enabled, the plugin will fetch the Employee's primary photo from OpenAsset and set it as the WordPress Featured Image during sync. This must be enabled for any featured image (including custom-tagged ones) to appear on Employee posts."
										value={options["data-options"]["employee-get-primary-photos-default"] || "yes"}
										options={{
											yes: "Yes",
											no: "No",
										}}
										setOption={updateOption}
									/>
									<SelectInput
										id='employee-use-featured-website-image-field'
										label='Use tagged OpenAsset image as Featured Image?'
										description="If enabled, the plugin will look for an Employee image tagged with use_as_featured_website_image = yes on OpenAsset and use it as the featured image instead of the primary photo."
										helpText="This only works if 'Enable Featured Image Sync for Employees?' is also turned on. If no such image is found, the default primary photo will be used."
										value={options["data-options"]["employee-use-featured-website-image-field"] || "no"}
										options={{
											yes: "Yes",
											no: "No",
										}}
										setOption={updateOption}
									/>
								</div>
								<div className='flex-1 space-y-6'>
									<TextInput
										id='maximum-images-per-employee'
										label='Maximum Images Per Employee'
										value={options["data-options"]["maximum-images-per-employee"]}
										setOption={updateOption}
										type='number'
									/>
									<SelectInput
										id='employee-images-sort-by'
										label='Sort images by'
										value={
											options["data-options"][
												"employee-images-sort-by"
											]
										}
										options={{
											created: "Created At",
											uploaded: "Uploaded At",
											updated: "Updated At",
											rank: "Rank",
										}}
										setOption={updateOption}
									/>
									<SelectInput
										id='employee-images-order'
										label='Order images by'
										value={
											options["data-options"][
												"employee-images-order"
											]
										}
										options={{
											Asc: "Ascending",
											Desc: "Descending",
										}}
										setOption={updateOption}
									/>
								</div>
							</div>

							<div className='border-b w-100 border-[#E6E6E6] pt-4 max-w-none sm:max-w-[80%] mx-3 sm:mx-0'></div>

							<h2 className='text-xl font-semibold leading-7 text-gray-900 px-3 sm:px-0'>
								Employee Videos
							</h2>
							<div className='px-3 sm:px-0 max-w-[80%]'>
								<ToggleInput
									id='employee-sync-videos'
									label='Sync Videos for Employees?'
									description='Enable syncing of MP4 videos from OpenAsset. Videos will be available in your WordPress Media Library and can be used anywhere in WordPress.'
									value={options["data-options"]["employee-sync-videos"] === "yes"}
									setOption={(value, id) => updateOption(value ? "yes" : "no", id)}
								/>
							</div>

							{options["data-options"]["employee-sync-videos"] === "yes" && (
								<div className='px-3 sm:px-0 space-y-6 max-w-[80%]'>
									<ToggleInput
										id='employee-videos-tagged-show-on-website'
										label='Only get videos that are selected to "Show on Website"'
										value={(options["data-options"]["employee-videos-tagged-show-on-website"] || "yes") === "yes"}
										setOption={(value, id) => updateOption(value ? "yes" : "no", id)}
									/>
									
									<div>
										<label className='text-sm font-semibold leading-6 text-gray-900 block mb-2'>
											Video Size to Sync
										</label>
										{loadingVideoSizes ? (
											<p className='text-blue-500 italic text-xs'>
												Loading available video sizes...
											</p>
										) : videoSizes.length === 0 ? (
											<p className='text-gray-500 italic text-xs'>
												No video sizes found. Make sure you have video files in OpenAsset.
											</p>
										) : (
											<div>
												<p className='text-sm text-gray-500 mb-3'>
													Select which video size to download from OpenAsset. Larger sizes provide better quality but use more storage and bandwidth.
												</p>
												<div className='grid grid-cols-1 sm:grid-cols-2 gap-3 border border-gray-200 rounded-md p-4 bg-gray-50'>
													{videoSizes.map((size) => {
														const isSelected = options["data-options"]["employee-video-size"] === size.id;
														return (
															<label 
																key={size.id} 
																className='flex items-start gap-3 cursor-pointer hover:bg-white p-2 rounded transition-colors'
															>
																<input
																	type="radio"
																	name="employee-video-size"
																	checked={isSelected}
																	onChange={() => updateOption(size.id, "employee-video-size")}
																	className='mt-0.5 h-4 w-4 border-gray-300 text-[#247070] focus:ring-[#247070]'
																/>
																<div className='flex-1'>
																	<div className='font-medium text-sm text-gray-900'>{size.name}</div>
																	<div className='text-xs text-gray-500'>
																		{size.width} × {size.height} • {size.file_format?.toUpperCase()}
																	</div>
																</div>
															</label>
														);
													})}
												</div>
												{options["data-options"]["employee-video-size"] && (
													<p className='text-xs text-green-600 mt-2'>
														✓ {videoSizes.find(s => s.id === options["data-options"]["employee-video-size"])?.name || 'Video size'} selected
													</p>
												)}
												{!options["data-options"]["employee-video-size"] && (
													<p className='text-xs text-amber-600 mt-2'>
														⚠️ No video size selected. Please select a size to sync videos.
													</p>
												)}
											</div>
										)}
									</div>

									<TextInput
										id='maximum-videos-per-employee'
										type='number'
										label='Maximum Videos Per Employee'
										description="Videos are larger files than images. Consider bandwidth and storage when setting this limit."
										value={options["data-options"]["maximum-videos-per-employee"] || "5"}
										setOption={updateOption}
									/>
								</div>
							)}

							</>
					)}

				{options["general-settings"] &&
					options["general-settings"]["role-show"] === "yes" && (
						<>
							<div className='border-b w-100 border-[#E6E6E6] pt-0 max-w-none sm:max-w-[80%] mx-3 sm:mx-0'></div>

							<h2 className='text-xl font-semibold leading-7 text-gray-900 px-3 sm:px-0'>
								Role Options
							</h2>

							<div className='px-3 sm:px-0'>
								{data["grid-columns"] ? (
									<>
										<MultiSelectInput
											id='roles-criteria-fields'
											label='Role Fields'
											values={
												options["data-options"][
													"roles-criteria-fields"
												]
											}
											options={roleCriteriaFieldsOptions}
											setOption={updateOption}
										/>
										<div className='flex flex-col sm:items-end sm:grid grid-cols-2 gap-x-10 gap-y-6 max-w-none sm:max-w-[80%] px-3 sm:px-0 mt-4'>
											<SelectInput
												id='number-of-roles'
												label='Maximum Roles per Project or Employee'
												value={
													options["data-options"][
														"number-of-roles"
													] || "5"
												}
												options={Array(20)
													.fill(undefined)
													.reduce((options, _, i) => {
														options[
															`${i + 1}`
														] = `${i + 1}`;
														return options;
													}, {})}
												setOption={updateOption}
											/>
										</div>
									</>
								) : (
									<div className='py-5'>
										<div className='flex justify-center items-center'>
											<div className='animate-spin rounded-full h-16 w-16 border-b-2 border-gray-900'></div>
										</div>
										<p className='text-center mt-3'>
											Loading Fields
										</p>
									</div>
								)}
							</div>
						</>
					)}

				{options["general-settings"] &&
					options["general-settings"]["text-assets-show"] === "yes" && (
						<>
							<div className='border-b w-100 border-[#E6E6E6] pt-0 max-w-none sm:max-w-[80%] mx-3 sm:mx-0'></div>

							<h2 className='text-xl font-semibold leading-7 text-gray-900 px-3 sm:px-0'>
								Text Asset Options
							</h2>

							<div className='px-3 sm:px-0'>
								{data["fields"] && data["fields"]["textAsset"] ? (
									<MultiSelectInput
										id='text-assets-criteria-fields'
										label='Text Asset Fields'
										values={
											options["data-options"][
												"text-assets-criteria-fields"
											]
										}
										options={textAssetCriteriaFieldsOptions}
										setOption={updateOption}
									/>
								) : (
									<div className='py-5'>
										<div className='flex justify-center items-center'>
											<div className='animate-spin rounded-full h-16 w-16 border-b-2 border-gray-900'></div>
										</div>
										<p className='text-center mt-3'>
											Loading Fields
										</p>
									</div>
								)}
							</div>
						</>
					)}
					</SettingsCard>
				)}

				{/* Syncing Banner */}
				{(syncData?.is_initiating || syncData?.is_processing || syncData?.queue_count > 0) && (
					<SyncingBanner options={options} syncData={syncData} />
				)}
			</div>
		</SettingsLayout>
	);
};

export default DataOptions;
