"use client";

import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Loader2, Plus } from "lucide-react";
import { useActionState, useEffect, useState } from "react"; // Import useActionState
import { toast } from "sonner";
import { GetMacAccordion } from "../how-to-get-mac";

import { addDeviceAction } from "@/queries/devices";

export type AddDeviceFormState = {
	message: string;
	fieldErrors?: {
		name?: string[];
		mac_address?: string[];
	};
	payload?: FormData;
};


export const initialState: AddDeviceFormState = {
	message: "",
	fieldErrors: {},
};

export default function AddDeviceDialogForm({ user_id }: { user_id?: string }) {
	const [open, setOpen] = useState(false);

	const [state, formAction, pending] = useActionState(
		addDeviceAction,
		initialState
	);

	useEffect(() => {
		if (state.message && state !== initialState) {
			if (state.fieldErrors && Object.keys(state.fieldErrors).length > 0) {
				toast.error(state.message);
			} else if (state.message.includes("success")) {
				toast.success(state.message);
				setOpen(false);
			} else {
				toast.error(state.message);
			}
		}
	}, [state]);

	if (!user_id) {
		return null;
	}

	return (
		<Dialog open={open} onOpenChange={setOpen}>
			<DialogTrigger asChild>
				<Button className="gap-2 items-center" disabled={pending} variant="default">
					Add Device
					<Plus size={16} />
				</Button>
			</DialogTrigger>
			<DialogContent className="sm:max-w-[425px]">
				<DialogHeader>
					<DialogTitle>New Device</DialogTitle>
					<DialogDescription>
						To add a new device, enter the device name and mac address below.
						Click save when you are done.
					</DialogDescription>
					<GetMacAccordion />
				</DialogHeader>
				<form action={formAction}>
					<div className="grid gap-4 py-4">
						<div className="flex flex-col gap-2">
							<div>
								<Label htmlFor="device_name" className="text-right">
									Device Name
								</Label>
								<Input
									placeholder="eg: iPhone X"
									type="text"
									defaultValue={(state?.payload?.get("name") || "") as string}
									name="name"
									id="device_name"
									className="col-span-3"
								/>
								{state.fieldErrors?.name && (
									<span className="text-red-500 text-sm">
										{state.fieldErrors.name[0]}
									</span>
								)}
							</div>

							<div>
								<Label htmlFor="mac_address" className="text-right">
									Mac Address
								</Label>
								<Input
									placeholder="Mac address of your device"
									name="mac_address"
									defaultValue={(state?.payload?.get("mac_address") || "") as string}
									id="mac_address"
									className="col-span-3"
								/>
								{state.fieldErrors?.mac_address && (
									<span className="text-red-500 text-sm">
										{state.fieldErrors.mac_address[0]}
									</span>
								)}
							</div>
						</div>
					</div>
					<DialogFooter>
						<Button disabled={pending} type="submit">
							{pending ? <Loader2 className="animate-spin" /> : "Save"}
						</Button>
					</DialogFooter>
				</form>
			</DialogContent>
		</Dialog>
	);
}