import type { Models } from "@nontara/server/models";
// import type { OnboardFolderOutput } from "@nontara/server/src/models";
import { useMutation } from "@tanstack/react-query";
import { ChevronRightIcon, FolderIcon, HomeIcon } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { apiClient } from "@/lib/api";

// import { useTRPC } from "@/utils/trpc";

interface FolderExplorerProps {
	onPathSelect: (path: string) => void;
	initialPath?: string;
}

export function FolderExplorer({
	onPathSelect,
	initialPath,
}: FolderExplorerProps) {
	const [currentFolderPath, setCurrentFolderPath] = useState<string[]>(() => {
		if (initialPath?.trim()) {
			return initialPath.split("/").filter(Boolean);
		}
		return [];
	});
	const [folderContents, setFolderContents] = useState<
		Models.OnboardFolderOutput[]
	>([]);
	const [errorMessage, setErrorMessage] = useState<string | null>(null);

	// const trpc = useTRPC();
	const folderExplorerMutation = useMutation({
		mutationFn: async (variables: Models.OnboardFolderInput) => {
			const response = await apiClient.post<Models.OnboardFolderOutput[]>(
				"onboard/folder",
				{
					json: variables,
				},
			);
			return await response.json();
		},
	});

	useEffect(() => {
		// Clear any previous errors when path changes
		setErrorMessage(null);

		const timeoutId = setTimeout(() => {
			folderExplorerMutation.mutate(
				{ path: currentFolderPath },
				{
					onSuccess: (data) => {
						setFolderContents(data);
						setErrorMessage(null);
					},
					onError: (error) => {
						// Clear folder contents on error
						setFolderContents([]);

						// Extract error message
						const message = error.message || "Failed to load folders";

						// Set error message for display
						setErrorMessage(message);

						// Show toast with appropriate message based on error type
						if (
							message.includes("Access denied") ||
							message.includes("permission")
						) {
							toast.error("Access Denied", {
								description:
									"You don't have permission to access this directory.",
							});
						} else if (
							message.includes("not found") ||
							message.includes("does not exist")
						) {
							toast.error("Directory Not Found", {
								description: "The directory no longer exists or was moved.",
							});
							// Go back to parent directory if current path doesn't exist
							if (currentFolderPath.length > 0) {
								setCurrentFolderPath(currentFolderPath.slice(0, -1));
							}
						} else if (message.includes("not a directory")) {
							toast.error("Invalid Path", {
								description: "The selected path is not a directory.",
							});
							// Go back to parent directory
							if (currentFolderPath.length > 0) {
								setCurrentFolderPath(currentFolderPath.slice(0, -1));
							}
						} else if (message.includes("too long")) {
							toast.error("Path Too Long", {
								description: "The path exceeds the maximum allowed length.",
							});
						} else if (message.includes("I/O error")) {
							toast.error("Filesystem Error", {
								description:
									"Unable to read from the filesystem. Please try again.",
							});
						} else if (message.includes("symbolic links")) {
							toast.error("Invalid Path", {
								description:
									"Unable to resolve path due to circular symbolic links.",
							});
						} else {
							// Generic error
							toast.error("Failed to Load Folders", {
								description: message,
							});
						}

						console.error("Folder loading error:", error);
					},
				},
			);
		}, 100);
		return () => clearTimeout(timeoutId);
	}, [currentFolderPath, folderExplorerMutation.mutate]);

	const handleFolderClick = useCallback(
		(folderName: string) => {
			const newPath = [...currentFolderPath, folderName];
			setCurrentFolderPath(newPath);
			const pathString = newPath.join("/");
			onPathSelect(pathString);
		},
		[currentFolderPath, onPathSelect],
	);

	const handlePathClick = useCallback(
		(index: number) => {
			const newPath = currentFolderPath.slice(0, index + 1);
			setCurrentFolderPath(newPath);
			const pathString = newPath.join("/");
			onPathSelect(pathString);
		},
		[currentFolderPath, onPathSelect],
	);

	const handleHomeClick = useCallback(() => {
		setCurrentFolderPath([]);
		onPathSelect("");
	}, [onPathSelect]);

	return (
		<div className="space-y-2">
			<Label>Folder Explorer</Label>
			<div className="space-y-3 rounded-md border p-3">
				{/* Breadcrumb navigation */}
				<div className="no-scrollbar flex items-center gap-1 overflow-x-auto text-sm">
					<Button
						type="button"
						variant="ghost"
						size="sm"
						onClick={handleHomeClick}
						className="h-6 shrink-0 px-2"
					>
						<HomeIcon className="size-3" />
					</Button>
					<div className="no-scrollbar flex min-w-0 max-w-3.5 items-center gap-1">
						{currentFolderPath.map((folder, index) => (
							<div
								key={`${folder}-${currentFolderPath.slice(0, index + 1).join("/")}`}
								className="flex shrink-0 items-center gap-1"
							>
								<ChevronRightIcon className="size-3 shrink-0 text-muted-foreground" />
								<Button
									type="button"
									variant="ghost"
									size="sm"
									onClick={() => handlePathClick(index)}
									className="h-6 max-w-32 shrink-0 px-2 text-xs"
									title={folder}
								>
									<span className="block truncate">{folder}</span>
								</Button>
							</div>
						))}
					</div>
				</div>

				{/* Folder list */}
				<div className="no-scrollbar max-h-40 space-y-1 overflow-y-auto">
					{folderExplorerMutation.isPending ? (
						<div className="flex items-center justify-center py-4 text-muted-foreground text-sm">
							Loading folders...
						</div>
					) : errorMessage ? (
						<div className="flex flex-col items-center justify-center gap-2 py-4 text-center">
							<span className="font-medium text-destructive text-sm">
								Unable to load folders
							</span>
							<span className="text-muted-foreground text-xs">
								{errorMessage}
							</span>
						</div>
					) : folderContents.length === 0 ? (
						<div className="flex items-center justify-center py-4 text-muted-foreground text-sm">
							No folders found
						</div>
					) : (
						folderContents.map((folder) => (
							<Button
								key={folder.name}
								type="button"
								variant="ghost"
								size="sm"
								onClick={() => handleFolderClick(folder.name)}
								className="h-8 w-full justify-start gap-2 px-2"
							>
								<FolderIcon className="size-4 shrink-0 text-muted-foreground" />
								<span className="overflow-hidden truncate text-ellipsis whitespace-nowrap text-left">
									{folder.name}
								</span>
							</Button>
						))
					)}
				</div>
			</div>
		</div>
	);
}
