import { languages as languageList } from "@nontara/language-codes/language-list";
import type { Models } from "@nontara/server/models";
import { useCallback, useState } from "react";
import { useNavigate } from "react-router";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
	Card,
	CardContent,
	CardDescription,
	CardFooter,
	CardHeader,
	CardTitle,
} from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import {
	Select,
	SelectContent,
	SelectItem,
	SelectTrigger,
	SelectValue,
} from "@/components/ui/select";
import { useOnboard } from "@/hooks/useOnboard";

type LanguageOption = {
	value: string;
	label: string;
	local?: string;
};

const LANGUAGE_OPTIONS: readonly LanguageOption[] = (() => {
	const dedup = new Map<string, LanguageOption>();

	for (const language of languageList) {
		const code = language["1"]?.trim();
		if (!code || dedup.has(code)) continue;

		dedup.set(code, {
			value: code,
			label: language.name,
			local: language.local,
		});
	}

	return Array.from(dedup.values()).sort((a, b) =>
		a.label.localeCompare(b.label),
	);
})();

export function OnboardLanguagePage() {
	const onboard = useOnboard();
	const language = onboard.getLanguage();
	const navigate = useNavigate();
	const [selection, setSelection] = useState<Models.MetadataLanguage>({
		primary: language?.primary ?? "en",
		fallback: language?.fallback ?? "en",
	});

	const handlePrimaryChange = useCallback((value: string) => {
		setSelection((prev: Models.MetadataLanguage) => ({
			...prev,
			primary: value,
		}));
	}, []);

	const handleFallbackChange = useCallback((value: string) => {
		setSelection((prev: Models.MetadataLanguage) => ({
			...prev,
			fallback: value,
		}));
	}, []);

	const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
		event.preventDefault();
		event.stopPropagation();
		onboard.updateLanguage(selection);
		toast.success("Language preferences saved");
		navigate("/onboard/complete");
	};

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

	const fallbackDisabled = selection.primary === selection.fallback;

	return (
		<form
			onSubmit={handleSubmit}
			className="mx-auto flex w-full max-w-3xl flex-col gap-8"
		>
			<Card>
				<CardHeader>
					<CardTitle className="font-semibold text-2xl">
						Choose metadata languages
					</CardTitle>
					<CardDescription>
						Select the language Nontara should prioritise when fetching metadata
						from providers like TMDB and OMDB. You can also pick a fallback
						language in case information isn't available.
					</CardDescription>
				</CardHeader>
				<CardContent className="grid gap-6 sm:grid-cols-2">
					<div className="space-y-2">
						<Label htmlFor="primary-language">Preferred language</Label>
						<Select
							value={selection.primary}
							onValueChange={handlePrimaryChange}
						>
							<SelectTrigger id="primary-language" className="w-full">
								<SelectValue placeholder="Pick a language" />
							</SelectTrigger>
							<SelectContent className="max-h-64">
								{LANGUAGE_OPTIONS.map((option) => (
									<SelectItem key={option.value} value={option.value}>
										<span className="flex flex-col">
											<span>{option.label}</span>
											{option.local && option.local !== option.label ? (
												<span className="text-muted-foreground text-xs">
													{option.local}
												</span>
											) : null}
										</span>
									</SelectItem>
								))}
							</SelectContent>
						</Select>
					</div>

					<div className="space-y-2">
						<Label htmlFor="fallback-language">Fallback language</Label>
						<Select
							value={selection.fallback}
							onValueChange={handleFallbackChange}
						>
							<SelectTrigger id="fallback-language" className="w-full">
								<SelectValue placeholder="Choose fallback" />
							</SelectTrigger>
							<SelectContent className="max-h-64">
								{LANGUAGE_OPTIONS.map((option) => (
									<SelectItem key={option.value} value={option.value}>
										<span className="flex flex-col">
											<span>{option.label}</span>
											{option.local && option.local !== option.label ? (
												<span className="text-muted-foreground text-xs">
													{option.local}
												</span>
											) : null}
										</span>
									</SelectItem>
								))}
							</SelectContent>
						</Select>
						{fallbackDisabled ? (
							<p className="text-muted-foreground text-sm">
								Fallback language matches the primary language by default.
							</p>
						) : null}
					</div>
				</CardContent>
				<CardFooter className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
					<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:gap-4">
						<Button type="button" variant="outline" onClick={handleBackClick}>
							Previous
						</Button>
						<div className="text-muted-foreground text-sm">
							Primary: {selection.primary.toUpperCase()} • Fallback:{" "}
							{selection.fallback.toUpperCase()}
						</div>
					</div>
					<Button type="submit">Save Languages</Button>
				</CardFooter>
			</Card>
		</form>
	);
}
