import { useQuery } from "@tanstack/react-query";
import axios from "axios";
import { format } from "date-fns";
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 { getLeases } from "@/lib/querys/forklifts/getLeases";
import { useAppForm } from "../../../../lib/formStuff";

type CompanyData = {
	id: string;
	name: string;
};
export default function NewLeaseForm({
	setOpenDialog,
}: {
	setOpenDialog: any;
}) {
	//const search = useSearch({ from: "/_app/(auth)/login" });
	const { data, isLoading } = useQuery(getCompanies());
	const { refetch } = useQuery(getLeases());
	const form = useAppForm({
		defaultValues: {
			companyId: "",
			leaseNumber: "",
			startDate: "",
			endDate: "",
		},
		onSubmit: async ({ value }) => {
			const data = {
				leaseNumber: value.leaseNumber.trimStart().trimEnd(),
				startDate: format(value.startDate, "MM/dd/yyyy"),
				endDate: format(value.endDate, "MM/dd/yyyy"),
				companyId: value.companyId,
			};
			console.log(data);
			try {
				await axios.post("/lst/api/forklifts/leases", data);
				form.reset();
				setOpenDialog(false);
				refetch();
				toast.success(`${value.leaseNumber} 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);
				}
			}
		},
	});

	if (isLoading) return <div>Loading Companies</div>;

	// remap the companies to fit out select field
	const companyMap = data.map((i: CompanyData) => {
		return { value: i.id, label: i.name };
	});

	//const currentYear = new Date().getFullYear();

	return (
		<>
			<DialogHeader>
				<DialogTitle>Create New Lease</DialogTitle>
				<DialogDescription>
					Select the company this lease will be for, lease number, start and end
					date
				</DialogDescription>
			</DialogHeader>

			<form
				onSubmit={(e) => {
					e.preventDefault();
					form.handleSubmit();
				}}
			>
				<form.AppField
					name="companyId"
					children={(field) => (
						<field.SelectField
							label="Select Company"
							placeholder="Companies"
							options={companyMap}
						/>
					)}
				/>
				<form.AppField
					name="leaseNumber"
					children={(field) => (
						<field.InputField
							label="Lease Number"
							inputType="string"
							required={false}
						/>
					)}
				/>
				<div className="flex flex-row gap-2 mt-2 mb-2">
					<form.AppField
						name="startDate"
						children={(field) => (
							<field.DateField label="Start Date" required />
						)}
					/>
					<form.AppField
						name="endDate"
						children={(field) => <field.DateField label="End Date" required />}
					/>
				</div>

				<DialogFooter>
					<DialogClose asChild>
						<Button variant="outline">Cancel</Button>
					</DialogClose>
					<Button type="submit">Submit</Button>
				</DialogFooter>
			</form>
		</>
	);
}
