"use client";

import { useAtomValue } from "jotai";
import { AlertCircle, Loader2 } from "lucide-react";
import { motion } from "motion/react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { useEffect, useState } from "react";
import { searchSpacesAtom } from "@/atoms/search-spaces/search-space-query.atoms";
import { CreateSearchSpaceDialog } from "@/components/layout";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import {
	Card,
	CardContent,
	CardDescription,
	CardFooter,
	CardHeader,
	CardTitle,
} from "@/components/ui/card";

function LoadingScreen() {
	const t = useTranslations("dashboard");
	return (
		<div className="flex min-h-screen flex-col items-center justify-center gap-4">
			<motion.div
				initial={{ opacity: 0, scale: 0.8 }}
				animate={{ opacity: 1, scale: 1 }}
				transition={{ duration: 0.5 }}
			>
				<Card className="w-full max-w-[350px] bg-background/60 backdrop-blur-sm">
					<CardHeader className="pb-2">
						<CardTitle className="text-xl font-medium">{t("loading")}</CardTitle>
						<CardDescription>{t("fetching_spaces")}</CardDescription>
					</CardHeader>
					<CardContent className="flex justify-center py-6">
						<motion.div
							animate={{ rotate: 360 }}
							transition={{ duration: 1.5, repeat: Number.POSITIVE_INFINITY, ease: "linear" }}
						>
							<Loader2 className="h-12 w-12 text-primary" />
						</motion.div>
					</CardContent>
					<CardFooter className="border-t pt-4 text-sm text-muted-foreground">
						{t("may_take_moment")}
					</CardFooter>
				</Card>
			</motion.div>
		</div>
	);
}

function ErrorScreen({ message }: { message: string }) {
	const t = useTranslations("dashboard");
	const router = useRouter();

	return (
		<div className="flex min-h-screen flex-col items-center justify-center gap-4">
			<motion.div
				initial={{ opacity: 0, y: 20 }}
				animate={{ opacity: 1, y: 0 }}
				transition={{ duration: 0.5 }}
			>
				<Card className="w-full max-w-[400px] border-destructive/20 bg-background/60 backdrop-blur-sm">
					<CardHeader className="pb-2">
						<div className="flex items-center gap-2">
							<AlertCircle className="h-5 w-5 text-destructive" />
							<CardTitle className="text-xl font-medium">{t("error")}</CardTitle>
						</div>
						<CardDescription>{t("something_wrong")}</CardDescription>
					</CardHeader>
					<CardContent>
						<Alert variant="destructive" className="border-destructive/30 bg-destructive/10">
							<AlertCircle className="h-4 w-4" />
							<AlertTitle>{t("error_details")}</AlertTitle>
							<AlertDescription className="mt-2">{message}</AlertDescription>
						</Alert>
					</CardContent>
					<CardFooter className="flex justify-end gap-2 border-t pt-4">
						<Button variant="outline" onClick={() => router.refresh()}>
							{t("try_again")}
						</Button>
						<Button onClick={() => router.push("/")}>{t("go_home")}</Button>
					</CardFooter>
				</Card>
			</motion.div>
		</div>
	);
}

export default function DashboardPage() {
	const router = useRouter();
	const [showCreateDialog, setShowCreateDialog] = useState(false);

	const {
		data: searchSpaces = [],
		isLoading,
		error,
	} = useAtomValue(searchSpacesAtom);

	useEffect(() => {
		if (isLoading) return;

		if (searchSpaces.length === 0) {
			setShowCreateDialog(true);
		} else {
			router.replace(`/dashboard/${searchSpaces[0].id}/new-chat`);
		}
	}, [isLoading, searchSpaces, router]);

	const handleDialogChange = (open: boolean) => {
		setShowCreateDialog(open);
	};

	if (isLoading) return <LoadingScreen />;
	if (error) return <ErrorScreen message={error?.message || "Failed to load search spaces"} />;

	if (searchSpaces.length > 0) {
		return <LoadingScreen />;
	}

	return (
		<div className="flex min-h-screen flex-col items-center justify-center">
			<CreateSearchSpaceDialog open={showCreateDialog} onOpenChange={handleDialogChange} />
		</div>
	);
}
