"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { KeywordOptionalDefaultsSchema } from "@repo/db/zod";
import { useForm } from "react-hook-form";
import { KEYWORD_CATEGORY, Keyword } from "@repo/db";
import { FileText } from "lucide-react";
import { Input } from "../../../../_components/ui/Input";
import { deleteKeyword, upsertKeyword } from "../action";
import { Button } from "../../../../_components/ui/Button";
import { redirect } from "next/navigation";
import { ListInput } from "_components/ui/List";
import toast from "react-hot-toast";

export const KeywordForm = ({ keyword }: { keyword?: Keyword }) => {
	const form = useForm({
		resolver: zodResolver(KeywordOptionalDefaultsSchema),
		defaultValues: keyword,
	});
	return (
		<>
			<form
				onSubmit={form.handleSubmit(async (values) => {
					await upsertKeyword(values, keyword?.id);
					toast.success("Daten gespeichert");
					if (!keyword) redirect(`/admin/keyword`);
				})}
				className="grid grid-cols-6 gap-3"
			>
				<div className="card bg-base-200 col-span-6 shadow-xl">
					<div className="card-body">
						<h2 className="card-title">
							<FileText className="h-5 w-5" /> Allgemeines
						</h2>
						<label className="form-control w-full">
							<span className="label-text flex items-center gap-2 text-lg">Kategorie</span>
							<select
								className="input-sm select select-bordered select-sm w-full"
								{...form.register("category")}
							>
								{Object.keys(KEYWORD_CATEGORY).map((use) => (
									<option key={use} value={use}>
										{use}
									</option>
								))}
							</select>
						</label>
						<Input form={form} label="Abkürzung" name="abreviation" className="input-sm" />
						<Input
							form={form}
							label="Name"
							placeholder="Atembeschwerden, die nicht zunehmen (ohne vitale Indikation)"
							name="name"
							className="input-sm"
						/>
						<Input
							form={form}
							label="Beschreibung"
							placeholder="zunehmende Atembeschwerden"
							name="description"
							className="input-sm"
						/>
						<ListInput
							className="input-sm"
							control={form.control}
							name="hpgMissionTypes"
							label="HPG Missions presets"
						/>
					</div>
				</div>

				<div className="card bg-base-200 col-span-6 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>
							{keyword && (
								<Button
									onClick={async () => {
										await deleteKeyword(keyword.id);
										redirect("/admin/keyword");
									}}
									className="btn btn-error"
								>
									Löschen
								</Button>
							)}
						</div>
					</div>
				</div>
			</form>
		</>
	);
};
