"use client";
import { useState } from "react";
import Image from "next/image";
import { Button } from "@repo/shared-components";
import MDEditor from "@uiw/react-md-editor";
import { RefreshCw } from "lucide-react";
import { updateChangelogAck } from "./ChangelogActions";

export const ChangelogModal = ({
	latestChangelog,
	isOpen,
	onClose,
}: {
	latestChangelog: { title: string; text: string; previewImage: string } | null;
	isOpen: boolean;
	onClose: () => void;
}) => {
	if (!isOpen || !latestChangelog) return null;

	const handleClose = async () => {
		onClose();
		await updateChangelogAck();
	};

	return (
		<div>
			<input
				type="checkbox"
				id="changelogModalToggle"
				className="modal-toggle"
				onChange={handleClose}
			/>
			<dialog open className="modal p-4">
				<div className="modal-box max-h-11/12 w-11/12 max-w-2xl overflow-y-auto">
					<form method="dialog">
						<button
							className="btn btn-sm btn-circle btn-ghost absolute right-3 top-3"
							onClick={handleClose}
						>
							✕
						</button>
					</form>
					<h3 className="flex items-center gap-2 text-lg font-bold">
						<span className="text-primary">{latestChangelog.title}</span> ist nun Verfügbar!
					</h3>

					<div className="flex flex-col items-center">
						{latestChangelog.previewImage && (
							<Image
								src={latestChangelog.previewImage}
								alt="Preview"
								width={800}
								height={400}
								className="mt-4 h-auto w-full object-cover"
							/>
						)}
					</div>

					<div className="text-base-content/80 mb-2 mt-4 text-left">
						<MDEditor.Markdown
							source={latestChangelog.text}
							style={{
								backgroundColor: "transparent",
							}}
						/>
					</div>

					<div className="modal-action">
						<Button className="btn btn-info btn-outline" onClick={handleClose}>
							Weiter zum HUB
						</Button>
					</div>
				</div>
				<label className="modal-backdrop" htmlFor="changelogModalToggle">
					Close
				</label>
			</dialog>
		</div>
	);
};

export const ChangelogBtn = ({
	latestChangelog,
}: {
	latestChangelog: { title: string; text: string; previewImage: string } | null;
}) => {
	const [isOpen, setIsOpen] = useState(false);

	if (!latestChangelog) return null;

	return (
		<>
			<a
				href="#!"
				className="hover:text-primary flex items-center gap-1"
				onClick={() => setIsOpen(true)}
			>
				<RefreshCw size={12} /> {latestChangelog.title}
			</a>
			<ChangelogModal
				latestChangelog={latestChangelog}
				isOpen={isOpen}
				onClose={() => setIsOpen(false)}
			/>
		</>
	);
};

export const OpenChangelogOnPageload = ({
	latestChangelog,
}: {
	latestChangelog: { title: string; text: string; previewImage: string } | null;
}) => {
	const [isOpen, setIsOpen] = useState(true);

	if (!latestChangelog) return null;

	return (
		<>
			<ChangelogModal
				latestChangelog={latestChangelog}
				isOpen={isOpen}
				onClose={() => setIsOpen(false)}
			/>
		</>
	);
};
