import { useCallback, useState } from "react";
import { getTagsForHobbies } from "@/shared/hobbyConfig";
import {
	useCompleteOnboarding,
	usePopularItems,
} from "../../hooks/useOnboarding";
import { useUpdateSetting } from "../../hooks/useSettings";
import { OnboardingDone } from "./OnboardingDone";
import { OnboardingHobbyPicker } from "./OnboardingHobbyPicker";
import { OnboardingItemBrowser } from "./OnboardingItemBrowser";
import { OnboardingReview } from "./OnboardingReview";
import { OnboardingWelcome } from "./OnboardingWelcome";
import { StepIndicator } from "./StepIndicator";

type Step = "welcome" | "hobby" | "browse" | "review" | "done";

const STEP_PROGRESS: Record<Step, number> = {
	welcome: 20,
	hobby: 40,
	browse: 60,
	review: 80,
	done: 100,
};

interface OnboardingFlowProps {
	onComplete: () => void;
}

export function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
	const [step, setStep] = useState<Step>("welcome");
	const [transitioning, setTransitioning] = useState(false);
	const [selectedHobbies, setSelectedHobbies] = useState<string[]>([]);
	const [selectedItemIds, setSelectedItemIds] = useState<Set<number>>(
		new Set(),
	);
	const [itemsCreated, setItemsCreated] = useState(0);

	const completeOnboarding = useCompleteOnboarding();
	const updateSetting = useUpdateSetting();

	// Fetch items for review step data
	const tags = getTagsForHobbies(selectedHobbies);
	const { data: popularItems } = usePopularItems(tags);

	const goToStep = useCallback((nextStep: Step) => {
		setTransitioning(true);
		setTimeout(() => {
			setStep(nextStep);
			setTransitioning(false);
		}, 200);
	}, []);

	const handleToggleHobby = useCallback((hobbyId: string) => {
		setSelectedHobbies((prev) =>
			prev.includes(hobbyId)
				? prev.filter((h) => h !== hobbyId)
				: [...prev, hobbyId],
		);
		// Reset item selections when hobbies change
		setSelectedItemIds(new Set());
	}, []);

	const handleToggleItem = useCallback((itemId: number) => {
		setSelectedItemIds((prev) => {
			const next = new Set(prev);
			if (next.has(itemId)) next.delete(itemId);
			else next.add(itemId);
			return next;
		});
	}, []);

	const handleRemoveItem = useCallback((itemId: number) => {
		setSelectedItemIds((prev) => {
			const next = new Set(prev);
			next.delete(itemId);
			return next;
		});
	}, []);

	const handleConfirm = useCallback(() => {
		const ids = [...selectedItemIds];
		completeOnboarding.mutate(ids, {
			onSuccess: (result) => {
				setItemsCreated(result.itemsCreated);
				goToStep("done");
			},
		});
	}, [selectedItemIds, completeOnboarding, goToStep]);

	const handleSkipBrowse = useCallback(() => {
		updateSetting.mutate(
			{ key: "onboardingComplete", value: "true" },
			{ onSuccess: onComplete },
		);
	}, [updateSetting, onComplete]);

	// Build review items from selected IDs
	const reviewItems = (popularItems || [])
		.filter((item) => selectedItemIds.has(item.id))
		.map((item) => ({
			id: item.id,
			brand: item.brand,
			model: item.model,
			imageUrl: item.imageUrl,
			category: item.category,
		}));

	return (
		<div className="fixed inset-0 z-50 bg-white overflow-y-auto">
			<StepIndicator progress={STEP_PROGRESS[step]} />

			<div
				className={`transition-all duration-300 ${
					transitioning
						? "opacity-0 -translate-y-4"
						: "opacity-100 translate-y-0"
				}`}
			>
				{step === "welcome" && (
					<OnboardingWelcome onContinue={() => goToStep("hobby")} />
				)}

				{step === "hobby" && (
					<OnboardingHobbyPicker
						selectedHobbies={selectedHobbies}
						onToggleHobby={handleToggleHobby}
						onContinue={() => goToStep("browse")}
					/>
				)}

				{step === "browse" && (
					<OnboardingItemBrowser
						selectedHobbies={selectedHobbies}
						selectedItemIds={selectedItemIds}
						onToggleItem={handleToggleItem}
						onContinue={() => goToStep("review")}
						onSkip={handleSkipBrowse}
					/>
				)}

				{step === "review" && (
					<OnboardingReview
						items={reviewItems}
						onRemoveItem={handleRemoveItem}
						onConfirm={handleConfirm}
						onSkip={handleSkipBrowse}
						isSubmitting={completeOnboarding.isPending}
					/>
				)}

				{step === "done" && (
					<OnboardingDone itemsCreated={itemsCreated} onFinish={onComplete} />
				)}
			</div>
		</div>
	);
}
