import {
	createFileRoute,
	Outlet,
	redirect,
	useRouterState,
} from "@tanstack/react-router";
import {
	Check,
	FolderCog,
	Languages as LanguagesIcon,
	LoaderCircleIcon,
	PartyPopper,
	UserRoundPlus,
} from "lucide-react";
import { useMemo } from "react";
import SetupHeader from "@/components/setup/header";
import {
	Stepper,
	StepperIndicator,
	StepperItem,
	StepperNav,
	StepperSeparator,
	StepperTitle,
	StepperTrigger,
} from "@/components/ui/stepper";
import { OnboardSessionService } from "@/services/onboard";
import { isOnboardingNeeded } from "@/utils/functions";

export const Route = createFileRoute("/welcome")({
	component: WelcomeLayout,
	context() {
		return {
			onboardSession: new OnboardSessionService(),
		};
	},
	beforeLoad: async () => {
		const needsOnboarding = await isOnboardingNeeded();
		if (!needsOnboarding.needsOnboarding) {
			throw redirect({
				to: "/login",
			});
		}
	},
	head() {
		return {
			meta: [
				{
					title: "Setup Nontara Media Server",
				},
			],
		};
	},
});

const steps = [
	{
		title: "Create your account",
		description:
			"Set up the primary administrator credentials for your server.",
		icon: UserRoundPlus,
		to: "/welcome" as const,
	},
	{
		title: "Add media libraries",
		description:
			"Point Nontara to your movie and series folders so we can keep them in sync.",
		icon: FolderCog,
		to: "/welcome/setup" as const,
	},
	{
		title: "Language preferences",
		description:
			"Choose metadata languages from providers like TMDB or OMDB and add a fallback.",
		icon: LanguagesIcon,
		to: "/welcome/language" as const,
	},
	{
		title: "Wrap things up",
		description:
			"Review your setup summary and mark everything as complete before launch.",
		icon: PartyPopper,
		to: "/welcome/complete" as const,
	},
] as const;

function WelcomeLayout() {
	const pathname = useRouterState({
		select: (state) => state.location.pathname,
	});

	const normalizedPath = useMemo(() => {
		if (pathname.length > 1 && pathname.endsWith("/")) {
			return pathname.slice(0, -1);
		}
		return pathname;
	}, [pathname]);

	const activeIndex = Math.max(
		steps.findIndex((step) => step.to === normalizedPath),
		0,
	);
	const activeStep = activeIndex + 1;

	return (
		<div className="flex h-full flex-col">
			<SetupHeader />
			<div className="flex-1 overflow-auto px-4 py-8">
				<div className="mx-auto flex w-full max-w-5xl flex-col gap-10">
					<Stepper
						value={activeStep}
						indicators={{
							completed: <Check className="size-4" />,
							loading: <LoaderCircleIcon className="size-4 animate-spin" />,
						}}
						className="w-full space-y-8"
					>
						<StepperNav className="w-full items-center gap-2 sm:gap-4 md:gap-6">
							{steps.map((step, index) => {
								const stepNumber = index + 1;

								return (
									<StepperItem
										key={step.to}
										step={stepNumber}
										className="relative"
									>
										<StepperTrigger
											aria-disabled="true"
											onClick={(event) => event.preventDefault()}
											onKeyDown={(event) => event.preventDefault()}
											className="flex cursor-default items-center justify-start gap-1.5"
										>
											<StepperIndicator className="size-8 border border-border bg-background font-semibold text-muted-foreground text-xs transition-colors group-data-[state=active]/step:border-blue-500 group-data-[state=completed]/step:border-green-500 group-data-[state=inactive]/step:border-border group-data-[state=active]/step:bg-blue-500/15 group-data-[state=completed]/step:bg-green-500/15 group-data-[state=active]/step:text-blue-500 group-data-[state=completed]/step:text-green-600">
												{stepNumber}
											</StepperIndicator>
											<StepperTitle className="font-medium text-muted-foreground text-sm group-data-[state=active]/step:text-blue-500 group-data-[state=completed]/step:text-green-500">
												{step.title}
											</StepperTitle>
										</StepperTrigger>

										{index < steps.length - 1 ? (
											<StepperSeparator className="bg-border group-data-[state=active]/step:bg-blue-500 group-data-[state=completed]/step:bg-green-500 md:mx-2.5" />
										) : null}
									</StepperItem>
								);
							})}
						</StepperNav>
					</Stepper>

					<div className="px-0 sm:px-4">
						<Outlet />
					</div>
				</div>
			</div>
		</div>
	);
}
