"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import {
	Users,
	Database,
	Settings,
	TrendingUp,
	ShieldAlert,
	Search,
	RefreshCcw,
	ArrowLeft,
	Save,
	Gift,
} from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
	Card,
	CardContent,
	CardDescription,
	CardHeader,
	CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { api, adminApi } from "@/lib/api";
import { useStore } from "@/lib/store";
import { formatNumber } from "@/lib/utils";

interface Analytics {
	users: { total: number; with_wallet: number; active_30d: number };
	transactions: {
		total_earned: number;
		total_spent: number;
		total_count: number;
	};
	requests: {
		total: number;
		pending: number;
		approved: number;
		declined: number;
	};
}

interface User {
	id: string;
	plexUsername: string;
	isAdmin: boolean;
	totalEarned: number;
	totalSpent: number;
}

interface SystemSettings {
	creditsPerMinute: number;
	movieRequestCost: number;
	tvRequestCost: number;
	tvPerSeasonCost: number;
	minWatchPercent: number;
	minWatchMinutes: number;
}

export default function AdminPage() {
	const router = useRouter();
	const { user, isAuthenticated } = useStore();
	const [analytics, setAnalytics] = useState<Analytics | null>(null);
	const [users, setUsers] = useState<User[]>([]);
	const [settings, setSettings] = useState<SystemSettings | null>(null);
	const [searchQuery, setSearchQuery] = useState("");
	const [isLoading, setIsLoading] = useState(true);
	const [isSavingSettings, setIsSavingSettings] = useState(false);
	const [rewardAmount, setRewardAmount] = useState<Record<string, string>>({});

	useEffect(() => {
		if (!isAuthenticated || !user?.isAdmin) {
			router.push("/dashboard");
			return;
		}
		loadData();
	}, [isAuthenticated, user, router]);

	const loadData = async () => {
		try {
			const [analyticsRes, usersRes, settingsRes] = await Promise.all([
				adminApi.getAnalytics(),
				adminApi.getUsers(),
				adminApi.getSettings(),
			]);
			setAnalytics(analyticsRes.data);
			setUsers(usersRes.data.users || []);
			setSettings(settingsRes.data);
		} catch {
			toast.error("Failed to load coop secrets");
		} finally {
			setIsLoading(false);
		}
	};

	const handleUpdateSettings = async (e: React.FormEvent) => {
		e.preventDefault();
		if (!settings) return;
		setIsSavingSettings(true);
		try {
			await adminApi.updateSettings(settings);
			toast.success("Barn rules updated!");
		} catch {
			toast.error("Failed to update rules");
		} finally {
			setIsSavingSettings(false);
		}
	};

	const adjustUser = async (userId: string, amount: number, reason: string) => {
		try {
			await adminApi.adjustUser(userId, amount, reason);
			toast.success("Feathers adjusted!");
			loadData();
		} catch {
			toast.error("Failed to adjust nest");
		}
	};

	const backfillUser = async (userId: string) => {
		toast.info("Scouring the barn for old eggs...");
		try {
			await adminApi.backfillUser(userId);
			toast.success("Backfill complete!");
			loadData();
		} catch {
			toast.error("Backfill failed");
		}
	};

	const toggleAdmin = async (userId: string, isAdmin: boolean) => {
		try {
			await api.patch(`/admin/users/${userId}`, { isAdmin });
			toast.success(isAdmin ? "Promoted to Rooster!" : "Demoted to Hen.");
			loadData();
		} catch {
			toast.error("Failed to change pecking order");
		}
	};

	const filteredUsers = users.filter((u) =>
		u.plexUsername?.toLowerCase().includes(searchQuery.toLowerCase()),
	);

	if (isLoading)
		return (
			<div className="flex min-h-screen items-center justify-center font-display text-primary bg-background uppercase">
				Peeking into the coop...
			</div>
		);

	return (
		<div className="min-h-screen bg-background p-4 sm:p-8 font-sans">
			<div className="mx-auto max-w-6xl space-y-8">
				<div className="flex flex-col items-start justify-between gap-4 rounded-3xl border-4 border-primary bg-secondary/20 p-6 shadow-[8px_8px_0px_0px_rgba(0,0,0,1)] md:flex-row md:items-center">
					<div className="flex items-center gap-4">
						<Button
							variant="ghost"
							onClick={() => router.push("/dashboard")}
							className="rounded-full p-2 h-10 w-10 border-2 border-foreground hover:bg-background transition-all"
						>
							<ArrowLeft className="h-6 w-6" />
						</Button>
						<div>
							<h1 className="font-display text-4xl leading-none text-primary uppercase italic tracking-tighter">
								COOP CONTROL
							</h1>
							<p className="text-sm font-bold text-muted-foreground">
								The Farmer's Desk
							</p>
						</div>
					</div>
					<Button
						onClick={loadData}
						variant="outline"
						className="rounded-full border-2 border-primary font-bold shadow-[4px_4px_0px_0px_rgba(192,111,74,1)] hover:translate-x-[2px] hover:translate-y-[2px] hover:shadow-none transition-all"
					>
						<RefreshCcw className="mr-2 h-4 w-4" /> REFRESH
					</Button>
				</div>

				<Tabs defaultValue="flock" className="w-full">
					<TabsList className="grid w-full grid-cols-3 gap-2 rounded-full border-4 border-foreground bg-muted/30 p-2 mb-8 h-auto">
						<TabsTrigger
							value="flock"
							className="rounded-full py-3 font-black uppercase data-[state=active]:bg-primary data-[state=active]:text-primary-foreground transition-all"
						>
							<Users className="mr-2 h-4 w-4" /> THE FLOCK
						</TabsTrigger>
						<TabsTrigger
							value="rules"
							className="rounded-full py-3 font-black uppercase data-[state=active]:bg-primary data-[state=active]:text-primary-foreground transition-all"
						>
							<Settings className="mr-2 h-4 w-4" /> BARN RULES
						</TabsTrigger>
						<TabsTrigger
							value="stats"
							className="rounded-full py-3 font-black uppercase data-[state=active]:bg-primary data-[state=active]:text-primary-foreground transition-all"
						>
							<TrendingUp className="mr-2 h-4 w-4" /> EGG STATS
						</TabsTrigger>
					</TabsList>

					<TabsContent
						value="flock"
						className="space-y-6 focus-visible:outline-none"
					>
						<div className="rounded-[2.5rem] border-4 border-foreground bg-card p-6 shadow-[10px_10px_0px_0px_rgba(0,0,0,0.05)]">
							<div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
								<h2 className="font-display text-3xl uppercase italic">
									The Peeps
								</h2>
								<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-muted-foreground" />
									<Input
										placeholder="Search chickens..."
										value={searchQuery}
										onChange={(e) => setSearchQuery(e.target.value)}
										className="rounded-full border-2 border-foreground pl-10 focus-visible:ring-primary h-12"
									/>
								</div>
							</div>

							<div className="space-y-4">
								{filteredUsers.map((u) => (
									<div
										key={u.id}
										className="flex flex-col gap-4 rounded-2xl border-4 border-foreground bg-accent/5 p-4 sm:flex-row sm:items-center sm:justify-between hover:bg-accent/10 transition-colors"
									>
										<div className="flex-1">
											<div className="flex items-center gap-2">
												<span className="font-black text-xl">
													{u.plexUsername}
												</span>
												{u.isAdmin && (
													<span className="rounded-full bg-primary px-3 py-1 text-[10px] font-black text-white uppercase shadow-sm">
														Rooster
													</span>
												)}
											</div>
											<div className="text-sm font-bold text-muted-foreground mt-1">
												Nest Egg: {formatNumber(u.totalEarned - u.totalSpent)}{" "}
												$COOP
											</div>
										</div>

										<div className="flex flex-wrap items-center gap-2">
											<div className="flex items-center gap-1 rounded-full border-2 border-foreground bg-background p-1 pr-3 shadow-sm">
												<Input
													type="number"
													placeholder="Amount"
													value={rewardAmount[u.id] || ""}
													onChange={(e) =>
														setRewardAmount({
															...rewardAmount,
															[u.id]: e.target.value,
														})
													}
													className="h-8 w-20 border-0 bg-transparent text-center font-bold focus-visible:ring-0"
												/>
												<Button
													size="sm"
													className="h-8 rounded-full font-black px-4"
													onClick={() => {
														const val = parseInt(rewardAmount[u.id]);
														if (val) adjustUser(u.id, val, "Farmer's Reward");
													}}
												>
													<Gift className="h-3 w-3 mr-1" /> REWARD
												</Button>
											</div>

											<Button
												size="sm"
												variant="outline"
												className="h-10 rounded-full font-black border-2 border-foreground"
												onClick={() => backfillUser(u.id)}
											>
												BACKFILL
											</Button>

											<div className="h-10 w-px bg-foreground/10 mx-1 hidden sm:block" />

											<Button
												size="sm"
												variant={u.isAdmin ? "destructive" : "secondary"}
												className="h-10 rounded-full font-black border-2 border-foreground shadow-[2px_2px_0px_0px_rgba(0,0,0,1)] hover:shadow-none transition-all"
												onClick={() => toggleAdmin(u.id, !u.isAdmin)}
											>
												{u.isAdmin ? "DEMOTE" : "PROMOTE"}
											</Button>
										</div>
									</div>
								))}
							</div>
						</div>
					</TabsContent>

					<TabsContent value="rules" className="focus-visible:outline-none">
						<Card className="rounded-[2.5rem] border-4 border-foreground bg-card shadow-[10px_10px_0px_0px_rgba(0,0,0,0.05)] overflow-hidden">
							<CardHeader className="bg-primary/5 border-b-4 border-foreground">
								<CardTitle className="font-display text-3xl uppercase italic">
									The Barn Rules
								</CardTitle>
								<CardDescription className="font-bold text-muted-foreground italic">
									Change the physics of the coop
								</CardDescription>
							</CardHeader>
							<CardContent className="p-8">
								{settings && (
									<form
										onSubmit={handleUpdateSettings}
										className="grid gap-8 md:grid-cols-2"
									>
										<div className="space-y-4">
											<h3 className="font-black uppercase tracking-widest text-primary text-sm flex items-center gap-2">
												<TrendingUp className="h-4 w-4" /> Earning Logic
											</h3>
											<div className="space-y-2">
												<label
													htmlFor="creditsPerMinute"
													className="text-xs font-black uppercase text-muted-foreground"
												>
													Credits Per Minute
												</label>
												<Input
													id="creditsPerMinute"
													type="number"
													value={settings.creditsPerMinute}
													onChange={(e) =>
														setSettings({
															...settings,
															creditsPerMinute: Number(e.target.value),
														})
													}
													className="border-2 border-foreground h-12 font-bold focus-visible:ring-primary"
												/>
											</div>
											<div className="space-y-2">
												<label
													htmlFor="minWatchPercent"
													className="text-xs font-black uppercase text-muted-foreground"
												>
													Min Watch % for Credit
												</label>
												<Input
													id="minWatchPercent"
													type="number"
													value={settings.minWatchPercent}
													onChange={(e) =>
														setSettings({
															...settings,
															minWatchPercent: Number(e.target.value),
														})
													}
													className="border-2 border-foreground h-12 font-bold focus-visible:ring-primary"
												/>
											</div>
										</div>

										<div className="space-y-4">
											<h3 className="font-black uppercase tracking-widest text-primary text-sm flex items-center gap-2">
												<Database className="h-4 w-4" /> Request Costs
											</h3>
											<div className="space-y-2">
												<label
													htmlFor="movieRequestCost"
													className="text-xs font-black uppercase text-muted-foreground"
												>
													Movie Request Cost
												</label>
												<Input
													id="movieRequestCost"
													type="number"
													value={settings.movieRequestCost}
													onChange={(e) =>
														setSettings({
															...settings,
															movieRequestCost: Number(e.target.value),
														})
													}
													className="border-2 border-foreground h-12 font-bold focus-visible:ring-primary"
												/>
											</div>
											<div className="space-y-2">
												<label
													htmlFor="tvRequestCost"
													className="text-xs font-black uppercase text-muted-foreground"
												>
													TV Request Cost
												</label>
												<Input
													id="tvRequestCost"
													type="number"
													value={settings.tvRequestCost}
													onChange={(e) =>
														setSettings({
															...settings,
															tvRequestCost: Number(e.target.value),
														})
													}
													className="border-2 border-foreground h-12 font-bold focus-visible:ring-primary"
												/>
											</div>
										</div>

										<div className="md:col-span-2 pt-4">
											<Button
												type="submit"
												disabled={isSavingSettings}
												className="w-full h-14 rounded-full font-black text-xl shadow-[6px_6px_0px_0px_rgba(0,0,0,1)] hover:translate-x-[2px] hover:translate-y-[2px] hover:shadow-none transition-all border-4 border-foreground"
											>
												{isSavingSettings
													? "SAVING..."
													: "NAIL RULES TO THE DOOR"}{" "}
												<Save className="ml-2 h-6 w-6" />
											</Button>
										</div>
									</form>
								)}
							</CardContent>
						</Card>
					</TabsContent>

					<TabsContent value="stats" className="focus-visible:outline-none">
						<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
							<div className="rounded-3xl border-4 border-foreground bg-card p-6 shadow-[6px_6px_0px_0px_rgba(0,0,0,1)]">
								<div className="text-xs font-black uppercase tracking-widest text-muted-foreground mb-2 flex items-center gap-2">
									<Users className="h-3 w-3" /> Flock Size
								</div>
								<div className="text-4xl font-black">
									{analytics?.users.total || 0}
								</div>
							</div>
							<div className="rounded-3xl border-4 border-foreground bg-card p-6 shadow-[6px_6px_0px_0px_rgba(0,0,0,1)]">
								<div className="text-xs font-black uppercase tracking-widest text-muted-foreground mb-2 flex items-center gap-2">
									<Database className="h-3 w-3" /> Total $COOP
								</div>
								<div className="text-4xl font-black">
									{formatNumber(analytics?.transactions.total_earned || 0)}
								</div>
							</div>
							<div className="rounded-3xl border-4 border-foreground bg-card p-6 shadow-[6px_6px_0px_0px_rgba(0,0,0,1)]">
								<div className="text-xs font-black uppercase tracking-widest text-muted-foreground mb-2 flex items-center gap-2">
									<TrendingUp className="h-3 w-3" /> Requests
								</div>
								<div className="text-4xl font-black">
									{analytics?.requests.total || 0}
								</div>
							</div>
							<div className="rounded-3xl border-4 border-foreground bg-card p-6 shadow-[6px_6px_0px_0px_rgba(0,0,0,1)]">
								<div className="text-xs font-black uppercase tracking-widest text-muted-foreground mb-2 flex items-center gap-2">
									<ShieldAlert className="h-3 w-3 text-destructive" /> Pending
								</div>
								<div className="text-4xl font-black text-destructive">
									{analytics?.requests.pending || 0}
								</div>
							</div>
						</div>
					</TabsContent>
				</Tabs>
			</div>
		</div>
	);
}
