import { useSuspenseQuery } from "@tanstack/react-query";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "../../../components/ui/button";
import {
	Dialog,
	DialogContent,
	DialogDescription,
	DialogHeader,
	DialogTitle,
} from "../../../components/ui/dialog";
import { api } from "../../../lib/apiHelper";
import { useAppForm } from "../../../lib/formSutff";
import { getScannerIds } from "../../../lib/queries/getScannerIds";

export default function NewScanUser({ refetch }: { refetch: any }) {
	const [open, setOpen] = useState(false);
	const { data, refetch: scannerFetch } = useSuspenseQuery(getScannerIds());
	const form = useAppForm({
		defaultValues: {
			name: "",
			scannerId: "",
			pinNumber: "",
		},
		onSubmit: async ({ value }) => {
			if (value.scannerId === "") {
				toast.error(
					"Scanner id is required please select a scanner id before submitting ",
				);
				return;
			}

			try {
				const { data } = await api.post(
					"/mobile/auth/user",
					{
						name: value.name,
						pinNumber: value.pinNumber,
						scannerId: value.scannerId,
					},
					{
						withCredentials: true,
						timeout: 15000,
						validateStatus: () => true,
					},
				);

				if (data.success) {
					toast.success(
						`${value.name}, was just created and can now log into the scanner with PIN: ${value.pinNumber}`,
					);
					form.reset();
					setOpen(false);
					refetch();
				}

				if (!data.success) {
					toast.error(data.message);
					return;
				}
			} catch (error) {
				console.error(error);
			}
		},
	});

	const closeModel = (e: boolean) => {
		setOpen(e);

		if (!e) {
			form.reset();
			scannerFetch();
		}
	};

	const openForm = () => {
		setOpen(true);
		scannerFetch();
	};

	let n: any = [];
	if (data) {
		n = data.map((i: any) => ({
			label: i.label,
			value: i.value.toString(),
		}));
	}

	return (
		<Dialog onOpenChange={(e) => closeModel(e)} open={open}>
			<Button onClick={openForm}>Create new user</Button>

			<DialogContent showCloseButton={false}>
				<DialogHeader>
					<DialogTitle>Create New Scan user.</DialogTitle>
					<DialogDescription></DialogDescription>
				</DialogHeader>
				<form
					onSubmit={(e) => {
						e.preventDefault();
						form.handleSubmit();
					}}
				>
					<div className="mb-2">
						<form.AppField name="name">
							{(field) => (
								<field.InputField
									label="Name"
									inputType="text"
									required={true}
								/>
							)}
						</form.AppField>
					</div>

					<div className="w-32">
						<form.AppField name="scannerId">
							{(field) => (
								<field.SelectField
									label="Scanner Id"
									placeholder="Select New scanner Id"
									options={n}
								/>
							)}
						</form.AppField>
					</div>
					<div className="flex flex-row">
						<div>
							<form.AppField name="pinNumber">
								{(field) => (
									<field.InputField
										label="Pin Number"
										inputType="number"
										required={true}
									/>
								)}
							</form.AppField>
						</div>
						<div className="mt-9 ml-2">
							<Button
								type="button"
								onClick={async () => {
									const { data } = await api.get("/mobile/pin/new");

									form.setFieldValue("pinNumber", data.data[0].pin);
								}}
							>
								New Pin
							</Button>
						</div>
					</div>
					<div className="flex justify-end mt-2 ">
						<form.AppForm>
							<form.SubmitButton>Submit</form.SubmitButton>
						</form.AppForm>
					</div>
				</form>
			</DialogContent>
		</Dialog>
	);
}
