/**
 * Copyright (c) 2023-present Pi Dash Software, Inc. and contributors
 * SPDX-License-Identifier: AGPL-3.0-only
 * See the LICENSE file for details.
 */

import type { Dispatch, SetStateAction } from "react";
import { Fragment } from "react";
import { observer } from "mobx-react";
import { Clock } from "lucide-react";
import { Popover, Transition } from "@headlessui/react";
// pi dash imports
import { NOTIFICATION_SNOOZE_OPTIONS } from "@pi-dash/constants";
import { useTranslation } from "@pi-dash/i18n";
import { TOAST_TYPE, setToast } from "@pi-dash/propel/toast";
import { Tooltip } from "@pi-dash/propel/tooltip";
import { cn } from "@pi-dash/utils";
// hooks
import { useWorkspaceNotifications } from "@/hooks/store/notifications";
import { usePlatformOS } from "@/hooks/use-platform-os";
// store
import type { INotification } from "@/store/notifications/notification";
// local imports
import { NotificationSnoozeModal } from "./modal";

type TNotificationItemSnoozeOption = {
  workspaceSlug: string;
  notification: INotification;
  setIsSnoozeStateModalOpen: Dispatch<SetStateAction<boolean>>;
  customSnoozeModal: boolean;
  setCustomSnoozeModal: Dispatch<SetStateAction<boolean>>;
};

export const NotificationItemSnoozeOption = observer(function NotificationItemSnoozeOption(
  props: TNotificationItemSnoozeOption
) {
  const { workspaceSlug, notification, setIsSnoozeStateModalOpen, customSnoozeModal, setCustomSnoozeModal } = props;
  // hooks
  const { isMobile } = usePlatformOS();
  const {} = useWorkspaceNotifications();
  const { t } = useTranslation();
  const { asJson: data, snoozeNotification, unSnoozeNotification } = notification;

  const handleNotificationSnoozeDate = async (snoozeTill: Date | undefined) => {
    if (snoozeTill) {
      try {
        await snoozeNotification(workspaceSlug, snoozeTill);
        setToast({
          title: `${t("Success!")}!`,
          message: t("Notification snoozed"),
          type: TOAST_TYPE.SUCCESS,
        });
      } catch (e) {
        console.error(e);
      }
    } else {
      try {
        await unSnoozeNotification(workspaceSlug);
        setToast({
          title: `${t("Success!")}!`,
          message: t("Notification unsnoozed"),
          type: TOAST_TYPE.SUCCESS,
        });
      } catch (e) {
        console.error(e);
      }
    }

    setCustomSnoozeModal(false);
    setIsSnoozeStateModalOpen(false);
  };

  const handleDropdownSelect = (snoozeDate: Date | "un-snooze" | undefined) => {
    if (snoozeDate === "un-snooze") {
      handleNotificationSnoozeDate(undefined);
      return;
    }
    if (snoozeDate) {
      handleNotificationSnoozeDate(snoozeDate);
    } else {
      setCustomSnoozeModal(true);
    }
  };

  return (
    <>
      <NotificationSnoozeModal
        isOpen={customSnoozeModal}
        onClose={() => setCustomSnoozeModal(false)}
        onSubmit={handleNotificationSnoozeDate}
      />
      <Popover className="relative">
        {({ open }) => {
          if (open) setIsSnoozeStateModalOpen(true);
          else setIsSnoozeStateModalOpen(false);

          return (
            <>
              <Tooltip
                tooltipContent={
                  data.snoozed_till ? t("Un snooze") : t("Snooze")
                }
                isMobile={isMobile}
              >
                <Popover.Button
                  className={cn(
                    "relative flex h-5 w-5 flex-shrink-0 items-center justify-center rounded-xs bg-layer-1 outline-none hover:bg-surface-2",
                    open ? "bg-layer-1" : ""
                  )}
                >
                  <Clock className="h-3 w-3 text-tertiary" />
                </Popover.Button>
              </Tooltip>

              <Transition
                as={Fragment}
                enter="transition ease-out duration-200"
                enterFrom="opacity-0 translate-y-1"
                enterTo="opacity-100 translate-y-0"
                leave="transition ease-in duration-150"
                leaveFrom="opacity-100 translate-y-0"
                leaveTo="opacity-0 translate-y-1"
              >
                <Popover.Panel className="absolute right-0 z-10 mt-2 min-w-44 select-none">
                  <div className="space-y-1 rounded-md border border-subtle bg-surface-1 p-2">
                    {data.snoozed_till && (
                      <button
                        className="w-full cursor-pointer rounded-xs p-1 px-2 text-left text-body-xs-medium text-secondary transition-all hover:bg-layer-1"
                        onClick={(e) => {
                          e.preventDefault();
                          e.stopPropagation();
                          handleDropdownSelect("un-snooze");
                        }}
                      >
                        <div>{t("Un snooze")}</div>
                      </button>
                    )}

                    {NOTIFICATION_SNOOZE_OPTIONS.map((option) => (
                      <button
                        key={option.key}
                        className="w-full cursor-pointer rounded-xs p-1 px-2 text-left text-body-xs-medium text-secondary transition-all hover:bg-layer-1"
                        onClick={(e) => {
                          e.preventDefault();
                          e.stopPropagation();
                          handleDropdownSelect(option.value != undefined ? option.value() : option.value);
                        }}
                      >
                        <div>{t(option?.i18n_label)}</div>
                      </button>
                    ))}
                  </div>
                </Popover.Panel>
              </Transition>
            </>
          );
        }}
      </Popover>
    </>
  );
});
