import { useSuspenseQuery } from "@tanstack/react-query";
import axios from "axios";
import { toast } from "sonner";
import { Card, CardDescription, CardHeader } from "../../../components/ui/card";
import { useAppForm } from "../../../lib/formSutff";
import { getSettings } from "../../../lib/queries/getSettings";

type Setting = {
	id: string;
	name: string;
	description?: string;
	value: string;
	active: boolean;
	inputType: "text" | "boolean" | "number" | "select";
	options?: string[];
};

export default function FeatureCard({ item }: { item: Setting }) {
	const { refetch } = useSuspenseQuery(getSettings());
	const form = useAppForm({
		defaultValues: {
			value: item.value ?? "",
			active: item.active,
		},
		onSubmit: async ({ value }) => {
			try {
				// adding this in as my base as i need to see timers working
				if (window.location.hostname === "localhost") {
					await new Promise((res) => setTimeout(res, 1000));
				}

				const { data } = await axios.patch(`/lst/api/settings/${item.name}`, {
					value: value.value,
					active: value.active ? "true" : "false",
				}, {
			withCredentials: true,
		});

				refetch();
				toast.success(
					<div>
						<p>{data.message}</p>
						<p>
							This was a feature setting so{" "}
							{value.active
								? "processes related to this will start working on there next interval"
								: "processes related to this will stop working on there next interval"}
						</p>
					</div>,
				);
			} catch (error) {
				console.error(error);
			}
		},
	});
	return (
		<Card className="p-2 w-96">
			<CardHeader>
				<p>{item.name}</p>
				<CardDescription>
					<p>{item.description}</p>
				</CardDescription>
			</CardHeader>

			<form
				onSubmit={(e) => {
					e.preventDefault();
					e.stopPropagation();
					void form.handleSubmit();
				}}
			>
				<div className="flex justify-end mt-2 flex-col gap-4">
					<form.AppField name="value">
						{(field) => (
							<field.InputField label="Setting Value" inputType="string" />
						)}
					</form.AppField>
					<div className="flex flex-row justify-between">
						<form.AppField name="active">
							{(field) => (
								<field.SwitchField trueLabel="Active" falseLabel="Deactivate" />
							)}
						</form.AppField>
						<form.AppForm>
							<form.SubmitButton>Update</form.SubmitButton>
						</form.AppForm>
					</div>
				</div>
			</form>
		</Card>
	);
}
