import type { Models } from "@nontara/server/models";
// import { createFileRoute, useNavigate } from "@tanstack/react-router";
import {
	FilmIcon,
	FolderIcon,
	MonitorPlayIcon,
	MoreVerticalIcon,
	PlusIcon,
} from "lucide-react";
import { useCallback, useMemo, useState } from "react";
import { useNavigate } from "react-router";
import { toast } from "sonner";
import { LibraryDialog } from "@/components/setup/LibraryDialog";
import { Button } from "@/components/ui/button";
import {
	Card,
	CardAction,
	CardContent,
	CardDescription,
	CardHeader,
	CardTitle,
} from "@/components/ui/card";
import { Dialog, DialogTrigger } from "@/components/ui/dialog";
import {
	DropdownMenu,
	DropdownMenuContent,
	DropdownMenuItem,
	DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useOnboard } from "@/hooks/useOnboard";

const PAGE_TITLE = "Add media libraries";
const PAGE_DESCRIPTION =
	"Point Nontara to the folders you want us to manage so we can keep them organised and up to date.";

const LIBRARY_TYPE_LABEL: Record<Models.LibraryData["type"], string> = {
	MOVIE: "Movies",
	SERIES: "Series",
};

function createId() {
	if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
		return crypto.randomUUID();
	}

	return `${Date.now()}-${Math.random().toString(16).slice(2)}`;
}

export function OnboardSetupPage() {
	const onboardSession = useOnboard();
	const navigate = useNavigate();

	const [libraries, setLibraries] = useState<Models.LibraryData[]>(() =>
		onboardSession.getLibraries(),
	);
	const [dialogOpen, setDialogOpen] = useState(false);
	const [editingLibrary, setEditingLibrary] =
		useState<Models.LibraryData | null>(null);

	const defaultLibraryType = useMemo(() => {
		const existingTypes = libraries.map((lib) => lib.type);
		if (!existingTypes.includes("MOVIE")) return "MOVIE";
		if (!existingTypes.includes("SERIES")) return "SERIES";
		return "MOVIE";
	}, [libraries]);

	const librariesCountLabel = useMemo(() => {
		const count = libraries.length;
		if (count === 0) return "No libraries added yet";
		if (count === 1) return "1 library added";
		return `${count} libraries added`;
	}, [libraries.length]);

	const handleDialogOpenChange = useCallback((open: boolean) => {
		setDialogOpen(open);
		if (!open) {
			setEditingLibrary(null);
		}
	}, []);

	const handleEditLibrary = useCallback((library: Models.LibraryData) => {
		setEditingLibrary(library);
		setDialogOpen(true);
	}, []);

	const handleDeleteLibrary = useCallback(
		(library: Models.LibraryData) => {
			const nextLibraries = libraries.filter((item) => item.id !== library.id);
			setLibraries(nextLibraries);
			onboardSession.updateLibraries(nextLibraries);
			toast.success(`${library.name} library deleted`);

			if (editingLibrary?.id === library.id) {
				setDialogOpen(false);
				setEditingLibrary(null);
			}
		},
		[libraries, onboardSession, editingLibrary?.id],
	);

	const handleLibrarySubmit = useCallback(
		(libraryData: Omit<Models.LibraryData, "id"> & { id?: string }) => {
			let nextLibraries: Models.LibraryData[];

			if (libraryData.id) {
				// Editing existing library
				nextLibraries = libraries.map((item) =>
					item.id === libraryData.id
						? { ...item, ...libraryData, id: libraryData.id }
						: item,
				);
				toast.success(`${libraryData.name} library updated`);
			} else {
				// Adding new library
				const library: Models.LibraryData = {
					id: createId(),
					name: libraryData.name,
					path: libraryData.path,
					type: libraryData.type,
				};

				nextLibraries = [...libraries, library];
				toast.success(`${library.name} library added`);
			}

			setLibraries(nextLibraries);
			onboardSession.updateLibraries(nextLibraries);
		},
		[libraries, onboardSession],
	);

	const handleCompleteClick = () => {
		if (libraries.length === 0) {
			toast.error("Add at least one library before continuing.");
			return;
		}

		navigate("/onboard/language");
	};

	const handleBackClick = () => {
		navigate("/onboard");
	};

	return (
		<div className="flex flex-col gap-8">
			<section className="flex flex-col items-center gap-6">
				<div className="flex flex-col items-center gap-2 text-center">
					<h1 className="font-semibold text-2xl tracking-tight">
						{PAGE_TITLE}
					</h1>
					<p className="max-w-2xl text-muted-foreground text-sm">
						{PAGE_DESCRIPTION}
					</p>
				</div>
				<div className="flex flex-wrap items-center justify-center gap-3 text-muted-foreground text-sm">
					<span>{librariesCountLabel}</span>
				</div>
				<Dialog open={dialogOpen} onOpenChange={handleDialogOpenChange}>
					<DialogTrigger asChild>
						<Button
							className="gap-2"
							size="lg"
							onClick={() => {
								setEditingLibrary(null);
							}}
						>
							<PlusIcon className="size-4" />
							New Library
						</Button>
					</DialogTrigger>
				</Dialog>
				<LibraryDialog
					mode={editingLibrary ? "EDITING" : "NEW"}
					open={dialogOpen}
					onOpenChange={handleDialogOpenChange}
					onSubmit={handleLibrarySubmit}
					defaultLibraryType={defaultLibraryType}
					initialLibrary={editingLibrary || undefined}
				/>
			</section>

			<section className="grid gap-4 sm:grid-cols-2">
				{libraries.length === 0 ? (
					<div className="col-span-full rounded-lg border border-dashed p-8 text-center text-muted-foreground">
						Your libraries will appear here once you create them.
					</div>
				) : (
					libraries.map((library) => {
						const Icon = library.type === "MOVIE" ? FilmIcon : MonitorPlayIcon;
						const libraryTypeLabel =
							LIBRARY_TYPE_LABEL[library.type] ?? library.type;
						return (
							<Card key={library.id}>
								<CardHeader className="gap-4">
									<div className="flex items-start gap-4">
										<div className="flex size-12 items-center justify-center rounded-full bg-muted shadow-inner">
											<Icon className="size-6" />
										</div>
										<div className="space-y-1 text-left">
											<CardTitle>{library.name}</CardTitle>
											<CardDescription>
												{libraryTypeLabel} • Folder path
											</CardDescription>
										</div>
									</div>
									<CardAction>
										<DropdownMenu>
											<DropdownMenuTrigger asChild>
												<Button type="button" variant="ghost" size="icon">
													<MoreVerticalIcon className="size-4" />
													<span className="sr-only">Open actions</span>
												</Button>
											</DropdownMenuTrigger>
											<DropdownMenuContent align="end">
												<DropdownMenuItem
													onSelect={() => handleEditLibrary(library)}
												>
													Edit
												</DropdownMenuItem>
												<DropdownMenuItem
													onSelect={() => handleDeleteLibrary(library)}
												>
													Delete
												</DropdownMenuItem>
											</DropdownMenuContent>
										</DropdownMenu>
									</CardAction>
								</CardHeader>
								<CardContent className="space-y-2">
									<p className="font-medium text-muted-foreground text-sm">
										Folder
									</p>
									<div className="flex items-center gap-2 text-sm">
										<FolderIcon className="size-4 text-muted-foreground" />
										<span className="truncate" title={library.path}>
											{library.path}
										</span>
									</div>
								</CardContent>
							</Card>
						);
					})
				)}
			</section>

			<div className="flex flex-col justify-end gap-3 sm:flex-row sm:gap-4">
				<Button
					type="button"
					variant="outline"
					size="lg"
					onClick={handleBackClick}
				>
					Previous
				</Button>
				<Button type="button" size="lg" onClick={handleCompleteClick}>
					Save &amp; Continue
				</Button>
			</div>
		</div>
	);
}
