"use client";
import { createReport } from "(app)/admin/report/actions";
import { getUser } from "(app)/admin/user/action";
import { useQuery } from "@tanstack/react-query";
import { Select } from "_components/ui/Select";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { TriangleAlert } from "lucide-react";
import toast from "react-hot-toast";
import { Button } from "@repo/shared-components";
import { ReportOptionalDefaults, ReportOptionalDefaultsSchema } from "@repo/db/zod";
import { zodResolver } from "@hookform/resolvers/zod";

export const NewReportForm = ({
	defaultValues,
}: {
	defaultValues?: Partial<ReportOptionalDefaults>;
}) => {
	const session = useSession();
	const [search, setSearch] = useState("");
	const { data: user } = useQuery({
		queryKey: ["newReport"],
		queryFn: async () =>
			getUser({
				OR: [
					{ firstname: { contains: search, mode: "insensitive" } },
					{ lastname: { contains: search, mode: "insensitive" } },
					{ publicId: { contains: search, mode: "insensitive" } },
					{ id: defaultValues?.reportedUserId || "" },
				],
			}),
		enabled: search.length > 0,
		refetchOnWindowFocus: false,
	});
	const router = useRouter();
	const form = useForm({
		resolver: zodResolver(ReportOptionalDefaultsSchema),
		defaultValues: {
			reportedUserId: defaultValues?.reportedUserId || "",
			senderUserId: session.data?.user.id || "",
			reviewerComment: null,
			reviewerUserId: null,
		},
	});

	return (
		<form
			className="flex flex-wrap gap-3"
			onSubmit={form.handleSubmit(async (values) => {
				console.log("Form submitted with values:", values);
				const newReport = await createReport(values);
				toast.success("Report erfolgreich erstellt!");
				router.push(`/admin/report/${newReport.id}`);
			})}
		>
			<div className="card bg-base-200 flex-1 basis-[800px] shadow-xl">
				<div className="card-body">
					<h2 className="card-title">
						<TriangleAlert /> Neuen Report erstellen
					</h2>
					<Select
						form={form}
						options={
							user?.map((u) => ({
								label: `${u.firstname} ${u.lastname} (${u.publicId})`,
								value: u.id,
							})) || [
								{
									label: "Kein Nutzer gefunden",
									value: "",
									disabled: true,
								},
							]
						}
						onInputChange={(v) => setSearch(v)}
						name="reportedUserId"
						label="Nutzer"
					/>
					<Select
						form={form}
						options={[
							{ label: "Nutzer", value: "Nutzer" },
							{ label: "Pilot", value: "Pilot" },
							{ label: "Disponent", value: "Disponent" },
						]}
						name="reportedUserRole"
						label="Rolle des Nutzers"
					/>
					<textarea
						{...form.register("text")}
						className="textarea w-full"
						placeholder="Beschreibe den Vorfall"
					/>
				</div>
			</div>
			<div className="card bg-base-200 flex-1 basis-[800px] shadow-xl">
				<div className="card-body">
					<div className="flex w-full gap-4">
						<Button
							isLoading={form.formState.isSubmitting}
							type="submit"
							className="btn btn-primary flex-1"
						>
							Speichern
						</Button>
					</div>
				</div>
			</div>
		</form>
	);
};
