"use client"

import { useCallback } from "react"
import { useRouter } from "next/navigation"
import { buildMailPath } from "@/lib/mail-url"
import { useWsEventListener } from "@/lib/api/ws"
import type { WsEvent } from "@/lib/api/types"
import { apiClient } from "@/lib/api/client"
import type { ApiMessageFull } from "@/lib/api/types"
import { useMailSettingsStore } from "@/lib/stores/mail-settings-store"
import {
  isReplyOrMentionSubject,
  showDesktopNotification,
} from "@/lib/notifications/desktop-notifications"

function mailEventPayload(evt: WsEvent): { message_id: string; account_id: string } | null {
  const payload = evt.payload
  if (!payload || typeof payload !== "object" || !("message_id" in payload)) return null
  const messageId = String(payload.message_id ?? "")
  if (!messageId) return null
  return {
    message_id: messageId,
    account_id: String(payload.account_id ?? ""),
  }
}

export function MailNotificationsBridge() {
  const router = useRouter()
  const desktopNewMail = useMailSettingsStore((s) => s.desktopNewMail)
  const desktopMentions = useMailSettingsStore((s) => s.desktopMentions)
  const soundEnabled = useMailSettingsStore((s) => s.soundEnabled)

  const handleMailCreated = useCallback(
    async (evt: WsEvent) => {
      if (evt.type !== "mail.created") return
      if (!desktopNewMail && !desktopMentions) return

      const payload = mailEventPayload(evt)
      if (!payload) return

      let subject = "Nouveau message"
      let sender = ""
      try {
        const message = await apiClient.get<ApiMessageFull>(
          `/mail/messages/${payload.message_id}`
        )
        subject = message.subject?.trim() || subject
        sender = message.from?.[0]?.name || message.from?.[0]?.address || ""
      } catch {}

      const isMention = isReplyOrMentionSubject(subject)
      if (isMention && !desktopMentions) return
      if (!isMention && !desktopNewMail) return

      showDesktopNotification({
        title: subject,
        body: sender ? `De ${sender}` : undefined,
        tag: payload.message_id,
        playSound: soundEnabled,
        onClick: () => {
          router.push(
            buildMailPath({
              folderId: "inbox",
              inboxTab: "primary",
              page: 1,
              mailId: payload.message_id,
            })
          )
        },
      })
    },
    [desktopMentions, desktopNewMail, router, soundEnabled]
  )

  useWsEventListener(handleMailCreated)

  return null
}
