import { useMutation } from "@tanstack/react-query";
import { createFileRoute, useNavigate } from "@tanstack/react-router";
import lodash from "lodash";
import { Loader2Icon } from "lucide-react";
import { useMemo } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { useTRPC } from "@/utils/trpc";

export const Route = createFileRoute("/welcome/complete")({
	component: CompletionStep,
	head: () => ({
		meta: [
			{
				title: "Setup Complete - Nontara",
			},
		],
	}),
});

function CompletionStep() {
	const context = Route.useRouteContext();
	const onboardSession = context.onboardSession;
	const navigate = useNavigate();
	const account = useMemo(() => onboardSession.getAccount(), [onboardSession]);
	const libraries = useMemo(
		() => onboardSession.getLibraries(),
		[onboardSession],
	);
	const language = useMemo(
		() => onboardSession.getLanguage(),
		[onboardSession],
	);
	const trpc = useTRPC();
	const onboardCompletedMutation = useMutation(
		trpc.onboard.completeOnboarding.mutationOptions(),
	);
	const handleCompletionOnboard = async () => {
		try {
			const onboardResult = onboardSession.dump();
			await onboardCompletedMutation.mutateAsync(onboardResult);
			navigate({
				to: "/login",
			});
		} catch (error) {
			if (error instanceof Error) {
				toast.error(error.message);
			}
		}
	};

	const handleBackClick = () => {
		navigate({
			to: "/welcome/language",
		});
	};

	return (
		<div className="mx-auto flex w-full max-w-3xl flex-col gap-8 py-8 text-center">
			<div className="space-y-2">
				<h1 className="font-semibold text-4xl tracking-tight">
					Setup complete
				</h1>
				<p className="text-muted-foreground">
					You&apos;re all set! Review the summary below and jump into your
					dashboard when you&apos;re ready.
				</p>
			</div>

			<div className="grid gap-4 text-left sm:grid-cols-3">
				<Card>
					<CardHeader>
						<CardTitle className="font-semibold text-muted-foreground text-sm uppercase">
							Account
						</CardTitle>
					</CardHeader>
					<CardContent>
						<p className="font-medium text-lg">{account.name ?? "Not set"}</p>
						<p className="text-muted-foreground text-sm">
							Primary administrator
						</p>
						{lodash.isEmpty(account) ? (
							<Button
								onClick={() =>
									navigate({
										to: "/welcome",
									})
								}
								size="sm"
								className="mt-5"
							>
								Setup account
							</Button>
						) : null}
					</CardContent>
				</Card>

				<Card>
					<CardHeader>
						<CardTitle className="font-semibold text-muted-foreground text-sm uppercase">
							Libraries
						</CardTitle>
					</CardHeader>
					<CardContent>
						<p className="font-medium text-lg">
							{libraries.length === 0
								? "None configured"
								: `${libraries.length} ${libraries.length === 1 ? "library" : "libraries"}`}
						</p>
						{libraries.map((library) => (
							<p
								key={library.id}
								className="truncate text-muted-foreground text-sm"
							>
								{library.name}
							</p>
						))}
						{libraries.length === 0 ? (
							<Button
								onClick={() => navigate({ to: "/welcome/setup" })}
								size="sm"
								className="mt-5 align-bottom"
							>
								Configure libraries
							</Button>
						) : null}
					</CardContent>
				</Card>

				<Card>
					<CardHeader>
						<CardTitle className="font-semibold text-muted-foreground text-sm uppercase">
							Languages
						</CardTitle>
					</CardHeader>
					<CardContent>
						<p className="font-medium text-lg">
							Primary: {language.primary?.toUpperCase() ?? "Not set"}
						</p>
						<p className="text-muted-foreground text-sm">
							Fallback: {language.fallback?.toUpperCase() ?? "Not set"}
						</p>
						{lodash.isEmpty(language) ? (
							<Button
								onClick={() => navigate({ to: "/welcome/language" })}
								size="sm"
								className="mt-5 align-bottom"
							>
								Configure language
							</Button>
						) : null}
					</CardContent>
				</Card>
			</div>

			<div className="flex flex-col items-center justify-center gap-3 sm:flex-row sm:gap-4">
				<Button
					type="button"
					variant="outline"
					size="lg"
					onClick={handleBackClick}
				>
					Previous
				</Button>
				<Button
					disabled={onboardCompletedMutation.isPending}
					size="lg"
					onClick={handleCompletionOnboard}
				>
					{onboardCompletedMutation.isPending && (
						<Loader2Icon className="animate-spin" />
					)}
					Complete Setup
				</Button>
			</div>
		</div>
	);
}
