import { useQuery } from "@tanstack/react-query";
import axios from "axios";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
	DialogClose,
	DialogDescription,
	DialogFooter,
	DialogHeader,
	DialogTitle,
} from "@/components/ui/dialog";
import { getCompanies } from "@/lib/querys/forklifts/getCompanies";
import { useAppForm } from "../../../../lib/formStuff";

export default function NewCompanyForm({
	setOpenDialog,
}: {
	setOpenDialog: any;
}) {
	//const search = useSearch({ from: "/_app/(auth)/login" });
	const { refetch } = useQuery(getCompanies());

	const form = useAppForm({
		defaultValues: {
			name: "",
		},
		onSubmit: async ({ value }) => {
			try {
				await axios.post("/lst/api/forklifts/companies", {
					name: value.name,
				});
				form.reset();
				setOpenDialog(false);
				refetch();
				toast.success(`${value.name} was just created `);
			} catch (error) {
				// @ts-ignore
				if (!error.response.data.success) {
					// @ts-ignore
					toast.error(error?.response?.data.message);
				} else {
					// @ts-ignore
					toast.error(error?.message);
				}
			}
		},
	});
	return (
		<>
			<DialogHeader>
				<DialogTitle>Create New Company</DialogTitle>
				<DialogDescription>Add the new Leasing company</DialogDescription>
			</DialogHeader>

			<form
				onSubmit={(e) => {
					e.preventDefault();
					form.handleSubmit();
				}}
			>
				<form.AppField
					name="name"
					children={(field) => (
						<field.InputField
							label="Company Name"
							inputType="string"
							required={true}
						/>
					)}
				/>
			</form>
			<DialogFooter>
				<DialogClose asChild>
					<Button variant="outline">Cancel</Button>
				</DialogClose>
				<Button type="submit">Submit</Button>
			</DialogFooter>
		</>
	);
}
