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 { getServers } from "@/lib/querys/admin/getServers";
import { getForklifts } from "@/lib/querys/forklifts/getForklifts";
import { getLeases } from "@/lib/querys/forklifts/getLeases";
import { useAppForm } from "../../../../lib/formStuff";

const forkliftManufacturer: any = [
	{ value: "Jungheinrich", label: "Jungheinrich" },
	{ value: "Toyota", label: "Toyota" },
	{ value: "Caterpillar", label: "Caterpillar" },
	{ value: "Mitsubishi", label: "Mitsubishi" },
	{ value: "BigJoe", label: "BigJoe" },
	{ value: "Yale", label: "Yale" },
	{ value: "Hyster", label: "Hyster" },
	{ value: "Global", label: "Global" },
	{ value: "Wesco", label: "Wesco" },
	{ value: "JLG", label: "JLG" },
	{ value: "Genie", label: "Genie" },
	{ value: "Linde", label: "Linde" },
	{ value: "Skyjack", label: "Skyjack" },
	{ value: "NilFisk", label: "NilFisk" },
	{ value: "Boomer", label: "Boomer" },
	{ value: "Crown", label: "Crown" },
];

const batteryType: any = [
	{ value: "leadAcid", label: "Lead Acid" },
	{ value: "lithium", label: "Lithium" },
	{ value: "12v", label: "12v" },
];

const engineType: any = [
	{ value: "electric", label: "Electric" },
	{ value: "propane", label: "Propane" },
];

const pfc: any = [
	{ value: "20", label: "EBM" },
	{ value: "30", label: "SBM" },
	{ value: "40", label: "PET" },
	{ value: "50", label: "CAPS" },
];
export default function NewForklift({ setOpenDialog }: { setOpenDialog: any }) {
	//const search = useSearch({ from: "/_app/(auth)/login" });
	const { data: s, isLoading: es } = useQuery(getServers());
	const { refetch: refetchLifts } = useQuery(getForklifts());
	const {
		data: leases,
		isLoading: leaseError,
		refetch,
	} = useQuery(getLeases());

	const form = useAppForm({
		defaultValues: {
			serialNumber: "",
			model: "",
			plant: "",
			profitCenter: "",
			manufacturer: "",
			manufacturerYear: "",
			engine: "",
			batteryType: "lead acid",
			leaseId: "",
		},
		onSubmit: async ({ value }) => {
			// get the glcode
			const glCode = s.filter((n: any) => n.name === value.plant);
			const data = {
				serialNumber: value.serialNumber,
				model: value.model.toUpperCase(),
				plant: value.plant,
				glCode: Number(glCode[0].greatPlainsPlantCode),
				profitCenter: Number(value.profitCenter),
				manufacturer: value.manufacturer,
				manufacturerYear: value.manufacturerYear,
				engine: value.engine,
				batteryType: value.batteryType,
				leaseId: value.leaseId.trimStart().trimEnd(),
			};
			console.log(data);
			try {
				await axios.post("/lst/api/forklifts", data);
				form.reset();
				setOpenDialog(false);
				refetch();
				refetchLifts();
				toast.success(`${value.serialNumber} 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);
				}
			}
		},
	});

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

	if (es) return <div>...Loading Servers</div>;
	if (leaseError) return <div>...Loading Leases</div>;

	const serverMap = s.map((i: any) => {
		return { value: i.name, label: i.name };
	});

	const leaseMap = leases.map((i: any) => {
		return { value: i.id, label: i.leaseNumber };
	});
	return (
		<>
			<DialogHeader>
				<DialogTitle>Create New Forklift</DialogTitle>
				<DialogDescription>Create a new forklift</DialogDescription>
			</DialogHeader>

			<form
				onSubmit={(e) => {
					e.preventDefault();
					form.handleSubmit();
				}}
			>
				<div className="flex flex-row gap-2 mt-2 mb-2">
					<form.AppField
						name="serialNumber"
						children={(field) => (
							<field.InputField
								label="Forklift SN"
								inputType="string"
								required={true}
							/>
						)}
					/>
					<form.AppField
						name="model"
						children={(field) => (
							<field.InputField
								label="Model"
								inputType="string"
								required={true}
							/>
						)}
					/>
				</div>
				<div className="flex flex-row gap-2 mt-2 mb-2">
					<form.AppField
						name="manufacturer"
						children={(field) => (
							<field.SelectField
								label="Select Forklift Manufacturer"
								placeholder="Manufacturer"
								options={forkliftManufacturer}
							/>
						)}
					/>
					<form.AppField
						name="manufacturerYear"
						children={(field) => (
							<field.InputField
								label="Year Made"
								inputType="string"
								required={true}
							/>
						)}
					/>
				</div>
				<div className="flex flex-row gap-2 mt-2 mb-2">
					<form.AppField
						name="engine"
						children={(field) => (
							<field.SelectField
								label="Select Engine Type"
								placeholder="Engine Type"
								options={engineType}
							/>
						)}
					/>
					<form.AppField
						name="batteryType"
						children={(field) => (
							<field.SelectField
								label="Select battery type"
								placeholder="Battery type"
								options={batteryType}
							/>
						)}
					/>
				</div>
				<div>
					<form.AppField
						name="profitCenter"
						children={(field) => (
							<field.SelectField
								label="Select profit center"
								placeholder="Profit Center"
								options={pfc}
							/>
						)}
					/>
				</div>

				<div className="flex flex-row gap-2 mt-2 mb-2">
					<form.AppField
						name="plant"
						children={(field) => (
							<field.SelectField
								label="Select Plant"
								placeholder="Plant"
								options={serverMap}
							/>
						)}
					/>
					<form.AppField
						name="leaseId"
						children={(field) => (
							<field.Searchable
								label="Select Lease"
								searchFor="Lease"
								options={leaseMap}
							/>
						)}
					/>
				</div>

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