import { useState } from 'react';
import {
	ArrowLeft,
	WandSparkles,
	FileSearch,
	CircleCheck,
	Circle,
	ShieldCheck,
} from 'lucide-react';
import SpeechBubble from '@/components/ui/speech-bubble';
import { Spinner } from '@/components/ui/spinner';
import { getWordPressConfig, post } from '@/api/client';
import useOnboarding from '@/hooks/useOnboarding';
import { logError } from '@/errors/logger';
import { getErrorMessage } from '@/utils/errorMessages';
import { cn } from '@/lib/utils';

const MODES = [
	{
		id: 'yolo',
		icon: WandSparkles,
		title: 'Automatic',
		subtitle: 'Let Flavio handle it',
		description:
			'Flavio fixes safe issues automatically (image descriptions, SEO titles, broken links, local details) and shows you a summary. You can undo anything anytime.',
		accent: 'magenta',
	},
	{
		id: 'ask',
		icon: FileSearch,
		title: 'Review',
		subtitle: 'Ask before changing anything',
		description:
			"Flavio prepares improvements and shows you a preview before anything goes live. Nothing changes on your site until you approve it.",
		accent: 'blue',
	},
];

const ModeOption = ({ mode, selected, disabled, onClick }) => {
	const Icon = mode.icon;
	const isMagenta = mode.accent === 'magenta';
	return (
		<button
			type="button"
			onClick={onClick}
			disabled={disabled}
			aria-pressed={selected}
			className={cn(
				'w-full flex items-start gap-4 rounded-lg border-2 p-5 text-left transition-all cursor-pointer',
				'disabled:opacity-60 disabled:cursor-not-allowed',
				selected
					? isMagenta
						? 'border-magenta-400 bg-magenta-50/60'
						: 'border-blue-400 bg-blue-50/60'
					: 'border-border bg-card hover:border-neutral-300'
			)}
		>
			<div
				className={cn(
					'size-10 rounded-xl flex items-center justify-center shrink-0',
					isMagenta ? 'bg-magenta-100' : 'bg-blue-100'
				)}
				aria-hidden="true"
			>
				<Icon
					size={20}
					strokeWidth={2.25}
					className={isMagenta ? 'text-magenta-500' : 'text-blue-600'}
				/>
			</div>

			<div className="flex-1 min-w-0">
				<div className="flex items-baseline gap-1.5">
					<h3 className="heading-h4 my-0!">{mode.title}</h3>
					<span className="small-regular text-muted-foreground">
						· {mode.subtitle}
					</span>
				</div>
				<p className="small-regular text-muted-foreground mt-1! mb-0!">
					{mode.description}
				</p>
			</div>

			<div className="shrink-0 mt-0.5" aria-hidden="true">
				{selected ? (
					<CircleCheck
						size={22}
						strokeWidth={2}
						className={isMagenta ? 'text-magenta-500' : 'text-blue-600'}
						fill="white"
					/>
				) : (
					<Circle size={22} strokeWidth={2} className="text-neutral-300" />
				)}
			</div>
		</button>
	);
};

/**
 * PreferencesPage Component
 *
 * Behavior preferences for how Flavio works. For now this is the agent mode
 * (Automatic vs Review); future preferences can be added as more cards.
 *
 * Each change persists immediately via POST /agent-mode (optimistic, reverts
 * on failure) just like GoalProfilePage.
 */
const PreferencesPage = ({ onBack, transition }) => {
	const config = getWordPressConfig();
	const { data: profile } = useOnboarding();

	const [value, setValue] = useState(profile.agentMode || 'yolo');
	const [pending, setPending] = useState(null);
	const [error, setError] = useState(null);

	const handleSelect = async (next) => {
		if (next === value || pending) return;
		const prev = value;
		setPending(next);
		setError(null);
		setValue(next);
		try {
			await post(config.endpoints.agentMode, {
				agent_mode: next,
			});
		} catch (err) {
			logError(err, {
				action: 'save_agent_mode',
				component: 'PreferencesPage',
				payload: { agent_mode: next },
			});
			setValue(prev);
			setError(
				getErrorMessage(
					err,
					'Could not save your preference. Please try again.'
				)
			);
		} finally {
			setPending(null);
		}
	};

	const transitionClass =
		transition === 'action-enter'
			? 'animate-slide-in-from-right'
			: transition === 'action-exit'
				? 'animate-slide-out-to-right'
				: '';

	return (
		<main className={`flex-1 pt-8 pb-24 ${transitionClass}`}>
			<div className="max-w-3xl mx-auto px-8">
				<button
					type="button"
					onClick={onBack}
					className="inline-flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors cursor-pointer mb-6"
				>
					<ArrowLeft className="w-4 h-4" />
					Back
				</button>

				{/* Title */}
				<h1 className="heading-h1 leading-tight mb-2">Preferences</h1>
				<p className="paragraph-regular text-muted-foreground mb-8">
					Choose how I work on your website. You can change this anytime.
				</p>

				{/* Agent mode card */}
				<div className="rounded-lg border border-border bg-card p-6">
					<div className="flex items-center gap-3 mb-1">
						<div className="flex items-center justify-center w-10 h-10 rounded-full bg-magenta-50">
							<ShieldCheck className="w-5 h-5 text-magenta-500" />
						</div>
						<span className="label-semibold uppercase tracking-wider text-muted-foreground">
							How Flavio works
						</span>
					</div>
					<p className="small-regular text-muted-foreground mb-5 mt-3!">
						Decide whether Flavio applies safe improvements on its own
						or queues everything for your approval first.
					</p>

					{error && (
						<div className="mb-4 p-3 bg-destructive/10 border border-destructive/20 rounded-lg">
							<p className="small-regular text-destructive my-0!">
								<strong className="font-semibold">Error:</strong>{' '}
								{error}
							</p>
						</div>
					)}

					<div
						className="space-y-3"
						role="radiogroup"
						aria-label="How Flavio works"
					>
						{MODES.map((mode) => (
							<ModeOption
								key={mode.id}
								mode={mode}
								selected={value === mode.id}
								disabled={!!pending}
								onClick={() => handleSelect(mode.id)}
							/>
						))}
					</div>

					{pending && (
						<div className="mt-4 flex items-center gap-2">
							<Spinner className="size-4" />
							<span className="small-regular text-muted-foreground">
								Saving your preference...
							</span>
						</div>
					)}

					<div className="mt-5 flex items-start gap-2.5 p-3 rounded-lg bg-neutral-100">
						<ShieldCheck
							size={18}
							strokeWidth={2}
							className="text-green-600 shrink-0 mt-0.5"
						/>
						<p className="small-regular text-foreground my-0!">
							<span className="small-bold">
								Flavio only applies safe improvements
								automatically.
							</span>{' '}
							Advanced or risky changes will always require your
							approval.
						</p>
					</div>
				</div>

				{/* Mascot speech bubble */}
				<div className="flex items-start gap-2 mt-8">
					<img
						src={`${config?.pluginUrl || ''}js/public/onboarding.svg`}
						alt="Flavio"
						className="size-8 shrink-0"
						aria-hidden="true"
					/>
					<SpeechBubble arrow="left" className="ml-2">
						Change this whenever you like. I'll adapt right away.
					</SpeechBubble>
				</div>
			</div>
		</main>
	);
};

export default PreferencesPage;
