"use client";

import {
	Activity,
	Coffee,
	Egg,
	HardDrive,
	History,
	LogOut,
	RefreshCw,
	Search,
	Users,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { api, authApi, overseerApi, userApi } from "@/lib/api";
import { useStore } from "@/lib/store";
import { formatNumber } from "@/lib/utils";
import { ActivityFeed } from "./components/ActivityFeed";
import { BuyCreditsModal } from "./components/BuyCreditsModal";
import { Leaderboard } from "./components/Leaderboard";
import { RequestHistory } from "./components/RequestHistory";
import { SearchRequestModal } from "./components/SearchRequestModal";
import { WatchHistory } from "./components/WatchHistory";

interface WalletData {
	balance: number;
	totalEarned: number;
	totalSpent: number;
}

export default function DashboardPage() {
	const router = useRouter();
	const { isAuthenticated, logout } = useStore();
	const [wallet, setWallet] = useState<WalletData | null>(null);
	const [requestCosts, setRequestCosts] = useState({
		movie: 500,
		tv: 1000,
		movieAdjusted: 500,
		tvAdjusted: 1000,
		scarcityMultiplier: 1,
	});
	const [totalRequests, setTotalRequests] = useState(0);
	const [diskSpace, setDiskSpace] = useState<any>(null);
	const [isLoading, setIsLoading] = useState(true);
	const [isSearchModalOpen, setIsSearchModalOpen] = useState(false);
	const [isBuyModalOpen, setIsBuyModalOpen] = useState(false);
	const [refreshCount, setRefreshCount] = useState(0);

	useEffect(() => {
		if (!isAuthenticated) {
			router.push("/login");
			return;
		}
		loadWalletAndPending();
		loadCosts();
		syncPending();
	}, [isAuthenticated, router]);

	const loadWalletAndPending = async () => {
		try {
			const [walletRes, reqRes, diskRes] = await Promise.all([
				api.get("/wallet"),
				userApi.getRequests(1, 100),
				api.get("/overseer/diskspace"),
			]);
			setWallet(walletRes.data);
			setTotalRequests(reqRes.data.requests?.length || 0);
			setDiskSpace(diskRes.data);
		} catch {
			toast.error("Chickens escaped! Failed to load.");
		} finally {
			setIsLoading(false);
		}
	};

	const loadCosts = async () => {
		try {
			const costsRes = await overseerApi.getCosts();
			setRequestCosts(costsRes.data);
		} catch {}
	};

	const syncPending = async () => {
		try {
			await api.post("/overseer/sync-pending");
			await loadWalletAndPending();
		} catch {}
	};

	const handleLogout = async () => {
		try {
			await authApi.logout();
		} catch {}
		logout();
		router.push("/login");
	};

	const handleRefresh = () => {
		loadWalletAndPending();
		loadCosts();
		syncPending();
		setRefreshCount((c) => c + 1);
	};

	if (isLoading)
		return (
			<div className="flex min-h-screen flex-col items-center justify-center bg-background text-primary gap-4 font-display">
				<Egg className="h-12 w-12 animate-bounce" />
				<span>Sitting on eggs...</span>
			</div>
		);

	return (
		<div className="min-h-screen bg-background p-4 sm:p-6 lg:p-8 font-sans">
			<div className="mx-auto max-w-6xl space-y-6">
				{/* Header */}
				<div className="flex flex-col gap-4 rounded-3xl border-4 border-foreground bg-card p-6 shadow-[8px_8px_0px_0px_rgba(0,0,0,1)]">
					<div className="flex items-center justify-between">
						<div>
							<h1 className="font-display text-4xl uppercase italic tracking-tighter text-primary">
								THE COOP
							</h1>
							<p className="text-sm font-bold text-muted-foreground">
								Welcome back, farmer.
							</p>
						</div>
						<div className="flex gap-2">
							<Button
								variant="ghost"
								size="icon"
								onClick={handleRefresh}
								className="rounded-full border-2 border-foreground"
							>
								<RefreshCw className="h-5 w-5" />
							</Button>
							<Button
								variant="ghost"
								size="icon"
								onClick={handleLogout}
								className="rounded-full font-bold text-muted-foreground hover:bg-destructive/10 hover:text-destructive"
							>
								<LogOut className="h-5 w-5" />
							</Button>
						</div>
					</div>

					<div className="flex flex-wrap items-center justify-center gap-2">
						<Button
							onClick={() => setIsSearchModalOpen(true)}
							className="rounded-full bg-primary px-6 font-bold text-lg hover:scale-105 transition-transform"
						>
							<Search className="mr-2 h-5 w-5" />
							PECK FOR FEED
						</Button>
						<Button
							variant="outline"
							onClick={() => setIsBuyModalOpen(true)}
							className="rounded-full border-2 border-[#FF5E5B] bg-background font-bold text-[#FF5E5B] hover:bg-[#FF5E5B]/10"
						>
							<Coffee className="mr-2 h-5 w-5" />
							BUY FEED
						</Button>
					</div>
				</div>

				{/* Nest Stats */}
				<div className="grid gap-4 sm:grid-cols-3">
					<div className="group relative rounded-3xl border-4 border-foreground bg-card p-6 shadow-[6px_6px_0px_0px_rgba(0,0,0,1)] hover:translate-x-[-2px] hover:translate-y-[-2px] hover:shadow-[8px_8px_0px_0px_rgba(0,0,0,1)] transition-all">
						<div className="text-xs font-black uppercase tracking-widest text-muted-foreground">
							Your Nest Egg
						</div>
						<div className="mt-2 text-4xl font-black text-primary">
							{formatNumber(wallet?.balance || 0)}{" "}
							<span className="text-sm">$COOP</span>
						</div>
						<div className="absolute top-4 right-4 text-4xl opacity-20 group-hover:opacity-40 transition-opacity">
							🥚
						</div>
					</div>
					<div className="group relative rounded-3xl border-4 border-foreground bg-secondary p-6 shadow-[6px_6px_0px_0px_rgba(0,0,0,1)] hover:translate-x-[-2px] hover:translate-y-[-2px] hover:shadow-[8px_8px_0px_0px_rgba(0,0,0,1)] transition-all">
						<div className="text-xs font-black uppercase tracking-widest text-secondary-foreground/60">
							Eggs Ordered
						</div>
						<div className="mt-2 text-4xl font-black text-secondary-foreground">
							{totalRequests}{" "}
							<span className="text-sm">Requests</span>
						</div>
						<div className="absolute top-4 right-4 text-4xl opacity-20 group-hover:opacity-40 transition-opacity">
							📋
						</div>
					</div>
					<div className="group relative rounded-3xl border-4 border-foreground bg-accent p-6 shadow-[6px_6px_0px_0px_rgba(0,0,0,1)] hover:translate-x-[-2px] hover:translate-y-[-2px] hover:shadow-[8px_8px_0px_0px_rgba(0,0,0,1)] transition-all">
						<div className="text-xs font-black uppercase tracking-widest text-accent-foreground/60">
							Market Price
						</div>
						<div className="mt-2 text-2xl font-black text-accent-foreground">
							{requestCosts.movieAdjusted || requestCosts.movie}{" "}
							<span className="text-sm">/</span>{" "}
							{requestCosts.tvAdjusted || requestCosts.tv}
						</div>
						<div className="text-xs font-bold text-accent-foreground/40 line-through">
							{requestCosts.movie} / {requestCosts.tv}
						</div>
						<div className="text-[10px] font-bold text-accent-foreground/50 uppercase">
							Movie / TV Series
							{requestCosts.scarcityMultiplier > 1 && (
								<span className="text-destructive ml-1">
									(x{requestCosts.scarcityMultiplier})
								</span>
							)}
						</div>
						<div className="absolute top-4 right-4 text-4xl opacity-20 group-hover:opacity-40 transition-opacity">
							🌽
						</div>
					</div>
				</div>

				{/* Disk Space */}
				{diskSpace && diskSpace.totalBytes > 0 && (
					<div className="rounded-3xl border-4 border-foreground bg-card p-6 shadow-[6px_6px_0px_0px_rgba(0,0,0,1)]">
						<div className="flex items-center justify-between mb-3">
							<div className="flex items-center gap-2">
								<HardDrive className="h-5 w-5 text-primary" />
								<h3 className="font-black uppercase tracking-widest text-sm text-muted-foreground">
									The Silo
								</h3>
							</div>
							<div className="text-sm font-black">
								<span className="text-primary">{diskSpace.used}</span>
								<span className="text-muted-foreground"> / {diskSpace.total}</span>
								<span className="text-destructive ml-2">({diskSpace.usedPercent}%)</span>
							</div>
						</div>
						<div className="h-6 w-full rounded-full border-2 border-foreground bg-muted overflow-hidden shadow-inner">
							<div
								className="h-full rounded-full bg-primary transition-all duration-500"
								style={{
									width: `${diskSpace.usedPercent}%`,
									backgroundColor:
											diskSpace.usedPercent > 90
												? "hsl(var(--destructive))"
												: "hsl(var(--primary))",
									}}
							/>
						</div>
						{diskSpace.scarcityMultiplier > 1 && (
							<p className="text-xs font-bold text-destructive mt-2 uppercase tracking-widest">
								Silo filling up! Prices x{diskSpace.scarcityMultiplier}
							</p>
						)}
					</div>
				)}

				{/* Main Yard */}
				<div className="grid gap-8 lg:grid-cols-[1fr_320px]">
					<div className="rounded-[3rem] border-4 border-foreground bg-card shadow-[12px_12px_0px_0px_rgba(0,0,0,0.1)]">
						<Tabs defaultValue="history" className="w-full">
							<TabsList className="grid h-auto w-full grid-cols-3 gap-2 border-b-4 border-foreground rounded-t-[2.75rem] bg-muted/30 p-2">
								<TabsTrigger
									value="history"
									className="flex items-center justify-center rounded-full py-3 font-black uppercase transition-all data-[state=active]:bg-primary data-[state=active]:text-primary-foreground"
								>
									<History className="mr-2 h-4 w-4 hidden sm:inline" /> WATCHED
								</TabsTrigger>
								<TabsTrigger
									value="requests"
									className="flex items-center justify-center rounded-full py-3 font-black uppercase transition-all data-[state=active]:bg-primary data-[state=active]:text-primary-foreground"
								>
									<Activity className="mr-2 h-4 w-4 hidden sm:inline" /> REQUESTS
								</TabsTrigger>
								<TabsTrigger
									value="leaderboard"
									className="flex items-center justify-center rounded-full py-3 font-black uppercase transition-all data-[state=active]:bg-primary data-[state=active]:text-primary-foreground"
								>
									<Users className="mr-2 h-4 w-4 hidden sm:inline" /> PECKING ORDER
								</TabsTrigger>
							</TabsList>
							<TabsContent value="history" className="p-6 space-y-4">
								<WatchHistory key={refreshCount} />
							</TabsContent>
							<TabsContent value="requests" className="p-6 space-y-4">
								<RequestHistory />
							</TabsContent>
							<TabsContent value="leaderboard" className="p-6 space-y-4">
								<Leaderboard />
							</TabsContent>
						</Tabs>
					</div>

					<div className="space-y-6">
						<div className="rounded-3xl border-4 border-foreground bg-accent/10 p-6 shadow-sm">
							<div className="mb-4 flex items-center gap-2">
								<Activity className="h-5 w-5 text-primary" />
								<h3 className="font-display text-2xl font-bold uppercase italic text-primary">
									Barn Noise
								</h3>
							</div>
							<div className="max-h-[500px] overflow-y-auto pr-2 scrollbar-hide">
								<ActivityFeed key={refreshCount} />
							</div>
						</div>

						<div className="rounded-3xl border-4 border-primary bg-primary/5 p-6 text-center italic">
							<p className="text-sm font-bold text-primary">
								"The early bird gets the 4K stream."
							</p>
						</div>
					</div>
				</div>
			</div>

			<SearchRequestModal
				open={isSearchModalOpen}
				onOpenChange={setIsSearchModalOpen}
				costs={requestCosts}
			/>
			<BuyCreditsModal open={isBuyModalOpen} onOpenChange={setIsBuyModalOpen} />
		</div>
	);
}
