"use client";

import { useAvatarOutfits } from "@/hooks/roblox/useAvatarOutfits";
import { Button } from "@/components/ui/button";
import LazyLoadedImage from "../util/LazyLoadedImage";
import { StupidHoverThing } from "../util/MiscStuff";
import { loadThumbnails } from "@/lib/thumbnailLoader";
import { useCurrentAccount } from "@/hooks/roblox/useCurrentAccount";
import { useEffect, useMemo, useState } from "react";
import { Search, X } from "lucide-react";
import { Input } from "@/components/ui/input";

type OutfitSelectorProps = {
	setVisible: (visible: boolean) => void;
	updateOutfit: (
		outfit: { id: number },
		acc: { id: number }
	) => Promise<void>;
};

export function OutfitSelector({
	setVisible,
	updateOutfit
}: OutfitSelectorProps) {
	const outfits = useAvatarOutfits();
	const acc = useCurrentAccount();
	const [query, setQuery] = useState("");

	useEffect(() => {
		if (!outfits || outfits.length === 0) return;
		loadThumbnails(
			outfits.map((a) => ({
				type: "Outfit",
				targetId: a.id,
				format: "webp",
				size: "420x420"
			}))
		).catch(() => {});
	}, [outfits]);

	useEffect(() => {
		const handleKeyDown = (event: KeyboardEvent) => {
			if (event.key === "Escape") setVisible(false);
		};
		window.addEventListener("keydown", handleKeyDown);
		return () => window.removeEventListener("keydown", handleKeyDown);
	}, [setVisible]);

	const isLoading = outfits === null;
	const hasOutfits = Array.isArray(outfits) && outfits.length > 0;

	const filteredOutfits = useMemo(() => {
		if (!hasOutfits) return [];
		if (!query.trim()) return outfits;
		const lowered = query.trim().toLowerCase();
		return outfits.filter((outfit) =>
			outfit.name.toLowerCase().includes(lowered)
		);
	}, [hasOutfits, outfits, query]);

	return (
		<div
			className="fixed inset-0 z-40 flex items-center justify-center bg-mantle/70 backdrop-blur-sm"
			onClick={() => setVisible(false)}
		>
			<div
				className="panel-blur relative w-full max-w-3xl sm:max-w-4xl mx-4"
				onClick={(event) => event.stopPropagation()}
			>
				<div className="flex flex-col gap-3 border-b border-surface0/60 px-6 py-4 sm:flex-row sm:items-center sm:justify-between">
					<div>
						<p className="text-lg font-semibold text-text">
							Outfits
						</p>
						<p className="text-xs text-subtext1">
							Pick a look to update your avatar instantly.
						</p>
					</div>
					<div className="flex items-center gap-2">
						<div className="relative w-full sm:w-64">
							<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-subtext1" />
							<Input
								value={query}
								onChange={(event) =>
									setQuery(event.target.value)
								}
								placeholder="Search outfits"
								className="pl-9"
							/>
						</div>
						<Button
							variant="ghost"
							size="icon"
							onClick={() => setVisible(false)}
							aria-label="Close outfit chooser"
						>
							<X className="h-4 w-4" />
						</Button>
					</div>
				</div>

				<div className="p-6">
					{!acc ? (
						<div className="rounded-xl border border-surface0/60 bg-base/50 p-6 text-sm text-subtext1">
							Sign in to load your outfits.
						</div>
					) : isLoading ? (
						<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
							{Array.from({ length: 8 }).map((_, index) => (
								<div
									key={`outfit-skeleton-${index}`}
									className="rounded-xl border border-surface0/60 bg-base/40 p-3"
								>
									<div className="h-24 w-24 sm:h-28 sm:w-28 rounded-lg bg-surface0/70 animate-pulse" />
									<div className="mt-3 h-3 w-20 rounded bg-surface0/70 animate-pulse" />
								</div>
							))}
						</div>
					) : hasOutfits ? (
						<div className="space-y-4">
							<p className="text-xs text-subtext1">
								{filteredOutfits.length} outfit
								{filteredOutfits.length === 1 ? "" : "s"}
							</p>
							<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4 max-h-[60vh] overflow-y-auto pr-2">
								{filteredOutfits.map(
									(outfit: { id: number; name: string }) => (
										<StupidHoverThing
											key={outfit.id}
											delayDuration={0}
											text={outfit.name}
										>
											<button
												className="group rounded-xl border border-surface0/50 bg-base/40 p-3 text-left transition hover:-translate-y-0.5 hover:border-surface1/80 hover:bg-surface0/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue/60"
												onClick={async () => {
													await updateOutfit(
														outfit,
														acc
													);
													setVisible(false);
												}}
												aria-label={`Wear ${outfit.name}`}
											>
												<LazyLoadedImage
													imgId={`Outfit_${outfit.id}`}
													alt={outfit.name}
													className="h-24 w-24 sm:h-28 sm:w-28 rounded-lg object-cover shadow-sm"
													size="420x420"
													lazyFetch={false}
												/>
												<p className="mt-3 text-xs font-medium text-text line-clamp-2">
													{outfit.name}
												</p>
											</button>
										</StupidHoverThing>
									)
								)}
							</div>
							{filteredOutfits.length === 0 ? (
								<div className="rounded-xl border border-surface0/60 bg-base/50 p-4 text-sm text-subtext1">
									No outfits match that search yet.
								</div>
							) : null}
						</div>
					) : (
						<div className="rounded-xl border border-surface0/60 bg-base/50 p-6 text-sm text-subtext1">
							No outfits found yet. Make one in the Roblox avatar
							editor, then come back here.
						</div>
					)}
				</div>
			</div>
		</div>
	);
}
