"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";
import { Cross } from "lucide-react";

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

const ModalBtn = ({
	title,
	dates,
	modalId,
	participant,
	selectedAppointments,
	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 canSelectDate =
		event.hasPresenceEvents &&
		!participant?.attended &&
		(selectedAppointments.length === 0 || participant?.appointmentCancelled);

	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>
							{canSelectDate && (
								<div className="flex items-center gap-2 justify-center">
									<CalendarIcon />
									{!!dates.length && (
										<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>
									)}
									{!dates.length && (
										<p className="text-center text-info">
											Keine Termine verfügbar
										</p>
									)}
								</div>
							)}
							{!!dates.length && (
								<p className="mt-3 text-center">
									Bitte finde dich an diesem Termin in unserem Discord ein.
								</p>
							)}
						</div>
					)}
					{event.finisherMoodleCourseId && (
						<MoodleCourseIndicator
							participant={participant}
							user={user}
							moodleCourseId={event.finisherMoodleCourseId}
							completed={participant?.finisherMoodleCurseCompleted}
							event={event}
						/>
					)}
					<div className="modal-action flex justify-between">
						<button className="btn" onClick={closeModal}>
							Abbrechen
						</button>
						{!!(event.hasPresenceEvents && dates.length) && (
							<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,
	event,
	participant,
	user,
}: {
	user: User;
	participant?: Participant;
	completed?: boolean;
	moodleCourseId: string;
	event: Event;
}) => {
	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>
		);
	if (!participant || (event.hasPresenceEvents && !participant?.attended))
		return (
			<p className="py-4 flex items-center gap-2 justify-center">
				<Cross className="text-error" />
				Teilnahme an Event erforderlich
			</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(event.id, user.id);

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