"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { Notam } from "@repo/db";
import {
	NotamOptionalDefaults,
	NotamOptionalDefaultsSchema,
} from "@repo/db/zod";
import { useForm } from "react-hook-form";
import { addMessage, disableMessage } from "../action";
import { useState } from "react";

export const MessageForm = ({ message }: { message?: Notam }) => {
	const [isSubmitting, setIsSubmitting] = useState(false);

	const getDefaultShowUntilDate = () => {
		const date = new Date();
		date.setDate(date.getDate() + 5);
		return date;
	};

	const disableMessageClient = async () => {
		disableMessage();
	};

	const form = useForm<NotamOptionalDefaults>({
		resolver: zodResolver(NotamOptionalDefaultsSchema),
		defaultValues: {
			message: message?.message,
			color: message?.color,
			isMainMsg: true,
			active: true,
			showUntil: getDefaultShowUntilDate(),
		},
	});

	return (
		<form
			onSubmit={form.handleSubmit(async (values) => {
				setIsSubmitting(true);
				try {
					const msg = await addMessage(values);
				} catch (error) {
					setIsSubmitting(false);
					console.error("Failed to add message", error);
				}
			})}
			className="grid grid-cols-6 gap-3"
		>
			<label className="floating-label col-span-6">
				<span>Globale Service Nachricht</span>
				<input
					type="text"
					placeholder="Globale Service Nachricht"
					className="input input-md w-full mb-2"
					{...form.register("message")}
				/>
			</label>
			<div className="gap-2 flex justify-between col-span-6">
				<div className="content-center">
					<input
						type="radio"
						value="INFO"
						{...form.register("color")}
						className="radio radio-info ml-2 mr-2"
					/>
					<span>Info</span>
					<input
						type="radio"
						value="SUCCESS"
						{...form.register("color")}
						className="radio radio-success ml-2 mr-2"
					/>
					<span>Success</span>
					<input
						type="radio"
						value="WARNING"
						{...form.register("color")}
						className="radio radio-warning ml-2 mr-2"
					/>
					<span>Warning</span>
					<input
						type="radio"
						value="ERROR"
						{...form.register("color")}
						className="radio radio-error ml-2 mr-2"
					/>
					<span>Error</span>
				</div>
				<div>
					<button
						type="submit"
						className="btn btn-soft mr-2"
						onClick={disableMessageClient}
					>
						Aktuelle Nachricht deaktivieren
					</button>
					<button
						type="submit"
						className="btn btn-primary"
						disabled={isSubmitting}
					>
						Speichern
					</button>
				</div>
			</div>
		</form>
	);
};
