import { useState } from 'react';
import { Leaf, Bell, Mail, ChevronDown } from 'lucide-react';
import {
	Dialog,
	DialogContent,
	DialogTitle,
	DialogDescription,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import FlavioIcon from '@/components/ui/flavio-icon';
import { post, getWordPressConfig } from '@/api/client';
import { logError } from '@/errors/logger';
import { cn } from '@/lib/utils';

/**
 * WelcomeModal
 *
 * Shown once over the dashboard, right after onboarding completes. Reassures the
 * user that Flavio takes it from here and there's nothing for them to do.
 *
 * "Seen once" is persisted server-side: the backend folds `welcomeSeen` into
 * siteInfo, and dismissing the modal POSTs to mark it seen so it never returns.
 */

const ICON_PROPS = { size: 20, strokeWidth: 2, className: 'text-magenta-500' };

const FEATURES = [
	{
		icon: <Leaf {...ICON_PROPS} />,
		title: "There's nothing for you to do",
		description:
			"Seriously, relax. I'll keep improving your site on my own, a little at a time.",
	},
	{
		icon: <Bell {...ICON_PROPS} />,
		title: "I'll only reach out when it matters",
		description:
			"If I hit something that needs your call, I'll ask you right here. Otherwise I won't bug you.",
	},
	{
		icon: <Mail {...ICON_PROPS} />,
		title: 'Keep an eye on your inbox',
		description:
			"You'll probably get an email from me soon, with the first improvements I've shipped.",
	},
];

const FAQS = [
	{
		question: 'Do I really not need to do anything?',
		answer: "Nope. I work through your site's improvements one by one, on my own. You can check in whenever you like, but you don't have to.",
	},
	{
		question: "How will I know it's working?",
		answer: "Every change I make shows up in your activity timeline, and I'll email you a summary when some improvements go live.",
	},
	{
		question: 'Can I change how you work?',
		answer: 'Anytime. Head to Preferences to switch between automatic mode and review mode, where I ask before applying anything.',
	},
];

const FeatureRow = ({ icon, title, description }) => (
	<div className="flex items-start gap-4">
		<div
			className="size-10 rounded-xl bg-magenta-100 flex items-center justify-center shrink-0"
			aria-hidden="true"
		>
			{icon}
		</div>
		<div className="flex-1 min-w-0">
			<p className="paragraph-bold text-foreground my-0!">{title}</p>
			<p className="small-regular text-muted-foreground my-0! mt-1!">
				{description}
			</p>
		</div>
	</div>
);

const FaqItem = ({ question, answer }) => {
	const [open, setOpen] = useState(false);
	return (
		<div className="border-b border-neutral-200">
			<button
				type="button"
				onClick={() => setOpen((prev) => !prev)}
				aria-expanded={open}
				className="w-full flex items-center justify-between gap-4 py-3.5 text-left cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-magenta-500 rounded-sm"
			>
				<span className="paragraph-regular text-foreground my-0!">
					{question}
				</span>
				<ChevronDown
					size={18}
					strokeWidth={2}
					className={cn(
						'text-muted-foreground shrink-0 transition-transform',
						open && 'rotate-180'
					)}
				/>
			</button>
			{open && (
				<p className="small-regular text-muted-foreground my-0! pb-3.5 pr-7">
					{answer}
				</p>
			)}
		</div>
	);
};

const WelcomeModal = () => {
	const siteInfo = window.flavioData?.siteInfo;
	const [open, setOpen] = useState(!siteInfo?.welcomeSeen);

	// Dismiss (button, X, ESC, or overlay click). Close immediately so the user
	// is never blocked, then mark it seen server-side. A failed POST only means
	// the modal may show again on the next load, which is harmless.
	const handleDismiss = () => {
		setOpen(false);
		const { endpoints } = getWordPressConfig();
		if (!endpoints?.onboardingWelcomeSeen) return;
		post(endpoints.onboardingWelcomeSeen, {}).catch((err) => {
			logError(err, {
				action: 'mark_welcome_seen',
				component: 'WelcomeModal',
			});
		});
	};

	return (
		<Dialog open={open} onOpenChange={(next) => !next && handleDismiss()}>
			<DialogContent
				className="max-w-xl gap-0 p-0 overflow-hidden inset-0 m-auto h-fit translate-x-0 translate-y-0"
				onOpenAutoFocus={(e) => e.preventDefault()}
			>
				<div className="max-h-[88vh] overflow-y-auto p-8">
					<div className="flex items-center gap-2.5 mb-6">
						<FlavioIcon className="size-6" />
						<span className="small-bold uppercase tracking-wider text-magenta-500">
							You're all set
						</span>
					</div>

					<DialogTitle className="heading-h2 text-foreground">
						I'll take it from here.
					</DialogTitle>
					<DialogDescription className="paragraph-regular text-muted-foreground mt-3! mb-0!">
						I'll keep on improving your site in the background.
						Nothing else for you to do right now.
					</DialogDescription>

					<div className="space-y-5 mt-8">
						{FEATURES.map((feature) => (
							<FeatureRow key={feature.title} {...feature} />
						))}
					</div>

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

					<p className="uppercase tracking-wider text-muted-foreground my-0! mb-1!">
						In case you're wondering
					</p>
					<div>
						{FAQS.map((faq) => (
							<FaqItem key={faq.question} {...faq} />
						))}
					</div>

					<Button
						onClick={handleDismiss}
						className="relative w-full h-12 mt-8 rounded-full paragraph-bold overflow-hidden"
					>
						<span className="relative z-10">Sounds good</span>
						<span
							aria-hidden="true"
							className="pointer-events-none absolute inset-y-0 left-0 w-1/3 bg-gradient-to-r from-transparent via-white/35 to-transparent animate-button-shine motion-reduce:hidden"
						/>
					</Button>
				</div>
			</DialogContent>
		</Dialog>
	);
};

export default WelcomeModal;
