import { NodeRect } from "./node-rect";
import { nodeIsConnectable, nodeLabel, useStateStore } from "@/lib/state";
import { useEffect, useMemo } from "react";
import { z } from "zod";
import { DeepPartial, EventType, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Form, FormControl, FormField, FormItem, FormMessage } from "./ui/form";
import { Input } from "./ui/input";
import { Handle, Position } from "@xyflow/react";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Name } from "./node-name";
import { NodeDetailsProps } from "@/lib/types";
import { VolumeNode } from "config";

export function NodeVolume(node: VolumeNode) {
	const { id, data, selected } = node;
	const isConnectable = useMemo(() => nodeIsConnectable(node, "volume"), [node]);
	return (
		<NodeRect id={id} selected={selected} node={node} state={node.data.state}>
			<div style={{ padding: "10px 20px" }}>
				<div>{nodeLabel(node)}</div>
				<div>{data.type && `${data.type}`}</div>
				<div>{data.size && `${data.size}`}</div>
				<Handle
					id="volume"
					type={"source"}
					position={Position.Top}
					isConnectableStart={isConnectable}
					isConnectableEnd={isConnectable}
					isConnectable={isConnectable}
				/>
			</div>
		</NodeRect>
	);
}

const volumeTypes = ["ReadWriteOnce", "ReadOnlyMany", "ReadWriteMany", "ReadWriteOncePod"] as const;

const schema = z.object({
	type: z.enum(volumeTypes),
	size: z.string().min(1).default("1Gi"),
});

export function NodeVolumeDetails({ node, disabled, showName = true }: NodeDetailsProps<VolumeNode>) {
	const { id, data } = node;
	const store = useStateStore();
	const form = useForm<z.infer<typeof schema>>({
		resolver: zodResolver(schema),
		mode: "onChange",
		defaultValues: {
			type: undefined,
			size: "",
		},
	});
	useEffect(() => {
		const sub = form.watch(
			(
				value: DeepPartial<z.infer<typeof schema>>,
				{ name, type }: { name?: keyof z.infer<typeof schema> | undefined; type?: EventType | undefined },
			) => {
				if (type !== "change") {
					return;
				}
				console.log({ name, type, value });
				store.updateNodeData<"volume">(id, {
					type: value.type,
					size: value.size,
				});
			},
		);
		return () => sub.unsubscribe();
	}, [id, form, store]);
	useEffect(() => {
		form.reset({
			type: data.type,
			size: data.size,
		});
	}, [form, data]);
	return (
		<>
			{showName ? <Name node={node} disabled={disabled} /> : null}
			<Form {...form}>
				<form className="space-y-2">
					<FormField
						control={form.control}
						name="type"
						render={({ field }) => (
							<FormItem>
								<Select onValueChange={field.onChange} defaultValue={field.value} disabled={disabled}>
									<FormControl>
										<SelectTrigger>
											<SelectValue placeholder="Volume Type" />
										</SelectTrigger>
									</FormControl>
									<SelectContent>
										{volumeTypes.map((t) => (
											<SelectItem key={t} value={t}>
												{t}
											</SelectItem>
										))}
									</SelectContent>
								</Select>
								<FormMessage />
							</FormItem>
						)}
					/>
					<FormField
						control={form.control}
						name="size"
						render={({ field }) => (
							<FormItem>
								<FormControl>
									<Input placeholder="size" {...field} disabled={disabled} />
								</FormControl>
								<FormMessage />
							</FormItem>
						)}
					/>
				</form>
			</Form>
		</>
	);
}
