"use client";
import { useEffect } from "react";
import {
  CheckCircledIcon,
  CalendarIcon,
  EnterIcon,
} from "@radix-ui/react-icons";

interface ModalBtnProps {
  title: string;
  dates: string[];
  modalId: string;
}

const ModalBtn = ({ title, dates, modalId }: 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="btn btn-outline btn-info btn-wide" onClick={openModal}>
        <EnterIcon /> Anmelden
      </button>
      <dialog id={modalId} className="modal">
        <div className="modal-box">
          <h3 className="font-bold text-lg">{title}</h3>
          <p className="py-4 flex items-center gap-2 justify-center">
            <CheckCircledIcon className="text-success" />
            Moodle Kurs abgeschlossen
          </p>
          <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}</option>
                ))}
              </select>
            </div>
            <p className="mt-3 text-center">
              Bitte finde dich an diesem Termin in unserem Discord ein.
            </p>
          </div>
          <div className="modal-action flex justify-between">
            <button className="btn" onClick={closeModal}>
              Abbrechen
            </button>
            <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;
