import { useForm } from "@tanstack/react-form";
import { useRouter } from "@tanstack/react-router";
import axios from "axios";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { CardContent, CardFooter, CardHeader } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { useAuth } from "@/lib/authClient";
import { LstCard } from "../../extendedUi/LstCard";

export default function Comment(data: any) {
	const { session } = useAuth();
	const [isSubmitting, setIsSubmitting] = useState(false);
	const router = useRouter();

	const form = useForm({
		defaultValues: {
			comment: "",
		},
		onSubmit: async ({ value }) => {
			setIsSubmitting(true);

			try {
				const res = await axios.post(
					`/lst/old/api/logistics/postcomment/${data.id.split("&")[0]}`,
					{
						comment: value.comment,
						key: data.id.split("&")[1].replace("amp;", ""),
						username: session?.user.username,
					},
				);

				if (res.data.success) {
					toast.success(res.data.message);
					form.reset();
					router.navigate({ to: "/old/siloAdjustments" });
				}

				if (!res.data.success) {
					toast.error(res.data.message);
					form.reset();
				}
			} catch (error) {
				console.log(error);
				toast.error(`There was an error posting your comment.`);
			}
			setIsSubmitting(false);
		},
	});
	return (
		<div className="">
			<LstCard>
				<CardHeader>Please enter your comment for the silo adjust</CardHeader>
				<CardContent>
					<form
						onSubmit={(e) => {
							e.preventDefault();
							e.stopPropagation();
						}}
					>
						<form.Field
							name="comment"
							validators={{
								// We can choose between form-wide and field-specific validators
								onChange: ({ value }) =>
									value.length > 10
										? undefined
										: "Comment must be longer than 10 characters.",
							}}
							children={(field) => {
								return (
									<div className="m-2 min-w-48 max-w-96 p-2">
										<Label htmlFor="comment" className="mb-2">
											Comment
										</Label>
										<Textarea
											name={field.name}
											value={field.state.value}
											onBlur={field.handleBlur}
											//type="number"
											onChange={(e) => field.handleChange(e.target.value)}
										/>
										{field.state.meta.errors.length ? (
											<em>{field.state.meta.errors.join(",")}</em>
										) : null}
									</div>
								);
							}}
						/>
					</form>
				</CardContent>
				<CardFooter>
					<div className="flex justify-end">
						<Button onClick={form.handleSubmit} disabled={isSubmitting}>
							Submit
						</Button>
					</div>
				</CardFooter>
			</LstCard>
		</div>
	);
}
