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

/**
 * Internal dependencies.
 */
import { showPromiseToast, showPromiseToastRefresh, deepEqual } from "../../../utils";
import {
	fetchOptions,
	fetchData,
	saveOptions,
	runUpdate,
	updateFrequency,
	fetchSyncingData,
	fetchProjectKeywords,
	fetchImageSizes,
	refreshFields,
	runManualFullSyncWrapper,
	sendTestEmail,
} from "../../../api/settings";
import SettingsLayout from "../../layout/SettingsLayout";
import {
	SettingsCard,
	SkeletonCard,
	InfoCallout,
	SelectInput,
	TextInput,
	RadioSelectInput,
	ToggleInput,
	SyncingBanner,
	SettingsButtons,
	GroupedSelect,
} from "../../templates";
import { useSyncData } from "../../../context/SyncContext";
import useUnsavedChangesWarning from "../../../hooks/useUnsavedChangesWarning";
import { useSettingsDirty } from "../../../context/SettingsDirtyContext";
import { Link, CheckCircle, FolderSync, Image, Clock, Bell, Filter, Settings } from 'lucide-react';

const GeneralSettings = () => {
	const [processing, setProcessing] = useState(true); // For initial data loading
	const [isSaving, setIsSaving] = useState(false); // State specifically for save button
	const {
		syncData,
		isInitialized, // Use this instead of custom 'processing' for initial load visibility
		handleTriggerSync,
		isTriggering,
	} = useSyncData();

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

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

	const [projectShow, setProjectShow] = useState(null);
	const [employeeShow, setEmployeeShow] = useState(null);
	const [textAssetShow, setTextAssetShow] = useState(null);
	const [fieldsLoaded, setFieldsLoaded] = useState(false);
	const [data, setData] = useState({});
	const [employeeFieldValues, setEmployeeFieldValues] = useState([]);
	const [loadingFieldValues, setLoadingFieldValues] = useState(false);
	const [projectFieldValues, setProjectFieldValues] = useState([]);
	const [loadingProjectFieldValues, setLoadingProjectFieldValues] =
		useState(false);
	const [isDesktop, setIsDesktop] = useState(false);
	const [projectKeywords, setProjectKeywords] = useState([]);
	const [loadingProjectKeywords, setLoadingProjectKeywords] = useState(false);
	const [imageSizes, setImageSizes] = useState([]);
	const [loadingImageSizes, setLoadingImageSizes] = useState(true); // Start as true to show loading state
	const [isSyncDisabled, setIsSyncDisabled] = useState(true); // Initially disabled until context is ready

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

	// Add useEffect to handle role-show settings when project-show or employee-show changes
	useEffect(() => {
		// If either project-show or employee-show is set to "no", set role-show to "no"
		if (
			options["general-settings"]?.["project-show"] === "no" ||
			options["general-settings"]?.["employee-show"] === "no"
		) {
			// Only update if it's currently set to "yes" to avoid unnecessary state updates
			if (options["general-settings"]?.["role-show"] === "yes") {
				updateOption("no", "role-show");
			}
		}
	}, [
		options["general-settings"]?.["project-show"],
		options["general-settings"]?.["employee-show"],
	]);

	const onSave = () => {
		if (!processing) {
			setIsSaving(true);
			const res = saveOptions({ options });
			const data = {
				frequency:
					options["general-settings"]["feed-frequency"] ||
					"openasset_24",
			};
			// Chain frequency update after saving options completes
			res.then((response) => {
					// Check if we need to refresh after showing success toast
					const shouldRefresh = response && response._shouldRefresh;
					
					return updateFrequency(data).then(() => {
						// Reset initial state reference after successful save
						initialOptionsRef.current = JSON.parse(JSON.stringify(options)); // 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(() => {
					// Handle potential errors from saveOptions or updateFrequency if needed
					// Toast might already show an error from showPromiseToastRefresh
			   })
			   .finally(() => setIsSaving(false));

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

	// Simplified onRun - just calls the context function
	// Note: Saving settings before syncing might still be desired behavior.
	// If so, call onSave() first, await its promise, then call handleTriggerSync.
	// For now, keeping them separate as per the context implementation.
	const onRun = () => {
		if (!processing) {
			setIsSaving(true); // Use the saving indicator
			// First, save the options
			const savePromise = saveOptions({ options });

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

			// After saving succeeds, update frequency, reset dirty state, and trigger sync
			savePromise.then((response) => {
					// Check if we need to refresh after showing success toast
					const shouldRefresh = response && response._shouldRefresh;
					
					// Update frequency
					const freqData = {
						frequency:
							options["general-settings"]["feed-frequency"] ||
							"openasset_24",
					};
					return updateFrequency(freqData).then(() => {
						// Reset dirty state after save and frequency update
						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 or updateFrequency
					console.error("Error saving settings or updating frequency before sync:", error);
					// Toast for saving error is handled by showPromiseToast above
				})
				.finally(() => {
					// Stop saving indicator
					setIsSaving(false);
				});
		}
	};

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

			// Initialize project filter if needed
			if (
				settings?.["general-settings"]?.["project-filter-type"] ===
					"fields" &&
				settings?.["general-settings"]?.["project-field-filter"]
			) {
				const fieldId =
					settings["general-settings"]["project-field-filter"];
				setOptions((prev) => ({
					...prev,
					"general-settings": {
						...prev["general-settings"],
						"project-filter": `field_${fieldId}`,
						"project-filter-type": "fields",
					},
				}));
			} else if (
				settings?.["general-settings"]?.["project-filter-type"] ===
					"keywords" &&
				settings?.["general-settings"]?.["project-keyword-category"]
			) {
				const categoryId =
					settings["general-settings"]["project-keyword-category"];
				setOptions((prev) => ({
					...prev,
					"general-settings": {
						...prev["general-settings"],
						"project-filter": `keyword_${categoryId}`,
						"project-filter-type": "keywords",
					},
				}));
			}
		};

		const loadData = async () => {
			try {
				setLoadingProjectKeywords(true);
				setLoadingProjectFieldValues(true);
				setLoadingFieldValues(true);
				setFieldsLoaded(false);

				// First, try to refresh fields from OpenAsset to get the latest data
				let fieldsRefreshed = false;
				try {
					await refreshFields();
					fieldsRefreshed = true;
				} 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();

				// If fields refresh failed and we have no cached field data, try refresh again
				if (!fieldsRefreshed && (!dataRes["fields"]?.["project"] || !dataRes["fields"]?.["employee"])) {
					console.log('No cached field data found, attempting fields refresh again...');
					try {
						await refreshFields();
						// Re-fetch data after successful refresh
						const updatedDataRes = await fetchData();
						Object.assign(dataRes, updatedDataRes);
					} catch (retryError) {
						console.warn('Retry fields refresh also failed:', retryError);
					}
				}

				// Ensure project keywords are properly initialized
				if (!dataRes["project-keywords"]) {
					dataRes["project-keywords"] = [];
				}

			// Get full keyword information
			const keywordData = await fetchProjectKeywords();

			// Update the data with full keyword information
			dataRes["project-keywords"] = keywordData;
			
			// Fetch available image sizes
			setLoadingImageSizes(true);
			try {
				const sizesData = await fetchImageSizes();
				setImageSizes(sizesData || []);
			} catch (sizesError) {
				console.warn('Failed to fetch image sizes:', sizesError);
				setImageSizes([]);
			} finally {
				setLoadingImageSizes(false);
			}
			
			setData(dataRes);

				// Set project show flag - be more defensive about field detection
				if (dataRes["fields"]?.["project"] && Array.isArray(dataRes["fields"]["project"])) {
					const hasProjectShowField = dataRes["fields"]["project"].some(
						(project) =>
							project.rest_code &&
							project.rest_code.startsWith("show_on_website")
					);
					setProjectShow(hasProjectShowField);
					console.log('Project show field detected:', hasProjectShowField, 'from', dataRes["fields"]["project"].length, 'fields');
				} else {
					console.warn('No project fields found in data response');
					setProjectShow(null); // Keep as null to show loading state
				}

				// Set employee show flag - be more defensive about field detection
				if (dataRes["fields"]?.["employee"] && Array.isArray(dataRes["fields"]["employee"])) {
					const hasEmployeeShowField = dataRes["fields"]["employee"].some(
						(employee) =>
							employee.rest_code &&
							employee.rest_code.startsWith("show_on_website")
					);
					setEmployeeShow(hasEmployeeShowField);
					console.log('Employee show field detected:', hasEmployeeShowField, 'from', dataRes["fields"]["employee"].length, 'fields');
				} else {
					console.warn('No employee fields found in data response');
					setEmployeeShow(null); // Keep as null to show loading state
				}

				// Set text asset show flag - check for show_on_website field in text asset fields
				if (dataRes["fields"]?.["text-asset"] && Array.isArray(dataRes["fields"]["text-asset"])) {
					const hasTextAssetShowField = dataRes["fields"]["text-asset"].some(
						(textAsset) =>
							textAsset.rest_code &&
							textAsset.rest_code.startsWith("show_on_website")
					);
					setTextAssetShow(hasTextAssetShowField);
					console.log('Text Asset show field detected:', hasTextAssetShowField, 'from', dataRes["fields"]["text-asset"].length, 'fields');
				} else {
					console.warn('No text asset fields found in data response');
					setTextAssetShow(null); // Keep as null to show loading state
				}

				setFieldsLoaded(true);
				setProcessing(false);
				setLoadingProjectKeywords(false);
				setLoadingProjectFieldValues(false);
				setLoadingFieldValues(false);

				return optionsRes;
			} catch (error) {
				console.error("Error loading data:", error);
				setFieldsLoaded(true); // Set to true even on error to prevent infinite loading
				setProcessing(false);
				setLoadingProjectKeywords(false);
				setLoadingProjectFieldValues(false);
				setLoadingFieldValues(false);
				throw error;
			}
		};

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

	// 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, setIsDirty]);

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

	useEffect(() => {
		// Initialize project field values when data and options are available
		if (
			data["fields"]?.["project"] &&
			options["general-settings"]?.["project-filter"] &&
			options["general-settings"]?.["project-filter"].startsWith("field_")
		) {
			setLoadingProjectFieldValues(true);
			
			const [_, id] =
				options["general-settings"]["project-filter"].split("_");

			try {
				const selectedField = data["fields"]["project"]?.find(
					(field) => field.id.toString() === id
				);

				if (selectedField?.fieldLookupStrings) {
					const values =
						selectedField.fieldLookupStrings.map(
							(item) => item.value
						) || [];
					const sortedValues = [...new Set(values)].sort();
					setProjectFieldValues(sortedValues);
				} else {
					setProjectFieldValues([]);
				}
			} catch (error) {
				console.error("Error initializing project field values:", error);
				setProjectFieldValues([]);
			} finally {
				setLoadingProjectFieldValues(false);
			}
		}
	}, [
		data["fields"]?.["project"],
		options["general-settings"]?.["project-filter"],
	]);

	useEffect(() => {
		// Initialize employee field values when data and options are available
		if (
			data["fields"]?.["employee"] &&
			options["general-settings"]?.["employee-field-filter"] &&
			options["general-settings"]?.["employee-field-filter"].startsWith(
				"field_"
			)
		) {
			setLoadingFieldValues(true);
			const [_, id] =
				options["general-settings"]["employee-field-filter"].split("_");

			try {
				const selectedField = data["fields"]["employee"]?.find(
					(field) => field.id.toString() === id
				);

				if (selectedField?.fieldLookupStrings) {
					const values =
						selectedField.fieldLookupStrings.map(
							(item) => item.value
						) || [];
					const sortedValues = [...new Set(values)].sort();
					setEmployeeFieldValues(sortedValues);
				} else {
					setEmployeeFieldValues([]);
				}
			} catch (error) {
				console.error(
					"Error initializing employee field values:",
					error
				);
				setEmployeeFieldValues([]);
			} finally {
				setLoadingFieldValues(false);
			}
		}
	}, [
		data["fields"]?.["employee"],
		options["general-settings"]?.["employee-field-filter"],
	]);

	// Handle employee field filter changes
	const handleEmployeeFieldChange = (value) => {
		if (!value || value === "no_filter") {
			// Clear all filter-related values
			setOptions((prevOptions) => ({
				...prevOptions,
				"general-settings": {
					...prevOptions["general-settings"],
					"employee-field-filter": value || "",
					"employee-filter-type": "",
					"employee-field-filter-value": "",
				},
			}));
			setEmployeeFieldValues([]);
			return;
		}

		const [type, id] = value.split("_");

		if (type === "field") {
			setLoadingFieldValues(true);
			try {
				// Update all states in a single batch for fields
				setOptions((prevOptions) => ({
					...prevOptions,
					"general-settings": {
						...prevOptions["general-settings"],
						"employee-filter-type": "fields",
						"employee-field-filter": value, // Store the full field_id format
						"employee-field-filter-value": "",
					},
				}));

				// Find the selected field
				const selectedField = data["fields"]["employee"]?.find(
					(field) => field.id.toString() === id
				);

				if (selectedField?.fieldLookupStrings) {
					const values =
						selectedField.fieldLookupStrings.map(
							(item) => item.value
						) || [];
					const sortedValues = [...new Set(values)].sort();
					setEmployeeFieldValues(sortedValues);
				} else {
					setEmployeeFieldValues([]);
				}
			} catch (error) {
				console.error("Error getting field values:", error);
				setEmployeeFieldValues([]);
			} finally {
				setLoadingFieldValues(false);
			}
		}
	};

	// Handle project field filter changes
	const handleProjectFieldFilter = (value) => {
		if (!value || value === "no_filter") {
			// Clear all filter-related values
			setOptions((prevOptions) => ({
				...prevOptions,
				"general-settings": {
					...prevOptions["general-settings"],
					"project-filter": value || "",
					"project-filter-type": "",
					"project-field-filter": "",
					"project-field-filter-value": "",
					"project-keyword-category": "",
					"project-keyword": "",
				},
			}));
			setProjectFieldValues([]);
			setProjectKeywords([]);
			return;
		}

		const [type, id] = value.split("_");

		if (type === "field") {
			setLoadingProjectFieldValues(true);
			try {
				// Update all states in a single batch for fields
				setOptions((prevOptions) => ({
					...prevOptions,
					"general-settings": {
						...prevOptions["general-settings"],
						"project-filter-type": "fields",
						"project-filter": value, // Store the full field_id format
						"project-field-filter": id,
						"project-field-filter-value": "",
						"project-keyword-category": "",
						"project-keyword": "",
					},
				}));

				setProjectKeywords([]);

				const selectedField = data["fields"]["project"]?.find(
					(field) => field.id.toString() === id
				);

				if (selectedField?.fieldLookupStrings) {
					const values =
						selectedField.fieldLookupStrings.map(
							(item) => item.value
						) || [];
					const sortedValues = [...new Set(values)].sort();
					setProjectFieldValues(sortedValues);
				} else {
					setProjectFieldValues([]);
				}
			} catch (error) {
				console.error("Error getting field values:", error);
				setProjectFieldValues([]);
			} finally {
				setLoadingProjectFieldValues(false);
			}
		} else if (type === "keyword") {
			setLoadingProjectKeywords(true);
			try {
				// Update all states in a single batch for keywords
				setOptions((prevOptions) => ({
					...prevOptions,
					"general-settings": {
						...prevOptions["general-settings"],
						"project-filter-type": "keywords",
						"project-filter": value,
						"project-keyword-category": id,
						"project-keyword": "",
						"project-field-filter": "",
						"project-field-filter-value": "",
					},
				}));

				setProjectFieldValues([]);

				const selectedCategory = data["project-keywords"]?.find(
					(category) => category.category.id.toString() === id
				);

				if (
					selectedCategory &&
					Array.isArray(selectedCategory.keywords)
				) {
					setProjectKeywords(selectedCategory.keywords);
				} else {
					setProjectKeywords([]);
				}
			} catch (error) {
				console.error("Error filtering project keywords:", error);
				setProjectKeywords([]);
			} finally {
				setLoadingProjectKeywords(false);
			}
		}
	};

	// Handle project field change (when selecting a specific field value)
	const handleProjectFieldChange = (value, id) => {
		// Clear the project field filter value when changing fields
		updateOption("", "project-field-filter-value");
		updateOption(value, id);

		setLoadingProjectFieldValues(true);
		try {
			// Find the selected field
			const selectedField = data["fields"]["project"]?.find(
				(field) => field.id.toString() === value
			);

			// Get and sort the values from fieldLookupStrings
			const values =
				selectedField?.fieldLookupStrings?.map((item) => item.value) ||
				[];
			const sortedValues = [...new Set(values)].sort();

			setProjectFieldValues(sortedValues);
		} catch (error) {
			console.error("Error getting field values:", error);
			setProjectFieldValues([]);
		} finally {
			setLoadingProjectFieldValues(false);
		}
	};

	// Handle the selection of a value in the project field filter value dropdown
	const handleProjectFieldValueChange = (value, id) => {
		// Just update the value without clearing anything
		updateOption(value, id);
	};

	// Handle the selection of a value in the employee field filter value dropdown
	const handleEmployeeFieldValueChange = (value, id) => {
		// Just update the value without clearing anything
		updateOption(value, id);
	};

	// Handle image size exclusion checkbox changes
	const handleImageSizeExclusionToggle = (sizeId) => {
		const currentExcluded = options["general-settings"]["excluded-image-sizes"] || [];
		let newExcluded;
		
		if (currentExcluded.includes(sizeId)) {
			// Remove from excluded list
			newExcluded = currentExcluded.filter(id => id !== sizeId);
		} else {
			// Add to excluded list
			newExcluded = [...currentExcluded, sizeId];
		}
		
		updateOption(newExcluded, "excluded-image-sizes");
	};

	// Handle manual full sync button click
	const handleManualFullSync = async () => {
		try {
			await runManualFullSyncWrapper();
			// No toast needed - sync banner provides all the feedback
		} catch (error) {
			console.error("Manual full sync error:", error);
			// Only show toast for actual errors
			showPromiseToast(
				Promise.reject(error),
				"",
				"Failed to start manual full sync."
			);
		}
	};
	
	// Handle test email button click
	const handleTestEmail = async () => {
		const email = options["general-settings"]["sync-email-address"] || null;
		
		showPromiseToast(
			sendTestEmail(email),
			"Sending test email...",
			"Test email sent successfully! Check your inbox.",
			"Failed to send test email. Check your email configuration."
		);
	};

	// Memoized project filter options
	const projectFilterOptions = useMemo(() => {
		// Only compute when data is available
		if (!data || !data.fields || !data.fields.project) {
			return [];
		}

		// Create the option groups
		return [
			{
				label: "No Filter",
				options: [
					{
						value: "no_filter",
						label: "No Filter",
						type: "none",
					},
				],
			},
			{
				label: "Fields",
				options: (data.fields.project || [])
					.filter(
						(field) =>
							(field.field_display_type === "option" ||
								field.field_display_type ===
									"fixedSuggestion" ||
								field.field_display_type === "suggestion") &&
							field.rest_code !== "show_on_website" &&
							field.rest_code !== "roles" &&
							field.rest_code !== "code" &&
							field.rest_code !== "name"
					)
					.map((field) => ({
						value: `field_${field.id}`,
						label: field.name,
						type: "field",
						fieldId: field.id,
					})),
			},
			{
				label: "Keyword Category",
				options: (data["project-keywords"] || []).map((item) => ({
					value: `keyword_${item.category.id}`,
					label: item.category.name,
					type: "keyword",
					categoryId: item.category.id,
				})),
			},
		];
	}, [data?.fields?.project, data?.["project-keywords"]]);

	// Memoized employee filter options
	const employeeFilterOptions = useMemo(() => {
		// Only compute when data is available
		if (!data || !data.fields || !data.fields.employee) {
			return [];
		}

		return [
			{
				label: "No Filter",
				options: [
					{
						value: "no_filter",
						label: "No Filter",
						type: "none",
					},
				],
			},
			{
				label: "Fields",
				options: (data.fields.employee || [])
					.filter(
						(field) =>
							(field.field_display_type === "option" ||
								field.field_display_type ===
									"fixedSuggestion" ||
								field.field_display_type === "suggestion") &&
							field.rest_code !== "show_on_website" &&
							field.rest_code !== "roles"
					)
					.map((field) => ({
						value: `field_${field.id}`,
						label: field.name,
						type: "field",
						fieldId: field.id,
					})),
			},
		];
	}, [data?.fields?.employee]);

	// Memoized options for the filter value dropdown
	const filterValueOptions = useMemo(() => {
		const filterType = options["general-settings"]["project-filter-type"];

		if (
			filterType === "keywords" &&
			projectKeywords &&
			projectKeywords.length > 0
		) {
			return Object.fromEntries(
				projectKeywords.map((keyword) => [
					keyword.id.toString(),
					keyword.name,
				])
			);
		} else {
			return Object.fromEntries(
				(projectFieldValues || []).map((value) => [value, value])
			);
		}
	}, [
		options["general-settings"]["project-filter-type"],
		projectKeywords,
		projectFieldValues,
	]);

	// Memoized options for the employee filter value dropdown
	const employeeFilterValueOptions = useMemo(() => {
		return Object.fromEntries(
			(employeeFieldValues || []).map((value) => [value, value])
		);
	}, [employeeFieldValues]);

	useEffect(() => {
		// Initialize project keywords when data and options are available
		if (
			data["project-keywords"] &&
			options["general-settings"]?.["project-filter-type"] === "keywords" &&
			options["general-settings"]?.["project-keyword-category"]
		) {
			setLoadingProjectKeywords(true);
			try {
				const selectedCategory = data["project-keywords"]?.find(
					(category) => category.category.id.toString() === options["general-settings"]["project-keyword-category"]
				);

				if (selectedCategory && Array.isArray(selectedCategory.keywords)) {
					setProjectKeywords(selectedCategory.keywords);
				} else {
					setProjectKeywords([]);
				}
			} catch (error) {
				console.error("Error initializing project keywords:", error);
				setProjectKeywords([]);
			} finally {
				setLoadingProjectKeywords(false);
			}
		}
	}, [data["project-keywords"], options["general-settings"]?.["project-filter-type"], options["general-settings"]?.["project-keyword-category"]]);

	useEffect(() => {
		// Update disabled state based on context data
		if (isInitialized) {
			setIsSyncDisabled(
				!!syncData?.is_initiating ||
					!!syncData?.is_processing ||
					isTriggering
			);
		}
	}, [syncData, isTriggering, isInitialized]);

	// Get the sync status text and style based on the current state
	const getSyncStatusDisplay = () => {
		if (!isInitialized) {
			return { text: "Loading status...", style: "loading" };
		}
		if (syncData?.is_initiating) {
			return { text: "Populating sync queue...", style: "syncing" };
		}
		if (syncData?.is_processing) {
			return {
				text: `Syncing: ${syncData.queue_count} items remaining...`,
				style: "syncing",
			};
		}
		if (syncData?.queue_count > 0) {
			// Queue has items but not actively processing (waiting for cron trigger)
			return {
				text: `Pending: ${syncData.queue_count} items in queue. Next sync: ${syncData.next_scheduled_human}`,
				style: "warning", // Or a different style
			};
		}
		// Idle state
		return {
			text: `Idle. Next sync: ${syncData.next_scheduled_human}`,
			style: "synced", // Or 'idle'
		};
	};

	const { text: syncStatusText, style: syncStatusStyle } = getSyncStatusDisplay();

	return (
		<SettingsLayout
			onSave={onSave}
			onRun={onRun}
			isLoading={isSaving || isSyncDisabled}
		>
			<div className='space-y-6'>
				{/* Page Header */}
				<div>
					<h1 className='text-2xl font-oa-bold text-oa-text-primary'>
						General Settings
					</h1>
					<p className='text-oa-sm text-oa-text-tertiary mt-1'>
						Configure your OpenAsset connection and sync preferences
					</p>
				</div>

				{/* Loading State - Show skeleton cards */}
				{processing ? (
					<>
						<SkeletonCard hasIcon={true} />
						<SkeletonCard hasIcon={true} />
						<SkeletonCard hasIcon={true} />
					</>
				) : (
					<>
					{/* Real content below */}

				{/* Card 1: OpenAsset API */}
				<SettingsCard
					icon={Link}
					title='OpenAsset API'
					description='Connect to your OpenAsset instance'
				>
				{/* Connection Status Badge - only show when URL is loaded */}
				{options["general-settings"]["client-instance-url"] && (
					<div className='flex items-center gap-2 px-3 py-2 bg-blue-50 border border-blue-200 rounded-oa-md w-fit'>
						<CheckCircle className='w-4 h-4 text-[#2563eb]' />
						<span className='text-oa-sm font-oa-medium text-[#1e40af]'>
							Connected to{' '}
							<a
								href={options["general-settings"]["client-instance-url"]}
								className='text-[#2563eb] hover:text-[#1d4ed8] underline transition-colors'
								target='_blank'
								rel='noopener noreferrer'
							>
								{options["general-settings"]["client-instance-url"]?.replace('https://', '').replace('http://', '').split('/')[0]}
							</a>
						</span>
					</div>
				)}
					
					<TextInput
						id='your-real-token-id'
						label='Token ID'
						value={options["general-settings"]["your-real-token-id"]}
						setOption={updateOption}
					/>
					
					<TextInput
						id='your-real-api-token'
						label='API Token'
						value={options["general-settings"]["your-real-api-token"]}
						setOption={updateOption}
						type='password'
					/>
				</SettingsCard>

				{/* Card 2: Asset Sync */}
				<SettingsCard
					icon={FolderSync}
					title='Asset Sync'
					description='Select which content types to sync from OpenAsset'
				>
					<InfoCallout type='info' title='Important'>
						Projects, Employees, and Text Assets must have a "Show on Website" 
						(show_on_website) field set to "yes" in OpenAsset.
					</InfoCallout>

					{/* Sync Toggles */}
					<div className='space-y-6'>
						{/* Sync Projects */}
						<div>
							{!fieldsLoaded && (
								<div className='mb-3'>
									<p className='text-oa-sm text-oa-text-tertiary italic'>
										Loading field information from OpenAsset...
									</p>
								</div>
							)}
							{fieldsLoaded && projectShow === false && (
								<div className='mb-3'>
									<p className='text-oa-sm text-oa-text-tertiary italic'>
										Project sync is not possible until you have created a "Show on Website" field in OpenAsset.
									</p>
								</div>
							)}
							<ToggleInput
								id='project-show'
								label='Sync Projects'
								description={fieldsLoaded && projectShow === false 
									? 'Requires "Show on Website" field in OpenAsset'
									: 'Sync project data from OpenAsset to WordPress'
								}
								value={options["general-settings"]["project-show"] === "yes"}
								setOption={(value) => updateOption(value ? "yes" : "no", "project-show")}
								disabled={!fieldsLoaded}
							/>
						</div>

						{/* Sync Employees */}
						<div>
							{!fieldsLoaded && (
								<div className='mb-3'>
									<p className='text-oa-sm text-oa-text-tertiary italic'>
										Loading field information from OpenAsset...
									</p>
								</div>
							)}
							{fieldsLoaded && employeeShow === false && (
								<div className='mb-3'>
									<p className='text-oa-sm text-oa-text-tertiary italic'>
										Employee sync is not possible until you have created a "Show on Website" field in OpenAsset.
									</p>
								</div>
							)}
							<ToggleInput
								id='employee-show'
								label='Sync Employees'
								description={fieldsLoaded && employeeShow === false
									? 'Requires "Show on Website" field in OpenAsset'
									: 'Sync employee data from OpenAsset to WordPress'
								}
								value={options["general-settings"]["employee-show"] === "yes"}
								setOption={(value) => updateOption(value ? "yes" : "no", "employee-show")}
								disabled={!fieldsLoaded}
							/>
						</div>

						{/* Sync Roles */}
						<div>
							{(options["general-settings"]["project-show"] === "no" ||
								options["general-settings"]["employee-show"] === "no") && (
								<div className='mb-3'>
									<p className='text-oa-sm text-oa-text-tertiary italic'>
										Roles can only be synced if you are syncing both Projects and Employees.
									</p>
								</div>
							)}
							<ToggleInput
								id='role-show'
								label='Sync Roles'
								description={
									options["general-settings"]["project-show"] === "no" ||
									options["general-settings"]["employee-show"] === "no"
										? 'Requires both Projects and Employees sync to be enabled'
										: 'Sync role assignments between projects and employees'
								}
								value={options["general-settings"]["role-show"] === "yes"}
								setOption={(value) => updateOption(value ? "yes" : "no", "role-show")}
								disabled={
									options["general-settings"]["project-show"] === "no" ||
									options["general-settings"]["employee-show"] === "no"
								}
							/>
						</div>

						{/* Sync Text Assets */}
						<div>
							{!fieldsLoaded && (
								<div className='mb-3'>
									<p className='text-oa-sm text-oa-text-tertiary italic'>
										Loading field information from OpenAsset...
									</p>
								</div>
							)}
							{fieldsLoaded && textAssetShow === false && (
								<div className='mb-3'>
									<p className='text-oa-sm text-oa-text-tertiary italic'>
										Text Asset sync is not possible until you have created a "Show on Website" field in OpenAsset.
									</p>
								</div>
							)}
							<ToggleInput
								id='text-assets-show'
								label='Sync Text Assets'
								description={fieldsLoaded && textAssetShow === false
									? 'Requires "Show on Website" field in OpenAsset'
									: 'Sync text asset content from OpenAsset to WordPress'
								}
								value={options["general-settings"]["text-assets-show"] === "yes"}
								setOption={(value) => updateOption(value ? "yes" : "no", "text-assets-show")}
								disabled={!fieldsLoaded}
							/>
						</div>
					</div>

				</SettingsCard>

				{/* Card 3: Media Sync */}
				<SettingsCard
					icon={Image}
					title='Media Sync'
					description='Configure how images and videos are synced'
				>
					<SelectInput
						id='image-size-sync'
						label='Image Size Sync'
						value={
							options["general-settings"]["image-size-sync"] ||
							"2000"
						}
						options={{
							2000: "Closest to 2000x2000px, up to 3.15MB",
							3000: "Closest to 3000x3000px, up to 3.15MB",
						}}
						setOption={updateOption}
					/>

					<div>
						<label className='text-oa-sm font-oa-semibold text-oa-text-secondary block mb-3'>
							Excluded Image Sizes
						</label>
						{loadingImageSizes ? (
							<p className='text-oa-sm text-oa-text-tertiary italic'>
								Loading available sizes...
							</p>
						) : imageSizes.length === 0 ? (
							<p className='text-oa-sm text-oa-text-tertiary italic'>
								No image sizes found. Make sure you have files in OpenAsset.
							</p>
						) : (
							<div className='space-y-3'>
								<p className='text-oa-sm text-oa-text-tertiary'>
									Images closest to your selected size (2000x2000px or 3000x3000px) will be synced. Check the boxes below to exclude specific image sizes from syncing (for example, grayscale or other variants you don't want). Only the most relevant size will be pulled in, not all sizes.
								</p>
								<div className='grid grid-cols-1 sm:grid-cols-2 gap-3 max-h-80 overflow-y-auto border border-oa-border rounded-oa-md p-4 bg-oa-bg-secondary'>
									{imageSizes.map((size) => {
										const isExcluded = (options["general-settings"]["excluded-image-sizes"] || []).includes(size.id);
										return (
											<label 
												key={size.id} 
												className='flex items-start gap-3 cursor-pointer hover:bg-white p-2 rounded-oa-sm transition-colors'
											>
												<input
													type="checkbox"
													checked={isExcluded}
													onChange={() => handleImageSizeExclusionToggle(size.id)}
													className='mt-0.5 h-4 w-4 rounded border-oa-border text-[#2563eb] focus:ring-[#2563eb] focus:ring-2'
												/>
												<span className='text-oa-sm text-oa-text-secondary select-none'>
													{size.display_name}
												</span>
											</label>
										);
									})}
								</div>
								{(options["general-settings"]["excluded-image-sizes"] || []).length > 0 && (
									<p className='text-oa-sm text-amber-600 mt-2'>
										⚠️ {(options["general-settings"]["excluded-image-sizes"] || []).length} size(s) will be excluded from syncing
									</p>
								)}
							</div>
						)}
					</div>
				</SettingsCard>

				{/* Card 4: Sync Schedule */}
				<SettingsCard
					icon={Clock}
					title='Sync Schedule'
					description='Configure automatic sync frequency and maintenance'
				>
					<InfoCallout type='info' title='Sync Types'>
						Regular syncs only update assets that have changed, whereas Maintenance Syncs sync everything again. Maintenance Syncs are much slower but are advised to run occasionally to ensure data integrity.
					</InfoCallout>

					<div className='space-y-6'>
						<SelectInput
							id='feed-frequency'
							label='Auto Sync Frequency'
							value={options["general-settings"]["feed-frequency"]}
							options={{
								none: "None",
								openasset_8: "Every 8 Hours",
								openasset_24: "Every 24 Hours",
							}}
							setOption={updateOption}
						/>

						<div>
							<label className='text-oa-sm font-oa-semibold text-oa-text-secondary block mb-2'>
								Maintenance Sync
							</label>
							<button
								type="button"
								className='inline-flex items-center px-4 py-2 border border-oa-border shadow-sm text-oa-sm font-oa-medium rounded-oa-md text-oa-text-secondary bg-white hover:bg-oa-bg-secondary focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[#2563eb] disabled:opacity-50 disabled:cursor-not-allowed transition-colors'
								disabled={isSyncDisabled}
								onClick={handleManualFullSync}
							>
								<svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
									<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
								</svg>
								Run Maintenance Sync
							</button>
							<p className='text-oa-sm text-oa-text-tertiary mt-2'>
								Forces a complete sync of all data, ignoring timestamps
							</p>
						</div>

						<SelectInput
							id='maintenance-sync-cycle'
							label='Auto Maintenance Sync'
							value={options["general-settings"]["maintenance-sync-cycle"] || "none"}
							options={{
								"10": "Every 10 syncs", 
								"20": "Every 20 syncs",
								"50": "Every 50 syncs",
								"100": "Every 100 syncs",
								"none": "None (Manual only)",
							}}
							setOption={updateOption}
						/>
						{options["general-settings"]["maintenance-sync-cycle"] === "none" && (
							<InfoCallout type='warning' title='Auto Maintenance Sync Disabled'>
								Auto Maintenance Syncs are disabled. These are advised to run occasionally to ensure data integrity.
							</InfoCallout>
						)}

						<ToggleInput
							id='enable-logging'
							label='Enable Detailed Logging'
							description='Standard logging (sync events, errors, warnings) is always active. Enable this for verbose diagnostics including per-item details, API requests, and memory stats. Log files are automatically capped at 5MB and rotated, so this is safe to leave on.'
							value={options["general-settings"]["enable-logging"] === "true" || options["general-settings"]["enable-logging"] === true}
							setOption={(value) => updateOption(value ? "true" : "false", "enable-logging")}
						/>

						{/* Next Scheduled Sync Info */}
						{syncData?.next_scheduled_human && (
							<div className='pt-4 border-t border-oa-border'>
								<p className='text-oa-sm text-oa-text-tertiary'>
									<span className='font-oa-medium text-oa-text-secondary'>Next scheduled sync:</span>{' '}
									{syncData.next_scheduled_human}
								</p>
							</div>
						)}
					</div>
				</SettingsCard>

				{/* Card 5: Notifications */}
				<SettingsCard
					icon={Bell}
					title='Sync Notifications'
					description='Get notified when syncs complete'
				>
					<div className='space-y-6'>
						<ToggleInput
							id='sync-email-enabled'
							label='Send email when sync completes'
							description='Get notified via email when syncs finish (success or failure)'
							value={options["general-settings"]["sync-email-enabled"] === "yes"}
							setOption={(value) => updateOption(value ? "yes" : "no", "sync-email-enabled")}
						/>

						{/* Email input - only show if enabled */}
						{options["general-settings"]["sync-email-enabled"] === "yes" && (
							<>
								<TextInput
									id='sync-email-address'
									label='Notification Email Address'
									type='email'
									value={options["general-settings"]["sync-email-address"] || ""}
									setOption={updateOption}
									placeholder='admin@yoursite.com'
								/>
								<p className='text-oa-sm text-oa-text-tertiary -mt-4'>
									Leave blank to use site admin email
								</p>

								{/* Test email button */}
								<div>
									<button
										type="button"
										onClick={handleTestEmail}
										className='inline-flex items-center px-4 py-2 border border-oa-border shadow-sm text-oa-sm font-oa-medium rounded-oa-md text-oa-text-secondary bg-white hover:bg-oa-bg-secondary focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[#2563eb] transition-colors'
									>
										<svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
											<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
										</svg>
										Send Test Email
									</button>
									<p className='text-oa-sm text-oa-text-tertiary mt-2'>
										Send a test email to verify your email configuration is working
									</p>
								</div>

								{/* Warning about email reliability */}
								<InfoCallout type='warning' title='Email Delivery Notice'>
									<div className='space-y-2'>
										<p>
											Email notifications may not work reliably on all servers. Shared hosting often blocks or limits email sending. 
											We recommend using the <strong>Test Email</strong> button to verify delivery before relying on notifications.
										</p>
										<p>
											For reliable email delivery, consider installing an SMTP plugin like <strong>WP Mail SMTP</strong> or <strong>Post SMTP</strong>.
										</p>
									</div>
								</InfoCallout>
							</>
						)}
					</div>
				</SettingsCard>

				{/* Card 6: Content Filters */}
				<SettingsCard
					icon={Filter}
					title='Custom Filters'
					description='Filter which Projects and Employees to sync'
				>
					<div className='space-y-8'>
						{/* Project Filter Section */}
						<div>
							<h3 className='text-base font-oa-semibold text-oa-text-primary mb-2'>
								Project Filter
							</h3>
							<p className='text-oa-sm text-oa-text-tertiary mb-6'>
								You can filter Project syncing based on Fixed Auto-Complete or Drop Down Menu fields or Keyword Categories.
							</p>
							
							{data["fields"] && data["fields"]["project"] ? (
								<div className='space-y-4'>
									<div className='flex flex-col sm:flex-row sm:items-end gap-4'>
										<div className='flex-1'>
											<GroupedSelect
												id='project-filter'
												label='Only sync Projects where...'
												value={
													options["general-settings"]["project-filter"] || ""
												}
												options={projectFilterOptions}
												setOption={handleProjectFieldFilter}
												noDefaultOption={true}
											/>
										</div>
										<p className='font-oa-semibold text-oa-sm text-oa-text-secondary whitespace-nowrap sm:px-2'>
											{options["general-settings"]["project-filter-type"] === "keywords"
												? "has"
												: "is"}
										</p>
										<div className='flex-1'>
											<SelectInput
												id={
													options["general-settings"]["project-filter-type"] === "keywords"
														? "project-keyword"
														: "project-field-filter-value"
												}
												label=''
												value={
													options["general-settings"]["project-filter-type"] === "keywords"
														? options["general-settings"]["project-keyword"]
														: options["general-settings"]["project-field-filter-value"]
												}
												options={filterValueOptions}
												setOption={handleProjectFieldValueChange}
												disabled={
													options["general-settings"]["project-filter-type"] === "keywords"
														? loadingProjectKeywords ||
														  !options["general-settings"]["project-keyword-category"]
														: loadingProjectFieldValues ||
														  !options["general-settings"]["project-field-filter"] ||
														  options["general-settings"]["project-filter"] === "no_filter"
												}
												loading={
													options["general-settings"]["project-filter-type"] === "keywords"
														? loadingProjectKeywords
														: loadingProjectFieldValues
												}
											/>
										</div>
									</div>
								</div>
							) : (
								<p className='text-oa-sm text-oa-text-tertiary italic'>
									Loading project fields...
								</p>
							)}
						</div>

						{/* Divider */}
						<div className='border-t border-oa-border'></div>

						{/* Employee Filter Section */}
						<div>
							<h3 className='text-base font-oa-semibold text-oa-text-primary mb-2'>
								Employee Filter
							</h3>
							<p className='text-oa-sm text-oa-text-tertiary mb-6'>
								You can filter Employee syncing based on a Fixed Auto-Complete or Drop Down Menu field.
							</p>
							
							{data["fields"] && data["fields"]["employee"] ? (
								<div className='space-y-4'>
									<div className='flex flex-col sm:flex-row sm:items-end gap-4'>
										<div className='flex-1'>
											<GroupedSelect
												id='employee-field-filter'
												label='Only sync Employees where...'
												value={
													options["general-settings"]["employee-field-filter"] || ""
												}
												options={employeeFilterOptions}
												setOption={handleEmployeeFieldChange}
												noDefaultOption={true}
											/>
										</div>
										<p className='font-oa-semibold text-oa-sm text-oa-text-secondary whitespace-nowrap sm:px-2'>
											is
										</p>
										<div className='flex-1'>
											<SelectInput
												id='employee-field-filter-value'
												label=''
												value={
													options["general-settings"]["employee-field-filter-value"]
												}
												options={employeeFilterValueOptions}
												setOption={handleEmployeeFieldValueChange}
												disabled={
													loadingFieldValues ||
													!options["general-settings"]["employee-field-filter"] ||
													options["general-settings"]["employee-field-filter"] === "no_filter"
												}
												loading={loadingFieldValues}
											/>
										</div>
									</div>
								</div>
							) : (
								<p className='text-oa-sm text-oa-text-tertiary italic'>
									Loading employee fields...
								</p>
							)}
						</div>
					</div>
				</SettingsCard>

			{/* Card 7: WordPress Settings */}
			<SettingsCard
				icon={Settings}
				title='WordPress Settings'
				description='Configure how content appears in WordPress'
			>
					<div className='space-y-8'>
						{/* Post Status Section */}
						<div>
							<h3 className='text-base font-oa-semibold text-oa-text-primary mb-4'>
								Post Status
							</h3>
							<div className='grid grid-cols-1 sm:grid-cols-2 gap-6'>
								<SelectInput
									id='project-post-status'
									label='Project Post Status'
									value={
										options["general-settings"]["project-post-status"] || "public"
									}
									options={{
										public: "Public",
										private: "Private",
									}}
									setOption={updateOption}
								/>
								<SelectInput
									id='employee-post-status'
									label='Employee Post Status'
									value={
										options["general-settings"]["employee-post-status"] || "public"
									}
									options={{
										public: "Public",
										private: "Private",
									}}
									setOption={updateOption}
								/>
							</div>
						</div>

						{/* Divider */}
						<div className='border-t border-oa-border'></div>

						{/* Project Naming Section */}
						<div>
							<h3 className='text-base font-oa-semibold text-oa-text-primary mb-4'>
								Project Naming
							</h3>
							<div className='grid grid-cols-1 sm:grid-cols-2 gap-6'>
								<TextInput
									id='project-name-plural'
									label='Projects Name (plural)'
									placeholder='Eg. projects'
									value={options["general-settings"]["project-name-plural"]}
									setOption={updateOption}
								/>
								<TextInput
									id='project-name-singular'
									label='Projects Name (singular)'
									placeholder='Eg. project'
									value={options["general-settings"]["project-name-singular"]}
									setOption={updateOption}
								/>
								<TextInput
									id='project-url-key'
									label='Projects URL Key'
									value={options["general-settings"]["project-url-key"]}
									setOption={updateOption}
									placeholder='Eg. projects'
								/>
							</div>
						</div>

						{/* Divider */}
						<div className='border-t border-oa-border'></div>

						{/* Employee Naming Section */}
						<div>
							<h3 className='text-base font-oa-semibold text-oa-text-primary mb-4'>
								Employee Naming
							</h3>
							<div className='grid grid-cols-1 sm:grid-cols-2 gap-6'>
								<TextInput
									id='employee-name-plural'
									label='Employees Name (plural)'
									placeholder='Eg. employees'
									value={options["general-settings"]["employee-name-plural"]}
									setOption={updateOption}
								/>
								<TextInput
									id='employee-name-singular'
									label='Employees Name (singular)'
									placeholder='Eg. employee'
									value={options["general-settings"]["employee-name-singular"]}
									setOption={updateOption}
								/>
								<TextInput
									id='employee-url-key'
									label='Employees URL Key'
									value={options["general-settings"]["employee-url-key"]}
									setOption={updateOption}
									placeholder='Eg. employees'
								/>
							</div>
						</div>
					</div>
				</SettingsCard>

					</>
				)}

				{/* Syncing Banner - show regardless of loading state */}
				{(syncData?.is_initiating || syncData?.is_processing || syncData?.queue_count > 0) && (
					<SyncingBanner options={options} syncData={syncData} />
				)}
				
				{/* Error Alert */}
				{syncData && syncData.syncRunning == 2 && (
					<div
						className='bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded fixed md:bottom-12 bottom-0.5 m-4 md:m-0'
						role='alert'
					>
						<strong className='font-bold'>
							Syncing terminated due to an API error.
						</strong>
						<span> - </span>
						<span className='block sm:inline'>
							Please try again or contact support.
						</span>
					</div>
				)}
			</div>
		</SettingsLayout>
	);
};

export default GeneralSettings;
