/**
 * 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,
	InfoCallout,
} from "../../templates";
import { useSyncData } from "../../../context/SyncContext";
import useUnsavedChangesWarning from "../../../hooks/useUnsavedChangesWarning";
import { useSettingsDirty } from "../../../context/SettingsDirtyContext";
import { FileText, Folder, Image, Video, Users, Settings, File } from 'lucide-react';

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} />
					</>
				) : (
					<>
						{/* Card 1: File Options - Always visible */}
						<SettingsCard
							icon={FileText}
							title="File Options"
							description="Choose which file fields to sync from OpenAsset"
						>
							{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>
							)}
						</SettingsCard>

						{/* Card 2: Project Options - Conditional */}
						{options["general-settings"] &&
							options["general-settings"]["project-show"] === "yes" && (
								<SettingsCard
									icon={Folder}
									title="Project Options"
									description="Configure which project fields to sync and how to sort them"
								>
									{/* Auto-configured notice - moved inside card */}
									{options["data-options"] &&
										options["data-options"]["project-name-field-auto-set"] && (
											<div className="relative">
												<InfoCallout
													type="info"
													title="Project Name Field Configured"
												>
													Your Project Name Field was automatically set to "Name" during
													the plugin update. You can change this below if you use a custom
													field.
												</InfoCallout>
												<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="absolute top-4 right-4 text-gray-500 hover:text-gray-700 text-xl leading-none"
													aria-label="Dismiss notice"
												>
													✕
												</button>
											</div>
										)}

									{/* Project Name Field Selector */}
									{data["fields"] && data["fields"]["project"] ? (
										<>
											<SelectInput
												id='project-name-field'
												label='Project Name Field'
												value={
													options["data-options"]["project-name-field"] || ""
												}
												options={projectNameFieldOptions}
												setOption={updateOption}
												placeholder="Select field to use as project name"
												helpText="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."
											/>
										</>
									) : (
										<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>
									)}

									{/* Project Fields */}
									{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>
									)}

									{/* Project Keyword Categories */}
									{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>
									)}

									{/* Sort/Order section - 2-column grid */}
									<div className='grid grid-cols-1 sm:grid-cols-2 gap-4'>
										{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>
								</SettingsCard>
							)}

						{/* Card 3: Project Images - Conditional */}
						{options["general-settings"] &&
							options["general-settings"]["project-show"] === "yes" && (
								<SettingsCard
									icon={Image}
									title="Project Images"
									description="Configure how images are synced for projects"
								>
									<ToggleInput
										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"] === "yes"}
										setOption={(value, id) => updateOption(value ? "yes" : "no", id)}
									/>

									<ToggleInput
										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") === "yes"}
										setOption={(value, id) => updateOption(value ? "yes" : "no", id)}
									/>

									<ToggleInput
										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 'Enable Featured Image Sync for Projects?' 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") === "yes"}
										setOption={(value, id) => updateOption(value ? "yes" : "no", id)}
									/>

									<TextInput
										id='maximum-images-per-project'
										type='number'
										label='Maximum Images Per Project'
										value={
											options["data-options"]["maximum-images-per-project"]
										}
										setOption={updateOption}
									/>

									{/* Sort/Order section - 2-column grid */}
									<div className='grid grid-cols-1 sm:grid-cols-2 gap-4'>
										<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>
								</SettingsCard>
							)}

						{/* Card 4: Project Videos - Conditional */}
						{options["general-settings"] &&
							options["general-settings"]["project-show"] === "yes" && (
								<SettingsCard
									icon={Video}
									title="Project Videos"
									description="Configure how videos are synced for projects"
								>
									<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)}
									/>

									{/* Conditional nested settings */}
									{options["data-options"]["project-sync-videos"] === "yes" && (
										<div className='space-y-6'>
											<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>
									)}
								</SettingsCard>
							)}

						{/* Card 5: Employee Options - Conditional */}
						{options["general-settings"] &&
							options["general-settings"]["employee-show"] === "yes" && (
								<SettingsCard
									icon={Users}
									title="Employee Options"
									description="Configure which employee fields to sync and how to sort them"
								>
									{/* Employee Fields */}
									{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>
									)}

									{/* Sort/Order section - 2-column grid */}
									<div className='grid grid-cols-1 sm:grid-cols-2 gap-4'>
										{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>
								</SettingsCard>
							)}

						{/* Card 6: Employee Images - Conditional */}
						{options["general-settings"] &&
							options["general-settings"]["employee-show"] === "yes" && (
								<SettingsCard
									icon={Image}
									title="Employee Images"
									description="Configure how images are synced for employees"
								>
									<ToggleInput
										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"] === "yes"}
										setOption={(value, id) => updateOption(value ? "yes" : "no", id)}
									/>

									<ToggleInput
										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") === "yes"}
										setOption={(value, id) => updateOption(value ? "yes" : "no", id)}
									/>

									<ToggleInput
										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") === "yes"}
										setOption={(value, id) => updateOption(value ? "yes" : "no", id)}
									/>

									<TextInput
										id='maximum-images-per-employee'
										type='number'
										label='Maximum Images Per Employee'
										value={options["data-options"]["maximum-images-per-employee"]}
										setOption={updateOption}
									/>

									{/* Sort/Order section - 2-column grid */}
									<div className='grid grid-cols-1 sm:grid-cols-2 gap-4'>
										<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>
								</SettingsCard>
							)}

						{/* Card 7: Employee Videos - Conditional */}
						{options["general-settings"] &&
							options["general-settings"]["employee-show"] === "yes" && (
								<SettingsCard
									icon={Video}
									title="Employee Videos"
									description="Configure how videos are synced for employees"
								>
									<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)}
									/>

									{/* Conditional nested settings */}
									{options["data-options"]["employee-sync-videos"] === "yes" && (
										<div className='space-y-6'>
											<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>
									)}
								</SettingsCard>
							)}

					{/* Card 8: Role Options - Conditional */}
					{options["general-settings"] &&
						options["general-settings"]["role-show"] === "yes" && (
							<SettingsCard
								icon={Settings}
								title="Role Options"
								description="Configure automated rules and role fields"
							>
									{data["grid-columns"] ? (
										<>
											<MultiSelectInput
												id='roles-criteria-fields'
												label='Role Fields'
												values={
													options["data-options"]["roles-criteria-fields"]
												}
												options={roleCriteriaFieldsOptions}
												setOption={updateOption}
											/>
											<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 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>
									)}
								</SettingsCard>
							)}

						{/* Card 9: Text Asset Options - Conditional */}
						{options["general-settings"] &&
							options["general-settings"]["text-assets-show"] === "yes" && (
								<SettingsCard
									icon={FileText}
									title="Text Asset Options"
									description="Choose which text asset fields to sync from OpenAsset"
								>
									{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>
									)}
								</SettingsCard>
							)}
					</>
				)}

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

export default DataOptions;
