import { useState } from 'react';
import {
	WandSparkles,
	FileSearch,
	Star,
	CircleCheck,
	Circle,
	ShieldCheck,
	Users,
	User,
} from 'lucide-react';
import { Spinner } from '@/components/ui/spinner';
import OnboardingLayout from '@/features/onboarding/OnboardingLayout';
import { post, getWordPressConfig } from '@/api/client';
import { logError } from '@/errors/logger';
import { getErrorMessage } from '@/utils/errorMessages';
import { cn } from '@/lib/utils';

const AUTOMATIC_FIXES = [
	'Missing image descriptions',
	'SEO titles and descriptions',
	'Broken links',
	'Local business details',
];

const AutomaticCard = ({ selected, onClick }) => (
	<div
		className={cn(
			'relative rounded-2xl border-2 bg-magenta-50/60 p-6 flex flex-col transition-all',
			selected ? 'border-magenta-300' : 'border-magenta-200/60'
		)}
	>
		<div className="inline-flex items-center gap-1.5 mb-4 text-magenta-500">
			<Star size={16} strokeWidth={2.5} fill="currentColor" />
			<span className="small-bold">Recommended</span>
		</div>

		<div className="flex items-start gap-4 mb-5">
			<div
				className="size-12 rounded-xl bg-magenta-100 flex items-center justify-center shrink-0"
				aria-hidden="true"
			>
				<WandSparkles size={22} strokeWidth={2.25} className="text-magenta-500" />
			</div>
			<div className="flex-1 min-w-0">
				<h4 className="heading-h4 my-0! mb-1!">Let Flavio handle it</h4>
				<p className="paragraph-regular text-magenta-500 mt-1! mb-0!">
					Recommended for most businesses
				</p>
			</div>
		</div>

		<div className="border-t border-magenta-200/60 mb-5" />

		<p className="paragraph-regular text-foreground my-0! mb-3!">
			Flavio automatically fixes safe issues like:
		</p>
		<ul className="space-y-2 mb-5 list-none p-0">
			{AUTOMATIC_FIXES.map((label) => (
				<li
					key={label}
					className="flex items-center gap-2.5 small-regular text-foreground my-1!"
				>
					<CircleCheck
						size={18}
						strokeWidth={2}
						className="text-green-600 shrink-0"
						fill="white"
					/>
					<span>{label}</span>
				</li>
			))}
		</ul>

		<div className="flex items-start gap-2.5 p-3 rounded-lg bg-green-50 border border-green-100 mb-5">
			<ShieldCheck
				size={18}
				strokeWidth={2}
				className="text-green-600 shrink-0 mt-0.5"
			/>
			<p className="small-regular text-foreground my-0!">
				You'll get a simple summary of what changed, and you can undo
				anything anytime.
			</p>
		</div>

		<div className="flex items-start gap-2.5 mb-6">
			<User size={18} strokeWidth={2} className="text-magenta-500 shrink-0 mt-0.5" />
			<p className="small-regular text-foreground my-0!">
				<span className="small-bold">Best for: </span>
				Busy business owners who want results without the manual work.
			</p>
		</div>

		<div className="mt-auto">
			<button
				type="button"
				onClick={onClick}
				aria-pressed={selected}
				className={cn(
					'w-full flex items-center justify-center gap-2 rounded-lg py-3 px-4 paragraph-bold transition-all cursor-pointer',
					'focus:outline-none focus:ring-2 focus:ring-magenta-500 focus:ring-offset-2',
					selected
						? 'bg-magenta-500 text-white hover:bg-magenta-600'
						: 'bg-white text-magenta-500 border-2 border-magenta-500 hover:bg-magenta-50'
				)}
			>
				{selected ? (
					<CircleCheck size={18} strokeWidth={2.25} fill="white" className="text-magenta-500" />
				) : (
					<Circle size={18} strokeWidth={2.25} />
				)}
				<span>Automatic mode</span>
			</button>
		</div>
	</div>
);

const ReviewCard = ({ selected, onClick }) => (
	<div
		className={cn(
			'relative rounded-2xl border-2 bg-white p-6 flex flex-col transition-all',
			selected ? 'border-blue-400' : 'border-neutral-200'
		)}
	>
		<div className="flex items-start gap-4 mb-5 mt-7">
			<div
				className="size-12 rounded-xl bg-blue-100 flex items-center justify-center shrink-0"
				aria-hidden="true"
			>
				<FileSearch size={22} strokeWidth={2.25} className="text-blue-600" />
			</div>
			<div className="flex-1 min-w-0">
				<h4 className="heading-h4 my-0! mb-1!">Ask before changing anything</h4>
				<p className="paragraph-regular text-blue-600 mt-1! mb-0!">
					Full review before updates
				</p>
			</div>
		</div>

		<div className="border-t border-neutral-200 mb-5" />

		<div className="space-y-4 mb-5">
			<p className="paragraph-regular text-foreground my-0!">
				Flavio will prepare improvements and show you a preview before
				anything goes live on your site.
			</p>
			<p className="paragraph-regular text-foreground my-0!">
				You stay fully in control of every change.
			</p>
		</div>

		<div className="flex items-start gap-2.5 mb-6 mt-auto">
			<Users size={18} strokeWidth={2} className="text-blue-600 shrink-0 mt-0.5" />
			<p className="small-regular text-foreground my-0!">
				<span className="small-bold">Best for: </span>
				Hands-on users, agencies, or websites with stricter review processes.
			</p>
		</div>

		<div>
			<button
				type="button"
				onClick={onClick}
				aria-pressed={selected}
				className={cn(
					'w-full flex items-center justify-center gap-2 rounded-lg py-3 px-4 paragraph-bold transition-all cursor-pointer',
					'focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2',
					selected
						? 'bg-blue-600 text-white hover:bg-blue-700'
						: 'bg-white text-blue-600 border-2 border-blue-600 hover:bg-blue-50'
				)}
			>
				{selected ? (
					<CircleCheck size={18} strokeWidth={2.25} fill="white" className="text-blue-600" />
				) : (
					<Circle size={18} strokeWidth={2.25} />
				)}
				<span>Review mode</span>
			</button>
		</div>
	</div>
);

// Pause after picking a card so the selection registers visually before
// the step advances.
const SELECTION_DELAY_MS = 600;

/**
 * AgentMode Step
 *
 * User picks how Flavio should ship interventions: autonomous ('yolo') or
 * approval-gated ('ask'). No mode is preselected; picking a card saves the
 * preference and advances automatically.
 */
const AgentMode = ({ onNext }) => {
	const [selected, setSelected] = useState(null);
	const [isSubmitting, setIsSubmitting] = useState(false);
	const [error, setError] = useState(null);

	const { endpoints } = getWordPressConfig();

	const handleSelect = async (mode) => {
		if (isSubmitting) return;
		setSelected(mode);
		setIsSubmitting(true);
		setError(null);

		try {
			await Promise.all([
				post(endpoints.agentMode, {
					agent_mode: mode,
				}),
				new Promise((resolve) => setTimeout(resolve, SELECTION_DELAY_MS)),
			]);
			onNext({ agentMode: mode });
		} catch (err) {
			logError(err, {
				action: 'save_agent_mode',
				component: 'AgentMode',
				payload: { agent_mode: mode },
			});
			setError(
				getErrorMessage(
					err,
					'Failed to save your preference. Please try again.'
				)
			);
			setIsSubmitting(false);
		}
	};

	return (
		<OnboardingLayout title="Choose how Flavio works on your website" wide>
			<div className="mb-8">
				<p className="paragraph-regular text-foreground my-0!">
					Flavio can improve your website automatically, or ask for approval before making changes.
				</p>
			</div>

			{error && (
				<div className="mb-6 p-4 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="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6 items-stretch"
				role="radiogroup"
				aria-label="Choose how Flavio works on your website"
			>
				<AutomaticCard
					selected={selected === 'yolo'}
					onClick={() => handleSelect('yolo')}
				/>
				<ReviewCard
					selected={selected === 'ask'}
					onClick={() => handleSelect('ask')}
				/>
			</div>

			<div className="flex items-start justify-center gap-2.5 p-4 rounded-xl bg-neutral-100 mb-8">
				<ShieldCheck
					size={20}
					strokeWidth={2}
					className="text-green-600 shrink-0"
				/>
				<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 className="flex items-center justify-center h-6">
				{isSubmitting && (
					<span className="flex items-center gap-2 small-regular text-muted-foreground">
						<Spinner className="size-4" />
						Saving your preference...
					</span>
				)}
			</div>
		</OnboardingLayout>
	);
};

export default AgentMode;
