import React, { useState, useEffect, useCallback, useMemo, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { SketchPicker } from "react-color";
import { ArrowLeft, LoaderCircle, Check } from "lucide-react";
import { __ } from "@wordpress/i18n";

/**
 * Settings - Page for displaying plugin and poll settings
 */
export const Settings = ({ settingsData, isSettingsLoading, handleUpdateSettings }) => {
	const navigate = useNavigate();

	// Tabs state
	const [activeTab, setActiveTab] = useState("standard");

	// Poll settings state
	const [showPollVotes, setShowPollVotes] = useState(false);

	// State for colors - standard view
	const [questionBgColor, setQuestionBgColor] = useState("#000000");
	const [questionTextColor, setQuestionTextColor] = useState("#FFFFFF");
	const [optionsBgColor, setOptionsBgColor] = useState("#FFFFFF");
	const [optionBgColor, setOptionBgColor] = useState("#F1F5F9");
	const [optionTextColor, setOptionTextColor] = useState("#000000");

	// Hover state colors
	const [optionBgColorHover, setOptionBgColorHover] = useState("#E2E8F0");
	const [optionTextColorHover, setOptionTextColorHover] = useState("#000000");

	// Results bar color
	const [resultsBarColor, setResultsBarColor] = useState("#6E56CF");

	// Voted answer colors
	const [votedOptionBgColor, setVotedOptionBgColor] = useState("#EDE9FE");
	const [votedOptionTextColor, setVotedOptionTextColor] = useState("#4C1D95");

	// Non-voted answer colors
	const [nonVotedOptionBgColor, setNonVotedOptionBgColor] = useState("#F8F9FA");
	const [nonVotedOptionTextColor, setNonVotedOptionTextColor] = useState("#6B7280");

	// Demo hover state
	const [hoveredOption, setHoveredOption] = useState(null);

	// Selected option for the voted view
	const [selectedOption, setSelectedOption] = useState(1);

	// Loading state for save
	const [isSaving, setIsSaving] = useState(false);

	// Refs for preview elements - used for direct DOM updates
	const previewRefs = useRef({});

	// Clear refs when switching tabs to prevent stale references
	useEffect(() => {
		// Clear array refs when switching tabs
		previewRefs.current = {};
	}, [activeTab]);

	// Function to register preview element refs
	const registerPreviewRef = useCallback((key, element) => {
		if (element) {
			previewRefs.current[key] = element;
		}
	}, []);

	// Function to update preview elements directly in DOM
	const updatePreviewColor = useCallback((key, color) => {
		const elements = previewRefs.current[key];
		if (elements) {
			if (Array.isArray(elements)) {
				elements.forEach((el) => {
					if (el && el.style) {
						if (key.includes("Text") || key.includes("color")) {
							el.style.color = color;
						} else {
							el.style.backgroundColor = color;
						}
					}
				});
			} else if (elements.style) {
				if (key.includes("Text") || key.includes("color")) {
					elements.style.color = color;
				} else {
					elements.style.backgroundColor = color;
				}
			}
		}
	}, []);

	// Load settings from props if available
	useEffect(() => {
		if (settingsData && !isSettingsLoading) {
			setShowPollVotes(settingsData.showPollVotes || false);

			if (settingsData.colors) {
				const colors = settingsData.colors;

				if (colors.questionBg) setQuestionBgColor(colors.questionBg);
				if (colors.questionText) setQuestionTextColor(colors.questionText);
				if (colors.optionsBg) setOptionsBgColor(colors.optionsBg);
				if (colors.optionBg) setOptionBgColor(colors.optionBg);
				if (colors.optionText) setOptionTextColor(colors.optionText);
				if (colors.optionBgHover) setOptionBgColorHover(colors.optionBgHover);
				if (colors.optionTextHover) setOptionTextColorHover(colors.optionTextHover);
				if (colors.resultsBar) setResultsBarColor(colors.resultsBar);
				if (colors.votedOptionBg) setVotedOptionBgColor(colors.votedOptionBg);
				if (colors.votedOptionText) setVotedOptionTextColor(colors.votedOptionText);
				if (colors.nonVotedOptionBg) setNonVotedOptionBgColor(colors.nonVotedOptionBg);
				if (colors.nonVotedOptionText) setNonVotedOptionTextColor(colors.nonVotedOptionText);
			}
		}
	}, [settingsData, isSettingsLoading]);

	// Get settings data to save
	const getSettingsToSave = () => {
		return {
			showPollResults: true,
			showPollVotes,
			colors: {
				questionBg: questionBgColor,
				questionText: questionTextColor,
				optionsBg: optionsBgColor,
				optionBg: optionBgColor,
				optionText: optionTextColor,
				optionBgHover: optionBgColorHover,
				optionTextHover: optionTextColorHover,
				resultsBar: resultsBarColor,
				votedOptionBg: votedOptionBgColor,
				votedOptionText: votedOptionTextColor,
				nonVotedOptionBg: nonVotedOptionBgColor,
				nonVotedOptionText: nonVotedOptionTextColor,
			},
		};
	};

	// Handle save
	const handleSave = async () => {
		setIsSaving(true);
		try {
			await handleUpdateSettings(getSettingsToSave());
			navigate("/settings");
		} catch (error) {
			console.error("Error saving settings:", error);
		} finally {
			setIsSaving(false);
		}
	};

	const handleBackClick = () => {
		navigate("/");
	};

	// Color picker configuration - Standard tab
	const standardColorConfig = [
		{
			id: "questionBgColor",
			label: __("Question background color", "socialpoll"),
			value: questionBgColor,
			setter: setQuestionBgColor,
			previewKey: "questionBg",
			hoverOption: false,
		},
		{
			id: "questionTextColor",
			label: __("Question text color", "socialpoll"),
			value: questionTextColor,
			setter: setQuestionTextColor,
			previewKey: "questionText",
			hoverOption: false,
		},
		{
			id: "optionsBgColor",
			label: __("Options background color", "socialpoll"),
			value: optionsBgColor,
			setter: setOptionsBgColor,
			previewKey: "optionsBg",
			hoverOption: false,
		},
		{
			id: "optionBgColor",
			label: __("Option background color", "socialpoll"),
			value: optionBgColor,
			setter: setOptionBgColor,
			previewKey: "optionBg",
			hoverOption: true,
			hoverValue: optionBgColorHover,
			hoverSetter: setOptionBgColorHover,
			hoverId: "optionBgColorHover",
			hoverPreviewKey: "optionBgHover",
		},
		{
			id: "optionTextColor",
			label: __("Option text color", "socialpoll"),
			value: optionTextColor,
			setter: setOptionTextColor,
			previewKey: "optionText",
			hoverOption: true,
			hoverValue: optionTextColorHover,
			hoverSetter: setOptionTextColorHover,
			hoverId: "optionTextColorHover",
			hoverPreviewKey: "optionTextHover",
		},
	];

	// Color picker configuration - Voted tab
	const votedColorConfig = [
		{
			id: "resultsBarColor",
			label: __("Results bar color", "socialpoll"),
			value: resultsBarColor,
			setter: setResultsBarColor,
			previewKey: "resultsBar",
			hoverOption: false,
		},
		{
			id: "votedOptionBgColor",
			label: __("Voted option background", "socialpoll"),
			value: votedOptionBgColor,
			setter: setVotedOptionBgColor,
			previewKey: "votedOptionBg",
			hoverOption: false,
		},
		{
			id: "votedOptionTextColor",
			label: __("Voted option text", "socialpoll"),
			value: votedOptionTextColor,
			setter: setVotedOptionTextColor,
			previewKey: "votedOptionText",
			hoverOption: false,
		},
		{
			id: "nonVotedOptionBgColor",
			label: __("Other options background", "socialpoll"),
			value: nonVotedOptionBgColor,
			setter: setNonVotedOptionBgColor,
			previewKey: "nonVotedOptionBg",
			hoverOption: false,
		},
		{
			id: "nonVotedOptionTextColor",
			label: __("Other options text", "socialpoll"),
			value: nonVotedOptionTextColor,
			setter: setNonVotedOptionTextColor,
			previewKey: "nonVotedOptionText",
			hoverOption: false,
		},
	];

	// Common BlockPicker colors
	const pickerColors = [
		"#000000",
		"#FFFFFF",
		"#F1F5F9",
		"#F8F9FA",
		"#E2E8F0",
		"#CBD5E1",
		"#6B7280",
		"#6E56CF",
		"#4C1D95",
		"#EDE9FE",
		"#F87171",
		"#10B981",
	];

	// Predefined color themes
	const colorThemes = [
		{
			name: "Fall Orange",
			preview: {
				from: "#d2691e",
				to: "#fab12f",
			},
			colors: {
				questionBg: "#d2691e",
				questionText: "#fff8f0",
				optionsBg: "#ffffff",
				optionBg: "#f8f9fa",
				optionText: "#4a2c17",
				optionBgHover: "#fff4e6",
				optionTextHover: "#4a2c17",
				resultsBar: "#fab12f",
				votedOptionBg: "#fff4e6",
				votedOptionText: "#4a2c17",
				nonVotedOptionBg: "#f8f9fa",
				nonVotedOptionText: "#4a2c17",
			},
		},
		{
			name: "Coastal Sage",
			preview: {
				from: "#34656D",
				to: "#FAEAB1",
			},
			colors: {
				questionBg: "#34656D",
				questionText: "#FAF8F1",
				optionsBg: "#ffffff",
				optionBg: "#f8f9fa",
				optionText: "#334443",
				optionBgHover: "#FAF8F1",
				optionTextHover: "#334443",
				resultsBar: "#FAEAB1",
				votedOptionBg: "#FAF8F1",
				votedOptionText: "#334443",
				nonVotedOptionBg: "#f8f9fa",
				nonVotedOptionText: "#334443",
			},
		},
		{
			name: "Olive Garden",
			preview: {
				from: "#606c38",
				to: "#bc6c25",
			},
			colors: {
				questionBg: "#606c38",
				questionText: "#fefae0",
				optionsBg: "#ffffff",
				optionBg: "#f8f9fa",
				optionText: "#283618",
				optionBgHover: "#fefae0",
				optionTextHover: "#283618",
				resultsBar: "#dda15e",
				votedOptionBg: "#fefae0",
				votedOptionText: "#283618",
				nonVotedOptionBg: "#f8f9fa",
				nonVotedOptionText: "#283618",
			},
		},
		{
			name: "Ocean Breeze",
			preview: {
				from: "#03045e",
				to: "#00b4d8",
			},
			colors: {
				questionBg: "#03045e",
				questionText: "#caf0f8",
				optionsBg: "#ffffff",
				optionBg: "#f8f9fa",
				optionText: "#03045e",
				optionBgHover: "#caf0f8",
				optionTextHover: "#03045e",
				resultsBar: "#90e0ef",
				votedOptionBg: "#caf0f8",
				votedOptionText: "#03045e",
				nonVotedOptionBg: "#f8f9fa",
				nonVotedOptionText: "#03045e",
			},
		},
		{
			name: "Light Steel",
			preview: {
				from: "#343a40",
				to: "#adb5bd",
			},
			colors: {
				questionBg: "#343a40",
				questionText: "#f8f9fa",
				optionsBg: "#ffffff",
				optionBg: "#f8f9fa",
				optionText: "#212529",
				optionBgHover: "#e9ecef",
				optionTextHover: "#212529",
				resultsBar: "#adb5bd",
				votedOptionBg: "#e9ecef",
				votedOptionText: "#212529",
				nonVotedOptionBg: "#f8f9fa",
				nonVotedOptionText: "#212529",
			},
		},
		{
			name: "Desert Rose",
			preview: {
				from: "#8b5a3c",
				to: "#daa49a",
			},
			colors: {
				questionBg: "#8b5a3c",
				questionText: "#fdf6f3",
				optionsBg: "#ffffff",
				optionBg: "#f8f9fa",
				optionText: "#3d2621",
				optionBgHover: "#fdf6f3",
				optionTextHover: "#3d2621",
				resultsBar: "#daa49a",
				votedOptionBg: "#fdf6f3",
				votedOptionText: "#3d2621",
				nonVotedOptionBg: "#f8f9fa",
				nonVotedOptionText: "#3d2621",
			},
		},
		{
			name: "Forest Mist",
			preview: {
				from: "#2d6a4f",
				to: "#95d5b2",
			},
			colors: {
				questionBg: "#2d6a4f",
				questionText: "#f1faee",
				optionsBg: "#ffffff",
				optionBg: "#f8f9fa",
				optionText: "#1b5e20",
				optionBgHover: "#d8f3dc",
				optionTextHover: "#1b5e20",
				resultsBar: "#95d5b2",
				votedOptionBg: "#d8f3dc",
				votedOptionText: "#1b5e20",
				nonVotedOptionBg: "#f8f9fa",
				nonVotedOptionText: "#1b5e20",
			},
		},
		{
			name: "Twilight Plum",
			preview: {
				from: "#5e548e",
				to: "#be95c4",
			},
			colors: {
				questionBg: "#5e548e",
				questionText: "#f8f7ff",
				optionsBg: "#ffffff",
				optionBg: "#f8f9fa",
				optionText: "#352f44",
				optionBgHover: "#e0d3ff",
				optionTextHover: "#352f44",
				resultsBar: "#be95c4",
				votedOptionBg: "#e0d3ff",
				votedOptionText: "#352f44",
				nonVotedOptionBg: "#f8f9fa",
				nonVotedOptionText: "#352f44",
			},
		},
		{
			name: "Clay & Moss",
			preview: {
				from: "#704e2e",
				to: "#87a878",
			},
			colors: {
				questionBg: "#704e2e",
				questionText: "#faf8f3",
				optionsBg: "#ffffff",
				optionBg: "#f8f9fa",
				optionText: "#3a2e20",
				optionBgHover: "#e8f5e8",
				optionTextHover: "#3a2e20",
				resultsBar: "#87a878",
				votedOptionBg: "#e8f5e8",
				votedOptionText: "#3a2e20",
				nonVotedOptionBg: "#f8f9fa",
				nonVotedOptionText: "#3a2e20",
			},
		},
		{
			name: "Nordic Frost",
			preview: {
				from: "#4a5568",
				to: "#9fb3c8",
			},
			colors: {
				questionBg: "#4a5568",
				questionText: "#f7fafc",
				optionsBg: "#ffffff",
				optionBg: "#f8f9fa",
				optionText: "#2d3748",
				optionBgHover: "#e2e8f0",
				optionTextHover: "#2d3748",
				resultsBar: "#9fb3c8",
				votedOptionBg: "#e2e8f0",
				votedOptionText: "#2d3748",
				nonVotedOptionBg: "#f8f9fa",
				nonVotedOptionText: "#2d3748",
			},
		},
		{
			name: "Autumn Spice",
			preview: {
				from: "#9c6644",
				to: "#e9c46a",
			},
			colors: {
				questionBg: "#9c6644",
				questionText: "#fdf4e3",
				optionsBg: "#ffffff",
				optionBg: "#f8f9fa",
				optionText: "#432818",
				optionBgHover: "#fdf4e3",
				optionTextHover: "#432818",
				resultsBar: "#e9c46a",
				votedOptionBg: "#fdf4e3",
				votedOptionText: "#432818",
				nonVotedOptionBg: "#f8f9fa",
				nonVotedOptionText: "#432818",
			},
		},
		{
			name: "Mountain Lake",
			preview: {
				from: "#264653",
				to: "#2a9d8f",
			},
			colors: {
				questionBg: "#264653",
				questionText: "#e9f5f2",
				optionsBg: "#ffffff",
				optionBg: "#f8f9fa",
				optionText: "#1a2e35",
				optionBgHover: "#d4f1ea",
				optionTextHover: "#1a2e35",
				resultsBar: "#2a9d8f",
				votedOptionBg: "#d4f1ea",
				votedOptionText: "#1a2e35",
				nonVotedOptionBg: "#f8f9fa",
				nonVotedOptionText: "#1a2e35",
			},
		},
		{
			name: "Dusty Cedar",
			preview: {
				from: "#6b4423",
				to: "#c9ada7",
			},
			colors: {
				questionBg: "#6b4423",
				questionText: "#f9f5f3",
				optionsBg: "#ffffff",
				optionBg: "#f8f9fa",
				optionText: "#3e2723",
				optionBgHover: "#f4e7e4",
				optionTextHover: "#3e2723",
				resultsBar: "#c9ada7",
				votedOptionBg: "#f4e7e4",
				votedOptionText: "#3e2723",
				nonVotedOptionBg: "#f8f9fa",
				nonVotedOptionText: "#3e2723",
			},
		},
	];

	// Function to apply a color theme
	const applyColorTheme = useCallback((theme) => {
		const colors = theme.colors;
		setQuestionBgColor(colors.questionBg);
		setQuestionTextColor(colors.questionText);
		setOptionsBgColor(colors.optionsBg);
		setOptionBgColor(colors.optionBg);
		setOptionTextColor(colors.optionText);
		setOptionBgColorHover(colors.optionBgHover);
		setOptionTextColorHover(colors.optionTextHover);
		setResultsBarColor(colors.resultsBar);
		setVotedOptionBgColor(colors.votedOptionBg);
		setVotedOptionTextColor(colors.votedOptionText);
		setNonVotedOptionBgColor(colors.nonVotedOptionBg);
		setNonVotedOptionTextColor(colors.nonVotedOptionText);
	}, []);

	// Individual color picker component with local state for smooth updates
	// Wrapped in React.memo to prevent unnecessary re-renders
	const ColorPicker = React.memo(
		({ label, value, setter, pickerColors, previewKey }) => {
			const [isOpen, setIsOpen] = useState(false);
			const [tempColor, setTempColor] = useState(value);

			// Update temp color when popover opens or value changes externally
			useEffect(() => {
				if (isOpen) {
					setTempColor(value);
				} else {
					// Sync with external changes when closed
					setTempColor(value);
				}
			}, [isOpen, value]);

			// Handle color change with direct DOM updates for preview
			const handleLocalColorChange = useCallback(
				(color) => {
					setTempColor(color.hex);
					// Update preview directly in DOM (no React re-render)
					if (previewKey) {
						updatePreviewColor(previewKey, color.hex);
					}
				},
				[previewKey]
			);

			// Apply color to React state only when closing the popover
			const handleOpenChange = useCallback(
				(open) => {
					setIsOpen(open);
					if (!open && tempColor !== value) {
						// Update React state when closing
						setter(tempColor);
					}
				},
				[tempColor, value, setter]
			);

			return (
				<>
					<Popover open={isOpen} onOpenChange={handleOpenChange}>
						<PopoverTrigger asChild>
							<Button
								type="button"
								variant="outline"
								className="w-6 h-6 p-0 border !rounded-sm"
								style={{ backgroundColor: tempColor }}
								aria-label={label}>
								<span className="sr-only">{__("Open color picker", "socialpoll")}</span>
							</Button>
						</PopoverTrigger>
						<PopoverContent className="w-auto p-0 border-none shadow-lg" align="start">
							<SketchPicker
								colors={pickerColors}
								color={tempColor}
								onChange={handleLocalColorChange}
								onChangeComplete={handleLocalColorChange}
								disableAlpha
							/>
						</PopoverContent>
					</Popover>
					<div className="w-24 font-mono text-sm uppercase">{value}</div>
				</>
			);
		},
		(prevProps, nextProps) => {
			// Custom comparison function for React.memo
			// Only re-render if these specific props change
			return (
				prevProps.value === nextProps.value &&
				prevProps.label === nextProps.label &&
				prevProps.pickerColors === nextProps.pickerColors &&
				prevProps.setter === nextProps.setter
			);
		}
	);

	// Color picker with hover options
	const ColorPickerGroup = ({ colorConfig }) => (
		<div className="grid grid-cols-1 gap-5">
			{colorConfig.map((config) => (
				<div key={config.id} className="flex flex-col items-start gap-3">
					<Label htmlFor={config.id} className="text-right">
						{config.label}
					</Label>
					<div className="flex items-center gap-2">
						<ColorPicker
							label={config.label}
							value={config.value}
							setter={config.setter}
							pickerColors={pickerColors}
							previewKey={config.previewKey}
						/>

						{/* Hover color option */}
						{config.hoverOption && (
							<>
								<Label className="ml-2 mr-1">{__("Hover state", "socialpoll")}:</Label>
								<ColorPicker
									label={`${__("Hover state", "socialpoll")} ${config.label}`}
									value={config.hoverValue}
									setter={config.hoverSetter}
									pickerColors={pickerColors}
									previewKey={config.hoverPreviewKey}
								/>
							</>
						)}
					</div>
				</div>
			))}
		</div>
	);

	// Standard poll preview
	const StandardPollPreview = () => (
		<div className="w-full grid grid-cols-1 gap-0 shadow-[10px_10px_20px_0px_rgba(0,0,0,0.05))] rounded-2xl overflow-hidden">
			<div
				ref={(el) => registerPreviewRef("questionBg", el)}
				className="w-full flex flex-col items-center p-5 text-center"
				style={{ backgroundColor: questionBgColor, color: questionTextColor }}>
				<h3 ref={(el) => registerPreviewRef("questionText", el)} className="!my-0" style={{ color: questionTextColor }}>
					{__("If you could have one superpower?", "socialpoll")}
				</h3>
			</div>
			<div
				ref={(el) => registerPreviewRef("optionsBg", el)}
				className="flex flex-col items-stretch gap-4 p-5"
				style={{ backgroundColor: optionsBgColor }}>
				{[
					__("Invisibility", "socialpoll"),
					__("Flying", "socialpoll"),
					__("Mind reading", "socialpoll"),
					__("Time travel", "socialpoll"),
				].map((option, index) => (
					<div
						key={`option-${index}`}
						ref={(el) => {
							if (hoveredOption === index) {
								registerPreviewRef("optionBgHover", el);
								registerPreviewRef("optionTextHover", el?.querySelector("span"));
							} else {
								// Store multiple option elements as array
								if (!previewRefs.current.optionBg) previewRefs.current.optionBg = [];
								if (!previewRefs.current.optionText) previewRefs.current.optionText = [];
								if (el && !previewRefs.current.optionBg.includes(el)) {
									previewRefs.current.optionBg.push(el);
								}
								const span = el?.querySelector("span");
								if (span && !previewRefs.current.optionText.includes(span)) {
									previewRefs.current.optionText.push(span);
								}
							}
						}}
						className="rounded-xl p-4 px-5 cursor-pointer transition-colors duration-150"
						style={{
							backgroundColor: hoveredOption === index ? optionBgColorHover : optionBgColor,
							color: hoveredOption === index ? optionTextColorHover : optionTextColor,
						}}
						onMouseEnter={() => setHoveredOption(index)}
						onMouseLeave={() => setHoveredOption(null)}
						onClick={() => setSelectedOption(index)}>
						<div className="flex flex-row items-center">
							<span className="text-base">{option}</span>
						</div>
					</div>
				))}
			</div>
		</div>
	);

	// Voted poll preview
	const VotedPollPreview = () => {
		const options = [
			{ text: __("Invisibility", "socialpoll"), percent: 15 },
			{ text: __("Flying", "socialpoll"), percent: 35 },
			{ text: __("Mind reading", "socialpoll"), percent: 12 },
			{ text: __("Time travel", "socialpoll"), percent: 38 },
		];

		return (
			<div className="w-full grid grid-cols-1 gap-0 shadow-[10px_10px_20px_0px_rgba(0,0,0,0.05))] rounded-2xl overflow-hidden">
				<div
					ref={(el) => registerPreviewRef("questionBg", el)}
					className="w-full flex flex-col items-center p-5 text-center"
					style={{ backgroundColor: questionBgColor, color: questionTextColor }}>
					<h3
						ref={(el) => registerPreviewRef("questionText", el)}
						className="!my-0"
						style={{ color: questionTextColor }}>
						{__("If you could have one superpower?", "socialpoll")}
					</h3>
				</div>
				<div
					ref={(el) => registerPreviewRef("optionsBg", el)}
					className="flex flex-col items-stretch gap-4 p-5"
					style={{ backgroundColor: optionsBgColor }}>
					{options.map((option, index) => {
						const isSelected = index === selectedOption;

						// TODO: Make inverted colors on options
						return (
							<div
								key={`voted-option-${index}`}
								ref={(el) => {
									if (isSelected) {
										registerPreviewRef("votedOptionBg", el);
									} else {
										if (!previewRefs.current.nonVotedOptionBg) previewRefs.current.nonVotedOptionBg = [];
										if (el && !previewRefs.current.nonVotedOptionBg.includes(el)) {
											previewRefs.current.nonVotedOptionBg.push(el);
										}
									}
								}}
								className="rounded-xl p-4 px-5 relative overflow-hidden"
								style={{
									backgroundColor: isSelected ? votedOptionBgColor : nonVotedOptionBgColor,
								}}>
								<div
									ref={(el) => {
										if (!previewRefs.current.resultsBar) previewRefs.current.resultsBar = [];
										if (el && !previewRefs.current.resultsBar.includes(el)) {
											previewRefs.current.resultsBar.push(el);
										}
									}}
									className="absolute top-0 left-0 h-full"
									style={{
										width: `${option.percent}%`,
										backgroundColor: resultsBarColor,
									}}
								/>

								<div className="flex flex-row items-center justify-between relative z-10">
									<span
										ref={(el) => {
											if (isSelected) {
												if (!previewRefs.current.votedOptionText) previewRefs.current.votedOptionText = [];
												if (el && !previewRefs.current.votedOptionText.includes(el)) {
													previewRefs.current.votedOptionText.push(el);
												}
											} else {
												if (!previewRefs.current.nonVotedOptionText) previewRefs.current.nonVotedOptionText = [];
												if (el && !previewRefs.current.nonVotedOptionText.includes(el)) {
													previewRefs.current.nonVotedOptionText.push(el);
												}
											}
										}}
										className={"text-base flex flex-row items-center gap-2" + (isSelected ? " font-bold" : "")}
										style={{ color: isSelected ? votedOptionTextColor : nonVotedOptionTextColor }}>
										{option.text} {isSelected && <Check size={20} />}
									</span>
									<span
										ref={(el) => {
											if (isSelected) {
												if (!previewRefs.current.votedOptionText) previewRefs.current.votedOptionText = [];
												if (el && !previewRefs.current.votedOptionText.includes(el)) {
													previewRefs.current.votedOptionText.push(el);
												}
											} else {
												if (!previewRefs.current.nonVotedOptionText) previewRefs.current.nonVotedOptionText = [];
												if (el && !previewRefs.current.nonVotedOptionText.includes(el)) {
													previewRefs.current.nonVotedOptionText.push(el);
												}
											}
										}}
										className={"text-sm" + (isSelected ? " font-bold" : " font-medium")}
										style={{ color: isSelected ? votedOptionTextColor : nonVotedOptionTextColor }}>
										{option.percent}%
									</span>
								</div>
							</div>
						);
					})}

					{showPollVotes && (
						<div className="text-xs text-left mt-1 text-gray-500">{__("Total: 20 votes", "socialpoll")}</div>
					)}
				</div>
			</div>
		);
	};

	if (isSettingsLoading) {
		return (
			<div className="flex justify-center items-center h-64">
				<LoaderCircle className="animate-spin h-8 w-8 text-primary" />
			</div>
		);
	}

	return (
		<div className="socialpoll-admin-app mt-5 mr-5 ml-1">
			<div className="bg-white p-5 rounded-xl flex flex-col gap-5">
				{/* Header with back button */}
				<div className="flex items-center gap-4">
					<Button variant="outline" size="icon" onClick={handleBackClick}>
						<ArrowLeft />
					</Button>
					<div>
						<h1 className="!text-2xl font-bold !mb-0 !mt-0">{__("SocialPoll Settings", "socialpoll")}</h1>
					</div>
				</div>

				{/* Display settings */}
				<div className="grid grid-cols-2 gap-3 items-start">
					<div className="flex flex-col items-start gap-3">
						<h2 className="!my-0">{__("Display settings", "socialpoll")}</h2>
						<div className="w-full flex flex-col text-muted-foreground">{__("Edit poll settings", "socialpoll")}</div>
					</div>
					<div className="grid grid-cols-1 gap-5">
						<div className="flex items-center space-x-2">
							<Switch id="show-poll-votes" checked={showPollVotes} onCheckedChange={setShowPollVotes} />
							<Label htmlFor="show-poll-votes">{__("Show total votes after voting", "socialpoll")}</Label>
						</div>
					</div>
				</div>

				{/* Style settings */}
				<div className="my-6">
					<h2 className="!my-0 mb-4">{__("Style settings", "socialpoll")}</h2>

					{/* Color Theme Selector */}
					<div className="">
						<h3 className="!text-sm font-medium mb-3">{__("Color Themes", "socialpoll")}</h3>
						<p className="text-muted-foreground">
							{__("Quickly apply a predefined color theme to your polls", "socialpoll")}
						</p>
						<div className="flex flex-wrap gap-2">
							{colorThemes.map((theme, index) => (
								<Button
									key={index}
									type="button"
									variant="outline"
									className="flex items-center gap-2 h-auto py-2 px-3"
									onClick={() => applyColorTheme(theme)}>
									<div
										className="w-5 h-5 rounded-full border-2 border-gray-200"
										style={{
											background: `linear-gradient(90deg, ${theme.preview.from} 0%, ${theme.preview.from} 50%, ${theme.preview.to} 50%, ${theme.preview.to} 100%)`,
										}}
									/>
									<span className="text-sm">{theme.name}</span>
								</Button>
							))}
						</div>
					</div>

					<Tabs defaultValue="standard" value={activeTab} onValueChange={setActiveTab}>
						<TabsList className="grid w-full grid-cols-2 mb-4 mt-6">
							<TabsTrigger value="standard" className="!border-transparent">
								{__("Standard Poll", "socialpoll")}
							</TabsTrigger>
							<TabsTrigger value="voted" className="!border-transparent">
								{__("Voted Poll", "socialpoll")}
							</TabsTrigger>
						</TabsList>

						<div className="grid grid-cols-2 gap-10">
							<div className="flex flex-col items-start gap-5">
								<TabsContent value="standard" className="w-full mt-0">
									<StandardPollPreview />
								</TabsContent>

								<TabsContent value="voted" className="w-full mt-0">
									<VotedPollPreview />
								</TabsContent>
							</div>

							<div className="flex flex-col gap-6">
								<TabsContent value="standard" className="mt-0">
									<ColorPickerGroup colorConfig={standardColorConfig} />
								</TabsContent>

								<TabsContent value="voted" className="mt-0">
									<ColorPickerGroup colorConfig={votedColorConfig} />
								</TabsContent>
							</div>
						</div>
					</Tabs>
				</div>

				{/* Action buttons */}
				<div className="flex gap-3">
					<Button variant="outline" onClick={handleBackClick}>
						{__("Cancel", "socialpoll")}
					</Button>
					<Button onClick={handleSave} disabled={isSaving}>
						{isSaving && <LoaderCircle className="animate-spin mr-2" />}
						{isSaving ? __("Saving changes...", "socialpoll") : __("Save changes", "socialpoll")}
					</Button>
				</div>
			</div>
		</div>
	);
};

export default Settings;
