"use client";
import { editPenalty } from "(app)/admin/penalty/actions";
import { zodResolver } from "@hookform/resolvers/zod";
import { Penalty, Report, User } from "@repo/db";
import { PenaltyOptionalDefaults, PenaltyOptionalDefaultsSchema } from "@repo/db/zod";
import { Button } from "_components/ui/Button";
import { Switch } from "_components/ui/Switch";
import { useForm } from "react-hook-form";
import toast from "react-hot-toast";

export const ReasonForm = ({
	penalty,
	userReports: suerReportsOfDay,
}: {
	penalty: Penalty;
	userReports: (Report & { Reported: User })[];
}) => {
	const form = useForm<PenaltyOptionalDefaults>({
		defaultValues: penalty,
		resolver: zodResolver(PenaltyOptionalDefaultsSchema),
	});
	const isSubmitting = form.formState.isSubmitting;

	return (
		<>
			<form
				className="card-body"
				onSubmit={form.handleSubmit(async (penalty) => {
					if (!penalty.id) return;
					const newPenalty = await editPenalty(penalty.id, penalty);
					toast.success("Daten gespeichert");
					form.reset(newPenalty);
				})}
			>
				<h2 className="card-title">Begründung</h2>

				<div>
					<textarea className="textarea textarea-bordered w-full" {...form.register("reason")} />
					{form.formState.errors.reason && (
						<p className="text-error">{form.formState.errors.reason.message}</p>
					)}
				</div>
				<div
					className="tooltip tooltip-bottom"
					data-tip="Wenn diese Option aktiviert ist, wird die Strafe so behandelt, als wäre sie abgelaufen."
				>
					<Switch
						form={form}
						name="suspended"
						label="Strafe aussetzen"
						className={form.watch("suspended") ? "toggle-error text-error" : ""}
					/>
				</div>
				<fieldset className="fieldset">
					<legend className="fieldset-legend text-left">Zugeordneter Report</legend>
					<select
						className="select select-bordered w-full"
						{...form.register("reportId", {
							valueAsNumber: true,
						})}
					>
						<option value="">Kein Report</option>
						{suerReportsOfDay.map((report) => (
							<option key={report.id} value={report.id}>
								Report #{report.id} - {report.reportedUserRole} - {report.Reported.firstname}{" "}
								{report.Reported.lastname} ({report.Reported.publicId})
							</option>
						))}
					</select>
					<p className="label">
						Bitte währe ein Report aus damit diese Maßname bei dem Report angezeigt wird
					</p>
				</fieldset>
				<Button
					className="btn-primary"
					type="submit"
					disabled={!form.formState.isDirty}
					isLoading={isSubmitting}
				>
					Speichern
				</Button>
			</form>
		</>
	);
};
