"use client";
import { useState } from "react";
import { Button, cn } from "@repo/shared-components";
import MDEditor from "@uiw/react-md-editor";
import { Check, RefreshCw } from "lucide-react";
import { Changelog } from "@repo/db";

export const ChangelogModal = ({
	latestChangelog,
	isOpen,
	onClose,
}: {
	latestChangelog: Changelog;
	isOpen: boolean;
	onClose: () => void;
}) => {
	return (
		<dialog open={isOpen} 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={onClose}
					>
						✕
					</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 && (
						<img
							src={latestChangelog.previewImage}
							alt="Preview"
							className="mt-4 h-auto w-full object-cover"
						/>
					)}
				</div>

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

				<div className="modal-action">
					<Button className="btn btn-info btn-outline" onClick={onClose}>
						<Check size={20} />
						gelesen
					</Button>
				</div>
			</div>
			<label className="modal-backdrop" htmlFor="changelogModalToggle">
				Close
			</label>
		</dialog>
	);
};

export const ChangelogModalBtn = ({
	latestChangelog,
	autoOpen,
	onClose,
	className = "",
	hideIcon = false,
}: {
	latestChangelog: Changelog | null | undefined;
	autoOpen: boolean;
	onClose?: () => void;
	className?: string;
	hideIcon?: boolean;
}) => {
	const [isOpen, setIsOpen] = useState(autoOpen);

	if (!latestChangelog) return null;

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