"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { ChangelogOptionalDefaultsSchema } from "@repo/db/zod";
import { useForm } from "react-hook-form";
import { Changelog } from "@repo/db";
import { FileText } from "lucide-react";
import { Input } from "../../../../_components/ui/Input";
import { useEffect, useState } from "react";
import { deleteChangelog, upsertChangelog } from "../action";
import { Button } from "../../../../_components/ui/Button";
import { redirect } from "next/navigation";
import dynamic from "next/dynamic";
import toast from "react-hot-toast";
import { cn } from "@repo/shared-components";

const MarkdownEditor = dynamic(() => import("@uiw/react-md-editor"), { ssr: false });

export const ChangelogForm = ({ changelog }: { changelog?: Changelog }) => {
	const form = useForm({
		resolver: zodResolver(ChangelogOptionalDefaultsSchema),
		defaultValues: {
			id: changelog?.id || undefined,
			title: changelog?.title || "",
			text: changelog?.text || "",
			previewImage: changelog?.previewImage || "", // Changed to accept a URL as a string
		},
	});
	const [skipUserUpdate, setSkipUserUpdate] = useState(false);
	const [markdownText, setMarkdownText] = useState(changelog?.text || "");
	const [imageError, setImageError] = useState(false);
	const [showImage, setShowImage] = useState(false);

	const isValidImageUrl = (url: string) => {
		if (!url) return false;
		try {
			const sanitizedUrl = url.trim(); // Remove leading/trailing spaces
			const parsedUrl = new URL(sanitizedUrl, window.location.origin);
			return parsedUrl.protocol === "http:" || parsedUrl.protocol === "https:";
		} catch (error) {
			console.error("Invalid URL provided:", url, error);
			return false;
		}
	};

	const previewImage = form.watch("previewImage") || "";

	useEffect(() => {
		if (!isValidImageUrl(previewImage)) {
			setImageError(true);
			setShowImage(false); // Ensure image is hidden if URL is invalid
		} else {
			setImageError(false); // Reset error when previewImage changes and is valid
		}
	}, [previewImage]);

	return (
		<>
			<form
				onSubmit={form.handleSubmit(async (values) => {
					await upsertChangelog(
						{
							...values,
							text: markdownText,
						},
						changelog?.id,
						{
							skipUserUpdate: skipUserUpdate,
						},
					);
					toast.success("Daten gespeichert");
					if (!changelog) redirect(`/admin/changelog`);
				})}
				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>
						<Input
							form={form}
							label="Titel"
							name="title"
							placeholder="Titel (vX.X.X)"
							className="input-sm"
						/>
						<Input
							form={form}
							label="Bild-URL"
							name="previewImage"
							className="input-sm"
							onChange={() => setShowImage(false)}
						/>
						<Button
							onClick={() => setShowImage(true)}
							type="button"
							className="btn btn-primary btn-outline mt-2"
						>
							Bildvorschau anzeigen
						</Button>
						{(() => {
							if (showImage && isValidImageUrl(previewImage) && !imageError) {
								return (
									// eslint-disable-next-line @next/next/no-img-element
									<img
										src={previewImage}
										alt="Preview"
										width={200}
										height={200}
										className="mt-4 max-h-48"
										onError={() => {
											setImageError(true);
											console.error("Failed to load image at URL:", previewImage);
										}}
									/>
								);
							} else if (imageError && showImage) {
								return <p className="text-error">Bild konnte nicht geladen werden</p>;
							}
						})()}
					</div>
				</div>

				<div className="card bg-base-200 col-span-6 shadow-xl">
					<div className="card-body">
						<h2 className="card-title">Beschreibung</h2>
						<MarkdownEditor
							value={markdownText}
							onChange={(value) => setMarkdownText(value || "")}
							className="min-h-96 w-full" // Increased height to make the editor bigger
						/>
					</div>
				</div>

				<div className="card bg-base-200 col-span-6 shadow-xl">
					{!changelog?.id && (
						<label className="label mx-6 mt-6 w-full cursor-pointer">
							<input
								type="checkbox"
								className={cn("toggle")}
								checked={skipUserUpdate}
								onChange={(e) => setSkipUserUpdate(e.target.checked)}
							/>
							<span className={cn("label-text w-full text-left")}>
								Kein Popup für Nutzer für dieses Update anzeigen
							</span>
						</label>
					)}
					<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>
							{changelog && (
								<Button
									onClick={async () => {
										await deleteChangelog(changelog.id);
										redirect("/admin/changelog");
									}}
									className="btn btn-error"
								>
									Löschen
								</Button>
							)}
						</div>
					</div>
				</div>
			</form>
		</>
	);
};
