"use client";
import { useEffect } from "react";
import {
	CheckCircledIcon,
	CalendarIcon,
	EnterIcon,
} from "@radix-ui/react-icons";
import { Event, EventAppointment, Participant, User } from "@repo/db";
import { cn } from "../../../../helper/cn";
import { addParticipant, inscribeToMoodleCourse } from "../actions";
import { useSession } from "next-auth/react";

interface ModalBtnProps {
	title: string;
	event: Event;
	dates: EventAppointment[];
	participant?: Participant;
	user: User;
	modalId: string;
}

const ModalBtn = ({
	title,
	dates,
	modalId,
	participant,
	event,
	user,
}: ModalBtnProps) => {
	useEffect(() => {
		const modal = document.getElementById(modalId) as HTMLDialogElement;
		const handleOpen = () => {
			document.body.classList.add("modal-open");
		};
		const handleClose = () => {
			document.body.classList.remove("modal-open");
		};
		modal?.addEventListener("show", handleOpen);
		modal?.addEventListener("close", handleClose);
		return () => {
			modal?.removeEventListener("show", handleOpen);
			modal?.removeEventListener("close", handleClose);
		};
	}, [modalId]);

	const openModal = () => {
		const modal = document.getElementById(modalId) as HTMLDialogElement;
		document.body.classList.add("modal-open");
		modal?.showModal();
	};

	const closeModal = () => {
		const modal = document.getElementById(modalId) as HTMLDialogElement;
		document.body.classList.remove("modal-open");
		modal?.close();
	};

	return (
		<>
			<button
				className={cn(
					"btn btn-outline btn-info btn-wide",
					event.type === "OBLIGATED_COURSE" && "btn-secondary",
				)}
				onClick={openModal}
			>
				<EnterIcon /> Anmelden
			</button>
			<dialog id={modalId} className="modal">
				<div className="modal-box">
					<h3 className="font-bold text-lg">{title}</h3>
					{event.hasPresenceEvents && (
						<div>
							<div className="flex items-center gap-2 justify-center">
								<CalendarIcon />
								<select className="select w-full max-w-xs" defaultValue={0}>
									<option disabled>Bitte wähle einen Termin aus</option>
									{dates.map((date, index) => (
										<option key={index}>
											{date.appointmentDate.toLocaleString()}
										</option>
									))}
								</select>
							</div>
							<p className="mt-3 text-center">
								Bitte finde dich an diesem Termin in unserem Discord ein.
							</p>
						</div>
					)}
					{event.finisherMoodleCourseId && (
						<MoodleCourseIndicator
							user={user}
							moodleCourseId={event.finisherMoodleCourseId}
							completed={participant?.finisherMoodleCurseCompleted}
							eventId={event.id}
						/>
					)}
					<div className="modal-action flex justify-between">
						<button className="btn" onClick={closeModal}>
							Abbrechen
						</button>
						{event.hasPresenceEvents && (
							<button className="btn btn-info btn-outline btn-wide">
								<EnterIcon /> Anmelden
							</button>
						)}
					</div>
				</div>
				<button className="modal-backdrop" onClick={closeModal}>
					Abbrechen
				</button>
			</dialog>
		</>
	);
};

export default ModalBtn;

const MoodleCourseIndicator = ({
	completed,
	moodleCourseId,
	eventId,
	user,
}: {
	completed?: boolean;
	moodleCourseId: string;
	eventId: number;
	user: User;
}) => {
	const courseUrl = `${process.env.NEXT_PUBLIC_MOODLE_URL}/course/view.php?id=${moodleCourseId}`;
	if (completed)
		return (
			<p className="py-4 flex items-center gap-2 justify-center">
				<CheckCircledIcon className="text-success" />
				Moodle Kurs abgeschlossen
			</p>
		);
	return (
		<p className="py-4 flex items-center gap-2 justify-center">
			Moodle-Kurs Benötigt
			<button
				className="btn btn-xs btn-info ml-2"
				onClick={async () => {
					await addParticipant(eventId, user.id);

					if (user.moodleId) {
						await inscribeToMoodleCourse(moodleCourseId, user.moodleId);
					}
					window.open(courseUrl, "_blank");
				}}
			>
				Zum Moodle Kurs
			</button>
		</p>
	);
};
