"use client";

import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { Button } from "@/components/ui/button";
import {
	Dialog,
	DialogContent,
	DialogFooter,
	DialogHeader,
	DialogTitle,
} from "@/components/ui/dialog";
import {
	Form,
	FormControl,
	FormField,
	FormItem,
	FormLabel,
	FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import {
	Select,
	SelectContent,
	SelectItem,
	SelectTrigger,
	SelectValue,
} from "@/components/ui/select";
import { CategoryService } from "@/services/category.service";
import { ContentService } from "@/services/content.service";
import type { Category, Content } from "@/types/content";

interface ContentEditDialogProps {
	content: Content | null;
	open: boolean;
	onOpenChange: (open: boolean) => void;
	onSuccess: () => void;
}

export function ContentEditDialog({
	content,
	open,
	onOpenChange,
	onSuccess,
}: ContentEditDialogProps) {
	const [loading, setLoading] = useState(false);
	const [categories, setCategories] = useState<Category[]>([]);

	const form = useForm<{ title: string; categoryId: string }>({
		defaultValues: {
			title: "",
			categoryId: "",
		},
	});

	useEffect(() => {
		CategoryService.getAll().then(setCategories).catch(console.error);
	}, []);

	useEffect(() => {
		if (content) {
			form.reset({
				title: content.title,
				categoryId: content.categoryId || "none",
			});
		}
	}, [content, form]);

	const onSubmit = async (values: { title: string; categoryId: string }) => {
		if (!content) return;
		setLoading(true);
		try {
			const data = {
				...values,
				categoryId: values.categoryId === "none" ? null : values.categoryId,
			};
			await ContentService.updateAdmin(content.id, data);
			onSuccess();
			onOpenChange(false);
		} catch (error) {
			console.error(error);
		} finally {
			setLoading(false);
		}
	};

	return (
		<Dialog open={open} onOpenChange={onOpenChange}>
			<DialogContent>
				<DialogHeader>
					<DialogTitle>Modifier le contenu</DialogTitle>
				</DialogHeader>
				<Form {...form}>
					<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
						<FormField
							control={form.control}
							name="title"
							rules={{ required: "Le titre est requis" }}
							render={({ field }) => (
								<FormItem>
									<FormLabel>Titre</FormLabel>
									<FormControl>
										<Input {...field} placeholder="Titre du contenu" />
									</FormControl>
									<FormMessage />
								</FormItem>
							)}
						/>
						<FormField
							control={form.control}
							name="categoryId"
							render={({ field }) => (
								<FormItem>
									<FormLabel>Catégorie</FormLabel>
									<Select
										onValueChange={field.onChange}
										defaultValue={field.value}
										value={field.value}
									>
										<FormControl>
											<SelectTrigger>
												<SelectValue placeholder="Sélectionner une catégorie" />
											</SelectTrigger>
										</FormControl>
										<SelectContent>
											<SelectItem value="none">Sans catégorie</SelectItem>
											{categories.map((cat) => (
												<SelectItem key={cat.id} value={cat.id}>
													{cat.name}
												</SelectItem>
											))}
										</SelectContent>
									</Select>
									<FormMessage />
								</FormItem>
							)}
						/>
						<DialogFooter>
							<Button
								type="button"
								variant="outline"
								onClick={() => onOpenChange(false)}
							>
								Annuler
							</Button>
							<Button type="submit" disabled={loading}>
								{loading ? "Enregistrement..." : "Enregistrer"}
							</Button>
						</DialogFooter>
					</form>
				</Form>
			</DialogContent>
		</Dialog>
	);
}
