"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import {
	AlertTriangle,
	Download,
	Laptop,
	Loader2,
	Moon,
	Palette,
	Save,
	Settings,
	Shield,
	Sun,
	Trash2,
	User as UserIcon,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { useTheme } from "next-themes";
import * as React from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import * as z from "zod";
import { TwoFactorSetup } from "@/components/two-factor-setup";
import {
	AlertDialog,
	AlertDialogAction,
	AlertDialogCancel,
	AlertDialogContent,
	AlertDialogDescription,
	AlertDialogFooter,
	AlertDialogHeader,
	AlertDialogTitle,
	AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import {
	Card,
	CardContent,
	CardDescription,
	CardHeader,
	CardTitle,
} from "@/components/ui/card";
import {
	Form,
	FormControl,
	FormDescription,
	FormField,
	FormItem,
	FormLabel,
	FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Spinner } from "@/components/ui/spinner";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { useAuth } from "@/providers/auth-provider";
import { UserService } from "@/services/user.service";

const settingsSchema = z.object({
	displayName: z.string().max(32, "Le nom d'affichage est trop long").optional(),
	bio: z.string().max(255, "La bio est trop longue").optional(),
	showOnlineStatus: z.boolean(),
	showReadReceipts: z.boolean(),
});

type SettingsFormValues = z.infer<typeof settingsSchema>;

export default function SettingsPage() {
	const { theme, setTheme } = useTheme();
	const { user, isLoading, refreshUser, logout } = useAuth();
	const router = useRouter();
	const [isSaving, setIsSaving] = React.useState(false);
	const [isDeleting, setIsDeleting] = React.useState(false);
	const [isExporting, setIsExporting] = React.useState(false);
	const [mounted, setMounted] = React.useState(false);

	React.useEffect(() => {
		setMounted(true);
	}, []);

	const form = useForm<SettingsFormValues>({
		resolver: zodResolver(settingsSchema),
		defaultValues: {
			displayName: "",
			bio: "",
			showOnlineStatus: true,
			showReadReceipts: true,
		},
	});

	React.useEffect(() => {
		if (user) {
			form.reset({
				displayName: user.displayName || "",
				bio: user.bio || "",
				showOnlineStatus: user.showOnlineStatus ?? true,
				showReadReceipts: user.showReadReceipts ?? true,
			});
		}
	}, [user, form]);

	if (isLoading) {
		return (
			<div className="flex h-[400px] items-center justify-center">
				<Spinner className="h-8 w-8 text-primary" />
			</div>
		);
	}

	if (!user) {
		return (
			<div className="max-w-2xl mx-auto py-8 px-4 text-center">
				<Card>
					<CardHeader>
						<CardTitle>Accès refusé</CardTitle>
						<CardDescription>
							Vous devez être connecté pour accéder aux paramètres.
						</CardDescription>
					</CardHeader>
				</Card>
			</div>
		);
	}

	const onSubmit = async (values: SettingsFormValues) => {
		setIsSaving(true);
		try {
			await UserService.updateMe(values);
			toast.success("Paramètres mis à jour !");
			await refreshUser();
		} catch (error) {
			console.error(error);
			toast.error("Erreur lors de la mise à jour des paramètres.");
		} finally {
			setIsSaving(false);
		}
	};

	const handleDeleteAccount = async () => {
		setIsDeleting(true);
		try {
			await UserService.removeMe();
			toast.success("Votre compte a été supprimé.");
			logout();
			router.push("/");
		} catch (error) {
			console.error(error);
			toast.error("Erreur lors de la suppression du compte.");
		} finally {
			setIsDeleting(false);
		}
	};

	const handleExportData = async () => {
		setIsExporting(true);
		try {
			const data = await UserService.exportData();
			const blob = new Blob([JSON.stringify(data, null, 2)], {
				type: "application/json",
			});
			const url = window.URL.createObjectURL(blob);
			const link = document.createElement("a");
			link.href = url;
			link.setAttribute("download", `memegoat-data-${user?.username}.json`);
			document.body.appendChild(link);
			link.click();
			link.remove();
			toast.success("Vos données ont été exportées avec succès.");
		} catch (error) {
			console.error(error);
			toast.error("Erreur lors de l'exportation des données.");
		} finally {
			setIsExporting(false);
		}
	};

	return (
		<div className="max-w-2xl mx-auto py-12 px-4">
			<div className="flex items-center gap-3 mb-8">
				<div className="bg-primary/10 p-3 rounded-xl">
					<Settings className="h-6 w-6 text-primary" />
				</div>
				<h1 className="text-3xl font-bold tracking-tight">Paramètres</h1>
			</div>

			<div className="space-y-8">
				<Card className="border-none shadow-sm">
					<CardHeader className="pb-4">
						<div className="flex items-center gap-2 mb-1">
							<UserIcon className="h-5 w-5 text-primary" />
							<CardTitle>Informations personnelles</CardTitle>
						</div>
						<CardDescription>
							Mettez à jour vos informations publiques. Ces données seront visibles par
							les autres utilisateurs.
						</CardDescription>
					</CardHeader>
					<CardContent>
						<Form {...form}>
							<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
								<div className="grid gap-6">
									<div className="grid sm:grid-cols-2 gap-4">
										<FormItem>
											<FormLabel>Nom d'utilisateur</FormLabel>
											<FormControl>
												<Input
													value={user.username}
													disabled
													className="bg-muted cursor-not-allowed"
												/>
											</FormControl>
											<FormDescription>Identifiant unique non modifiable.</FormDescription>
										</FormItem>

										<FormField
											control={form.control}
											name="displayName"
											render={({ field }) => (
												<FormItem>
													<FormLabel>Nom d'affichage</FormLabel>
													<FormControl>
														<Input placeholder="Votre nom" {...field} />
													</FormControl>
													<FormDescription>Nom visible sur votre profil.</FormDescription>
													<FormMessage />
												</FormItem>
											)}
										/>
									</div>

									<FormField
										control={form.control}
										name="bio"
										render={({ field }) => (
											<FormItem>
												<FormLabel>Bio</FormLabel>
												<FormControl>
													<Textarea
														placeholder="Racontez-nous quelque chose sur vous..."
														className="resize-none min-h-[100px]"
														{...field}
													/>
												</FormControl>
												<FormDescription>
													Une courte description de vous (max 255 caractères).
												</FormDescription>
												<FormMessage />
											</FormItem>
										)}
									/>
								</div>

								<div className="flex justify-end border-t pt-6">
									<Button type="submit" disabled={isSaving} className="min-w-[150px]">
										{isSaving ? (
											<>
												<Loader2 className="mr-2 h-4 w-4 animate-spin" />
												Enregistrement...
											</>
										) : (
											<>
												<Save className="mr-2 h-4 w-4" />
												Enregistrer
											</>
										)}
									</Button>
								</div>
							</form>
						</Form>
					</CardContent>
				</Card>

				{/* Confidentialité */}
				<Card className="border-none shadow-sm">
					<CardHeader className="pb-4">
						<div className="flex items-center gap-2">
							<Shield className="h-5 w-5 text-primary" />
							<div>
								<CardTitle>Confidentialité</CardTitle>
								<CardDescription>Gérez la visibilité de vos activités.</CardDescription>
							</div>
						</div>
					</CardHeader>
					<CardContent>
						<Form {...form}>
							<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
								<div className="space-y-4">
									<FormField
										control={form.control}
										name="showOnlineStatus"
										render={({ field }) => (
											<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
												<div className="space-y-0.5">
													<FormLabel className="text-base">Statut en ligne</FormLabel>
													<FormDescription>
														Affiche quand vous êtes actif sur le site.
													</FormDescription>
												</div>
												<FormControl>
													<Switch checked={field.value} onCheckedChange={field.onChange} />
												</FormControl>
											</FormItem>
										)}
									/>
									<FormField
										control={form.control}
										name="showReadReceipts"
										render={({ field }) => (
											<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
												<div className="space-y-0.5">
													<FormLabel className="text-base">
														Confirmations de lecture
													</FormLabel>
													<FormDescription>
														Permet aux autres de voir quand vous avez lu leurs messages.
													</FormDescription>
												</div>
												<FormControl>
													<Switch checked={field.value} onCheckedChange={field.onChange} />
												</FormControl>
											</FormItem>
										)}
									/>
								</div>
								<div className="flex justify-end pt-2">
									<Button type="submit" disabled={isSaving} className="min-w-[150px]">
										{isSaving ? (
											<Loader2 className="mr-2 h-4 w-4 animate-spin" />
										) : (
											<Save className="mr-2 h-4 w-4" />
										)}
										Enregistrer
									</Button>
								</div>
							</form>
						</Form>
					</CardContent>
				</Card>

				<TwoFactorSetup />

				<Card className="border-none shadow-sm">
					<CardHeader className="pb-4">
						<div className="flex items-center gap-2 mb-1">
							<Palette className="h-5 w-5 text-primary" />
							<CardTitle>Apparence</CardTitle>
						</div>
						<CardDescription>
							Personnalisez l'apparence de l'application selon vos préférences.
						</CardDescription>
					</CardHeader>
					<CardContent>
						<RadioGroup
							value={mounted ? theme : "system"}
							onValueChange={(value) => setTheme(value)}
							className="grid grid-cols-1 sm:grid-cols-3 gap-4"
						>
							<div className="relative">
								<RadioGroupItem value="light" id="light" className="peer sr-only" />
								<Label
									htmlFor="light"
									className="flex flex-col items-center justify-between rounded-xl border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary [&:has([data-state=checked])]:border-primary cursor-pointer transition-all"
								>
									<Sun className="mb-3 h-6 w-6" />
									<span className="text-sm font-semibold">Clair</span>
								</Label>
							</div>

							<div className="relative">
								<RadioGroupItem value="dark" id="dark" className="peer sr-only" />
								<Label
									htmlFor="dark"
									className="flex flex-col items-center justify-between rounded-xl border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary [&:has([data-state=checked])]:border-primary cursor-pointer transition-all"
								>
									<Moon className="mb-3 h-6 w-6" />
									<span className="text-sm font-semibold">Sombre</span>
								</Label>
							</div>

							<div className="relative">
								<RadioGroupItem value="system" id="system" className="peer sr-only" />
								<Label
									htmlFor="system"
									className="flex flex-col items-center justify-between rounded-xl border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary [&:has([data-state=checked])]:border-primary cursor-pointer transition-all"
								>
									<Laptop className="mb-3 h-6 w-6" />
									<span className="text-sm font-semibold">Système</span>
								</Label>
							</div>
						</RadioGroup>
					</CardContent>
				</Card>

				<Card className="border-none shadow-sm">
					<CardHeader className="pb-4">
						<div className="flex items-center gap-2 mb-1">
							<Download className="h-5 w-5 text-primary" />
							<CardTitle>Portabilité des données</CardTitle>
						</div>
						<CardDescription>
							Conformément au RGPD, vous pouvez exporter l'intégralité de vos données
							rattachées à votre compte.
						</CardDescription>
					</CardHeader>
					<CardContent>
						<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 p-4 rounded-lg bg-white dark:bg-zinc-900 border">
							<div className="space-y-1">
								<p className="font-bold">Exporter mes données</p>
								<p className="text-sm text-muted-foreground">
									Téléchargez un fichier JSON contenant votre profil, vos mèmes et vos
									favoris.
								</p>
							</div>
							<Button
								variant="outline"
								size="sm"
								onClick={handleExportData}
								disabled={isExporting}
								className="font-semibold"
							>
								{isExporting ? (
									<>
										<Loader2 className="mr-2 h-4 w-4 animate-spin" />
										Exportation...
									</>
								) : (
									<>
										<Download className="h-4 w-4 mr-2" />
										Exporter mes données
									</>
								)}
							</Button>
						</div>
					</CardContent>
				</Card>

				<Card className="border-destructive/20 shadow-sm bg-destructive/5">
					<CardHeader className="pb-4">
						<div className="flex items-center gap-2 mb-1">
							<AlertTriangle className="h-5 w-5 text-destructive" />
							<CardTitle className="text-destructive">Zone de danger</CardTitle>
						</div>
						<CardDescription className="text-destructive/80 font-medium">
							Actions irréversibles concernant votre compte.
						</CardDescription>
					</CardHeader>
					<CardContent>
						<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 p-4 rounded-lg bg-white dark:bg-zinc-900 border border-destructive/20">
							<div className="space-y-1">
								<p className="font-bold">Supprimer mon compte</p>
								<p className="text-sm text-muted-foreground">
									Toutes vos données seront supprimées définitivement.
								</p>
							</div>
							<AlertDialog>
								<AlertDialogTrigger asChild>
									<Button variant="destructive" size="sm" className="font-semibold">
										<Trash2 className="h-4 w-4 mr-2" />
										Supprimer le compte
									</Button>
								</AlertDialogTrigger>
								<AlertDialogContent>
									<AlertDialogHeader>
										<AlertDialogTitle>Êtes-vous absolument sûr ?</AlertDialogTitle>
										<AlertDialogDescription>
											Cette action est irréversible. Votre compte sera supprimé
											définitivement ainsi que tous vos mèmes et vos favoris.
										</AlertDialogDescription>
									</AlertDialogHeader>
									<AlertDialogFooter>
										<AlertDialogCancel disabled={isDeleting}>Annuler</AlertDialogCancel>
										<AlertDialogAction
											onClick={handleDeleteAccount}
											disabled={isDeleting}
											className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
										>
											{isDeleting ? (
												<>
													<Loader2 className="mr-2 h-4 w-4 animate-spin" />
													Suppression...
												</>
											) : (
												"Confirmer la suppression"
											)}
										</AlertDialogAction>
									</AlertDialogFooter>
								</AlertDialogContent>
							</AlertDialog>
						</div>
					</CardContent>
				</Card>
			</div>
		</div>
	);
}
