import { useEffect } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import {
	Dialog,
	DialogContent,
	DialogHeader,
	DialogTitle,
	DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
	Form,
	FormControl,
	FormField,
	FormItem,
	FormLabel,
	FormMessage,
} from "@/components/ui/form";

const memberSchema = z.object({
	userId: z.string().optional(),
	firstname: z.string().min(1, "Prénom est requis."),
	lastname: z.string().min(1, "Nom de famille est requis."),
	email: z.string().email("Adresse email invalide."),
	password: z
		.string()
		.min(6, "Le mot de passe doit avoir au moins 6 caractères.")
		.optional(),
	phone: z.string().regex(/^\d{10}$/, "Le numéro doit avoir 10 chiffres."),
	role: z.string().min(1, "Le rôle est requis."),
});

const updateMemberSchema = memberSchema.partial();

export type Member = z.infer<typeof memberSchema>;

interface MemberDialogProps {
	isOpen: boolean;
	onClose: () => void;
	member: Member | null;
	onSave: (member: Member) => void;
}

export default function MemberDialog({
	isOpen,
	onClose,
	member,
	onSave,
}: MemberDialogProps) {
	const schema = member?.userId ? updateMemberSchema : memberSchema;
	const form = useForm<Member>({
		resolver: zodResolver(schema),
		defaultValues: member?.userId
			? member
			: {
					userId: "",
					firstname: "",
					lastname: "",
					email: "",
					password: "",
					phone: "",
					role: "",
				},
	});

	useEffect(() => {
		if (member) {
			form.reset(member);
		} else {
			form.reset({
				userId: "",
				firstname: "",
				lastname: "",
				email: "",
				password: "",
				phone: "",
				role: "",
			});
		}
	}, [member, form]);

	const onSubmit = (data: Member) => {
		onSave(data);
		onClose();
	};

	return (
		<Dialog open={isOpen} onOpenChange={onClose}>
			<DialogContent>
				<DialogHeader>
					<DialogTitle>
						{member
							? "Mis à jour du membre"
							: "Créer un nouveau membre"}
					</DialogTitle>
				</DialogHeader>
				<Form {...form}>
					<form
						onSubmit={form.handleSubmit(onSubmit)}
						className="space-y-4"
					>
						{(
							[
								"userId",
								"firstname",
								"lastname",
								"email",
								"password",
								"phone",
								"role",
							] as const
						).map((field) => (
							<FormField
								key={field}
								control={form.control}
								name={field}
								render={({ field }) => (
									<FormItem>
										<FormLabel>
											{field.name
												.charAt(0)
												.toUpperCase() +
												field.name.slice(1)}
										</FormLabel>
										<FormControl>
											<Input
												{...field}
												disabled={
													field.name === "userId"
												}
											/>
										</FormControl>
										<FormMessage />
									</FormItem>
								)}
							/>
						))}
						<DialogFooter>
							<Button type="submit">
								{member ? "Actualiser" : "Ajouter"}
							</Button>
						</DialogFooter>
					</form>
				</Form>
			</DialogContent>
		</Dialog>
	);
}
