import { DialogProps } from "@radix-ui/react-dialog";
import { LocationForm, LocationFormValues } from "./location-form";
import { useState } from "react";
import { UseFormReturn } from "react-hook-form";
import {
	Dialog,
	DialogContent,
	DialogFooter,
	DialogHeader,
	DialogTitle,
	DialogTrigger,
} from "../ui/dialog";
import { Button } from "../ui/button";
import { Location } from "@/types/types";

const LocationDialog: React.FC<
	{
		onDelete?: (location: Location) => void;
		onUpdate?: (formValues: LocationFormValues) => void;
		onAdd?: (formValues: LocationFormValues) => void;
		location?: Location;
	} & DialogProps
> = ({ open, onOpenChange, onDelete, onUpdate, onAdd, location }) => {
	const [form, setForm] = useState<UseFormReturn<LocationFormValues>>();

	const submitForm = (event: "add" | "update") => {
		const callback = event === "add" ? onAdd : onUpdate;
		if (callback) form?.handleSubmit(callback)();
	};

	if (!(onAdd || onUpdate)) return;

	return (
		<Dialog open={open} onOpenChange={onOpenChange}>
			<DialogTrigger asChild>
				<Button>
					{!location
						? "Ajouter une nouvelle adresse"
						: "Modifier l'adresse"}
				</Button>
			</DialogTrigger>
			<DialogContent>
				<DialogHeader>
					<DialogTitle>
						{!location ? "Nouvelle adresse" : "Modifier"}
					</DialogTitle>
				</DialogHeader>
				<LocationForm location={location} setForm={setForm} />
				<DialogFooter className="flex flex-row justify-end">
					{onUpdate && (
						<Button
							variant="outline"
							onClick={() => submitForm("update")}
							type="submit"
						>
							Actualiser
						</Button>
					)}
					{onDelete && (
						<Button
							variant="destructive"
							onClick={() => location && onDelete(location)}
							type="submit"
						>
							Supprimer
						</Button>
					)}
					{onAdd && !onUpdate && !onDelete && (
						<Button onClick={() => submitForm("add")} type="submit">
							Ajouter
						</Button>
					)}
				</DialogFooter>
			</DialogContent>
		</Dialog>
	);
};

export default LocationDialog;
