"use client";

import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";

import { useLanguageStore } from "@/store/languageStore";
import {
  buildGoogleCalendarUrl,
  buildIcsContent,
  resolveSchedule,
  type CalendarPayload,
} from "./icsCalendar";

const MENU_ITEM_CLASS =
  "w-full whitespace-nowrap px-4 py-2.5 text-start text-base font-medium text-primary-5 transition-colors hover:bg-primary-5/5 2xl:text-lg";

/**
 * "Add to calendar" on an event or opportunity.
 *
 * Two destinations, because they are not interchangeable: Google Calendar is a
 * template link that saves the entry into the signed-in Google account, while
 * the .ics download is what Apple Calendar and Outlook take. A downloaded .ics
 * puts nothing into Google Calendar without a manual import, so offering only
 * that was not the same feature.
 */
export default function AddToCalendar({
  payload,
  className,
}: {
  payload?: CalendarPayload;
  className?: string;
}) {
  const { t } = useTranslation();
  const selectedLanguage = useLanguageStore((s) => s.language);
  const [open, setOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;

    const onPointerDown = (event: MouseEvent | TouchEvent) => {
      if (!containerRef.current?.contains(event.target as Node)) {
        setOpen(false);
      }
    };
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") setOpen(false);
    };

    document.addEventListener("mousedown", onPointerDown);
    document.addEventListener("touchstart", onPointerDown);
    document.addEventListener("keydown", onKeyDown);
    return () => {
      document.removeEventListener("mousedown", onPointerDown);
      document.removeEventListener("touchstart", onPointerDown);
      document.removeEventListener("keydown", onKeyDown);
    };
  }, [open]);

  if (!payload?.start_date) return null;

  const title =
    (selectedLanguage === "ar" ? payload.title_ar : payload.title_en) || "";
  const location =
    (selectedLanguage === "ar" ? payload.location_ar : payload.location_en) ||
    "";

  const handleGoogleCalendar = () => {
    setOpen(false);
    const schedule = resolveSchedule(payload);
    if (!schedule) {
      toast.error(t("COMMON.CALENDAR_ERROR_MESSAGE"));
      return;
    }

    window.open(
      buildGoogleCalendarUrl(
        schedule,
        title,
        location,
        payload.details_url ?? window.location.href,
      ),
      "_blank",
      "noopener,noreferrer",
    );
  };

  const handleDownloadICS = async () => {
    setOpen(false);
    const schedule = resolveSchedule(payload);
    if (!schedule) {
      toast.error(t("COMMON.CALENDAR_ERROR_MESSAGE"));
      return;
    }

    const icsContent = buildIcsContent(schedule, title, location);
    const filename = `${title.replace(/\s+/g, "_") || "event"}.ics`;

    const url = URL.createObjectURL(
      new Blob([icsContent], { type: "text/calendar;charset=utf-8" }),
    );
    const link = document.createElement("a");
    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    toast.success(t("COMMON.CALENDAR_TOAST_MESSAGE"));
  };

  return (
    <div
      ref={containerRef}
      className={`relative inline-block ${className || ""}`}
    >
      <button
        type="button"
        aria-haspopup="menu"
        aria-expanded={open}
        className="border-b border-primary-5 text-base font-bold text-primary-5 lg:text-base 2xl:text-xl xsmall:text-[13px]"
        onClick={() => setOpen((value) => !value)}
      >
        {t("COMMON.ADD_TO_CALENDAR")}
      </button>

      {open && (
        // `start-0` rather than `left-0`: the menu has to hang off the same
        // edge as the trigger in both directions.
        <div
          role="menu"
          className="absolute top-[calc(100%+8px)] z-20 start-0 overflow-hidden rounded-xl border border-primary-5/20 bg-white py-1 shadow-[0px_4px_10px_rgba(0,0,0,0.15)]"
        >
          <button
            type="button"
            role="menuitem"
            className={MENU_ITEM_CLASS}
            onClick={handleGoogleCalendar}
          >
            {t("COMMON.GOOGLE_CALENDAR")}
          </button>
          <button
            type="button"
            role="menuitem"
            className={MENU_ITEM_CLASS}
            onClick={handleDownloadICS}
          >
            <span className="block">{t("COMMON.DOWNLOAD_ICS")}</span>
            <span className="mt-1 block text-xs font-normal text-secondary-102">
              {t("COMMON.DEVICE_CALENDAR_HINT")}
            </span>
          </button>
        </div>
      )}
    </div>
  );
}
