import { useAtomValue, useSetAtom } from 'jotai';
import React, { ReactNode, useCallback, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  MatrixEvent,
  Room,
  RoomEvent,
  RoomEventHandlerMap,
  Thread,
  ThreadEvent,
} from 'matrix-js-sdk';
import { focusAssistActiveAtom } from '../../state/focusAssist';
import { roomToUnreadAtom, unreadEqual, unreadInfoToUnread } from '../../state/room/roomToUnread';
import LogoSVG from '../../../../public/res/lotus.png';
import LogoUnreadSVG from '../../../../public/res/lotus-unread.png';
import LogoHighlightSVG from '../../../../public/res/lotus-highlight.png';
import NotificationSound from '../../../../public/sound/notification.ogg';
import InviteSound from '../../../../public/sound/invite.ogg';
import { notificationPermission, setFavicon, showOsNotification } from '../../utils/dom';
import { NOTIFICATION_SOUND_MAP } from '../../utils/notificationSounds';
import { useSetting } from '../../state/hooks/settings';
import { settingsAtom } from '../../state/settings';
import { allInvitesAtom } from '../../state/room-list/inviteList';
import { usePreviousValue } from '../../hooks/usePreviousValue';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { getDirectRoomPath, getHomeRoomPath, getInboxInvitesPath } from '../pathUtils';
import { mDirectAtom } from '../../state/mDirectList';
import {
  getMemberDisplayName,
  getNotificationType,
  getUnreadInfo,
  isNotificationEvent,
} from '../../utils/room';
import { NotificationType, UnreadInfo } from '../../../types/matrix/room';
import { getMxIdLocalPart, mxcUrlToHttp } from '../../utils/matrix';
import { useSelectedRoom } from '../../hooks/router/useSelectedRoom';
import { useInboxNotificationsSelected } from '../../hooks/router/useInbox';
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
import { usePresenceUpdater } from '../../hooks/usePresenceUpdater';
import { useDeepLinkNavigate } from '../../hooks/useDeepLinkNavigate';
import { toastQueueAtom } from '../../state/toast';
import { useReminders } from '../../hooks/useReminders';
import { useTauriUpdater } from '../../hooks/useTauriUpdater';
import { TauriDesktopFeatures } from '../../components/TauriDesktopFeatures';
import { KeyboardShortcutsDialog, useKeyboardShortcutsTrigger } from '../../features/shortcuts';
import { useRoomsListener } from '../../hooks/useRoomsListener';
import { threadNotificationsAtom } from '../../state/threadNotifications';
import { roomIdToActiveThreadIdAtomFamily } from '../../state/room/thread';
import {
  getThreadNotificationMode,
  shouldNotifyThreadReply,
  THREAD_NOTIFICATIONS_FALLBACK_BEHAVIOR,
} from '../../utils/threadNotifications';

function isInQuietHours(start: string, end: string): boolean {
  const now = new Date();
  const [sh, sm] = start.split(':').map(Number);
  const [eh, em] = end.split(':').map(Number);
  const cur = now.getHours() * 60 + now.getMinutes();
  const s = sh! * 60 + (sm ?? 0);
  const e = eh! * 60 + (em ?? 0);
  // start===end means zero-length window → treat as disabled (no quiet hours)
  if (s === e) return false;
  return s < e ? cur >= s && cur < e : cur >= s || cur < e;
}

function SystemEmojiFeature() {
  const [twitterEmoji] = useSetting(settingsAtom, 'twitterEmoji');

  if (twitterEmoji) {
    document.documentElement.style.setProperty('--font-emoji', 'Twemoji');
  } else {
    document.documentElement.style.setProperty('--font-emoji', 'Twemoji_DISABLED');
  }

  return null;
}

function PageZoomFeature() {
  const [pageZoom] = useSetting(settingsAtom, 'pageZoom');

  if (pageZoom === 100) {
    document.documentElement.style.removeProperty('font-size');
  } else {
    document.documentElement.style.setProperty('font-size', `calc(1em * ${pageZoom / 100})`);
  }

  return null;
}

function FaviconUpdater() {
  const roomToUnread = useAtomValue(roomToUnreadAtom);

  useEffect(() => {
    let totalNotif = 0;
    let totalHighlight = 0;
    roomToUnread.forEach((unread) => {
      totalNotif += unread.total;
      totalHighlight += unread.highlight;
    });

    if (totalNotif > 0) {
      setFavicon(totalHighlight > 0 ? LogoHighlightSVG : LogoUnreadSVG);
    } else {
      setFavicon(LogoSVG);
    }

    if (totalHighlight > 0) {
      document.title = `(${totalHighlight}) Lotus Chat`;
    } else if (totalNotif > 0) {
      document.title = `· Lotus Chat`;
    } else {
      document.title = 'Lotus Chat';
    }
  }, [roomToUnread]);

  return null;
}

function InviteNotifications() {
  const audioRef = useRef<HTMLAudioElement>(null);
  const invites = useAtomValue(allInvitesAtom);
  const perviousInviteLen = usePreviousValue(invites.length, 0);
  const mx = useMatrixClient();

  const navigate = useNavigate();
  const [showNotifications] = useSetting(settingsAtom, 'showNotifications');
  const [notificationSound] = useSetting(settingsAtom, 'isNotificationSounds');
  const [quietHoursEnabled] = useSetting(settingsAtom, 'quietHoursEnabled');
  const focusAssistActive = useAtomValue(focusAssistActiveAtom);
  const [quietHoursStart] = useSetting(settingsAtom, 'quietHoursStart');
  const [quietHoursEnd] = useSetting(settingsAtom, 'quietHoursEnd');
  const [inviteSoundId] = useSetting(settingsAtom, 'inviteSoundId');
  const setToast = useSetAtom(toastQueueAtom);

  const soundSrc =
    inviteSoundId !== 'none' ? (NOTIFICATION_SOUND_MAP[inviteSoundId] ?? InviteSound) : null;

  useEffect(() => {
    const el = audioRef.current;
    if (!el) return;
    const source = el.querySelector('source');
    if (source && soundSrc) {
      source.src = soundSrc;
      el.load();
    }
  }, [soundSrc]);

  const notify = useCallback(
    (count: number) => {
      if (document.hasFocus()) {
        setToast({
          id: `invite-${Date.now()}`,
          displayName: 'Invitation',
          body: `You have ${count} new invitation request.`,
          roomName: 'Invites',
          roomId: '',
          hashPath: getInboxInvitesPath(),
        });
        return;
      }

      const invitesPath = getInboxInvitesPath();
      showOsNotification(
        'Invitation',
        {
          icon: LogoSVG,
          badge: LogoSVG,
          body: `You have ${count} new invitation request.`,
          silent: true,
          tag: 'lotus-invites',
          data: { path: invitesPath },
        },
        () => {
          if (!window.closed) navigate(invitesPath);
        },
      );
    },
    [navigate, setToast],
  );

  const playSound = useCallback(() => {
    const audioElement = audioRef.current;
    audioElement?.play();
  }, []);

  useEffect(() => {
    if (invites.length > perviousInviteLen && mx.getSyncState() === 'SYNCING') {
      const quietActive =
        focusAssistActive || (quietHoursEnabled && isInQuietHours(quietHoursStart, quietHoursEnd));
      if (!quietActive) {
        if (showNotifications && notificationPermission('granted')) {
          notify(invites.length - perviousInviteLen);
        }

        if (notificationSound && inviteSoundId !== 'none') {
          playSound();
        }
      }
    }
  }, [
    mx,
    invites,
    perviousInviteLen,
    showNotifications,
    notificationSound,
    notify,
    playSound,
    quietHoursEnabled,
    quietHoursStart,
    quietHoursEnd,
    focusAssistActive,
    inviteSoundId,
  ]);

  return (
    <audio ref={audioRef} style={{ display: 'none' }} aria-hidden="true">
      <source src={soundSrc ?? InviteSound} type="audio/ogg" />
    </audio>
  );
}

function PresenceUpdater() {
  usePresenceUpdater();
  return null;
}

function MessageNotifications() {
  const audioRef = useRef<HTMLAudioElement>(null);
  const unreadCacheRef = useRef<Map<string, UnreadInfo>>(new Map());
  // Per-thread dedupe: threadId -> last notified eventId.
  const lastNotifiedThreadRef = useRef<Map<string, string>>(new Map());
  const mx = useMatrixClient();
  const useAuthentication = useMediaAuthentication();
  const [showNotifications] = useSetting(settingsAtom, 'showNotifications');
  const [notificationSound] = useSetting(settingsAtom, 'isNotificationSounds');
  const [quietHoursEnabled] = useSetting(settingsAtom, 'quietHoursEnabled');
  const focusAssistActive = useAtomValue(focusAssistActiveAtom);
  const [quietHoursStart] = useSetting(settingsAtom, 'quietHoursStart');
  const [quietHoursEnd] = useSetting(settingsAtom, 'quietHoursEnd');
  const [messageSoundId] = useSetting(settingsAtom, 'messageSoundId');
  const setToast = useSetAtom(toastQueueAtom);
  const mDirects = useAtomValue(mDirectAtom);

  const soundSrc =
    messageSoundId !== 'none'
      ? (NOTIFICATION_SOUND_MAP[messageSoundId] ?? NotificationSound)
      : null;

  useEffect(() => {
    const el = audioRef.current;
    if (!el) return;
    const source = el.querySelector('source');
    if (source && soundSrc) {
      source.src = soundSrc;
      el.load();
    }
  }, [soundSrc]);

  const navigate = useNavigate();
  const notificationSelected = useInboxNotificationsSelected();
  const selectedRoomId = useSelectedRoom();
  const threadPrefs = useAtomValue(threadNotificationsAtom);
  const activeThreadId = useAtomValue(roomIdToActiveThreadIdAtomFamily(selectedRoomId ?? ''));

  const notify = useCallback(
    ({
      roomName,
      roomAvatar,
      username,
      roomId,
      eventId,
      body,
      encrypted,
      threadId,
    }: {
      roomName: string;
      roomAvatar?: string;
      username: string;
      roomId: string;
      eventId: string;
      body?: string;
      encrypted?: boolean;
      threadId?: string;
    }) => {
      const roomPath = mDirects.has(roomId)
        ? getDirectRoomPath(roomId, eventId)
        : getHomeRoomPath(roomId, eventId);

      if (document.hasFocus()) {
        setToast({
          id: `${roomId}-${eventId}-${Date.now()}`,
          avatarUrl: roomAvatar,
          displayName: username,
          body: (body ?? '').slice(0, 80),
          roomName,
          roomId,
          hashPath: roomPath,
        });
        return;
      }

      // N109: the OS notification subsystem fetches icon/badge OUTSIDE the page,
      // so the SW can't inject auth headers and authenticated-media URLs 401.
      // Use the static app logo (as invite notifications already do).
      // N106: never put decrypted E2EE plaintext into the OS notification (it
      // persists in the notification center / lock screen / is readable by other
      // apps). For encrypted rooms show only the sender; the in-page toast above
      // still shows the preview while the user is actively looking at the screen.
      showOsNotification(
        roomName,
        {
          icon: LogoSVG,
          badge: LogoSVG,
          body: !encrypted && body ? `${username}: ${body}`.slice(0, 120) : username,
          silent: true,
          // Coalesce repeated notifications for the same room (replaces the old
          // manual notifRef.close() dedup, which a SW notification can't hold).
          // For thread replies widen the tag to room:thread so each thread
          // coalesces independently instead of clobbering the room's bucket.
          tag: threadId ? `${roomId}:${threadId}` : roomId,
          data: { path: roomPath },
        },
        () => {
          window.focus();
          navigate(roomPath);
        },
      );
    },
    [navigate, setToast, mDirects],
  );

  // N105: when a service-worker-owned notification is clicked, the SW focuses
  // this tab and forwards the target path here so we can route to it (works even
  // when the click happened while the tab was in the background / reopened).
  useEffect(() => {
    if (!('serviceWorker' in navigator)) return undefined;
    const onMessage = (event: MessageEvent) => {
      const data = event.data ?? {};
      if (data.type === 'notificationClick' && typeof data.path === 'string') {
        navigate(data.path);
      }
    };
    navigator.serviceWorker.addEventListener('message', onMessage);
    return () => navigator.serviceWorker.removeEventListener('message', onMessage);
  }, [navigate]);

  const playSound = useCallback(() => {
    const audioElement = audioRef.current;
    audioElement?.play();
  }, []);

  // Shared delivery tail for both the main timeline and per-thread paths:
  // room-level unread dedup → avatar resolution → OS/toast notify → sound, all
  // behind the quiet-hours / focus-assist gate. `threadId` (when set) widens the
  // OS coalescing tag so each thread notifies independently; the click path
  // stays the room path (RoomTimeline deep-links thread events into the panel).
  const deliverNotification = useCallback(
    (room: Room, mEvent: MatrixEvent, threadId?: string) => {
      const sender = mEvent.getSender();
      const eventId = mEvent.getId();
      if (!sender || !eventId) return;

      const unreadInfo = getUnreadInfo(room);
      const cachedUnreadInfo = unreadCacheRef.current.get(room.roomId);
      unreadCacheRef.current.set(room.roomId, unreadInfo);

      if (unreadInfo.total === 0) return;
      if (
        cachedUnreadInfo &&
        unreadEqual(unreadInfoToUnread(cachedUnreadInfo), unreadInfoToUnread(unreadInfo))
      ) {
        return;
      }

      const quietActive =
        focusAssistActive || (quietHoursEnabled && isInQuietHours(quietHoursStart, quietHoursEnd));
      if (quietActive) return;

      if (showNotifications && notificationPermission('granted')) {
        const avatarMxc =
          room.getAvatarFallbackMember()?.getMxcAvatarUrl() ?? room.getMxcAvatarUrl();
        notify({
          roomName: room.name ?? 'Unknown',
          roomAvatar: avatarMxc
            ? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined)
            : undefined,
          username: getMemberDisplayName(room, sender) ?? getMxIdLocalPart(sender) ?? sender,
          roomId: room.roomId,
          eventId,
          body: (mEvent.getContent().body as string | undefined) ?? '',
          encrypted: room.hasEncryptionStateEvent(),
          threadId,
        });
      }

      if (notificationSound && messageSoundId !== 'none') {
        playSound();
      }
    },
    [
      mx,
      notify,
      playSound,
      showNotifications,
      notificationSound,
      useAuthentication,
      quietHoursEnabled,
      quietHoursStart,
      quietHoursEnd,
      focusAssistActive,
      messageSoundId,
    ],
  );

  useEffect(() => {
    const handleTimelineEvent: RoomEventHandlerMap[RoomEvent.Timeline] = (
      mEvent,
      room,
      toStartOfTimeline,
      removed,
      data,
    ) => {
      if (mx.getSyncState() !== 'SYNCING') return;
      if (document.hasFocus() && (selectedRoomId === room?.roomId || notificationSelected)) return;
      if (
        !room ||
        !data.liveEvent ||
        room.isSpaceRoom() ||
        !isNotificationEvent(mEvent) ||
        getNotificationType(mx, room.roomId) === NotificationType.Mute
      ) {
        return;
      }

      const sender = mEvent.getSender();
      const eventId = mEvent.getId();
      if (!sender || !eventId || mEvent.getSender() === mx.getUserId()) return;
      // Single-owner rule: thread replies are delivered by the ThreadEvent.NewReply
      // handler below (per-thread gating), so ignore them here — a reply notifies once.
      if (mEvent.threadRootId && mEvent.getId() !== mEvent.threadRootId) return;

      deliverNotification(room, mEvent);
    };
    mx.on(RoomEvent.Timeline, handleTimelineEvent);
    return () => {
      mx.removeListener(RoomEvent.Timeline, handleTimelineEvent);
    };
  }, [mx, notificationSelected, selectedRoomId, deliverNotification]);

  const handleNewReply = useCallback(
    // useRoomsListener prepends the emitting Room; the thread's own room lookup
    // below is kept as the authority (identical object in practice).
    (_room: Room, thread: Thread, mEvent: MatrixEvent) => {
      if (mx.getSyncState() !== 'SYNCING') return;
      const room = mx.getRoom(thread.roomId);
      if (!room || room.isSpaceRoom()) return;
      if (!isNotificationEvent(mEvent) || mEvent.isSending()) return;
      const sender = mEvent.getSender();
      if (!sender || sender === mx.getUserId()) return;
      // Suppress when the user is actively looking at this thread (or the inbox).
      if (
        document.hasFocus() &&
        (notificationSelected || (selectedRoomId === thread.roomId && activeThreadId === thread.id))
      ) {
        return;
      }

      // Per-thread dedupe: a NewReply can re-fire for the same event as the
      // thread (re)populates; notify at most once per (thread, event).
      const eventId = mEvent.getId();
      if (eventId) {
        if (lastNotifiedThreadRef.current.get(thread.id) === eventId) return;
        lastNotifiedThreadRef.current.set(thread.id, eventId);
      }

      const content = threadPrefs;
      const mode = getThreadNotificationMode(content, room.roomId, thread.id);
      const actions = mx.getPushActionsForEvent(mEvent);
      const decision = shouldNotifyThreadReply({
        mode,
        defaultBehavior: content.default ?? THREAD_NOTIFICATIONS_FALLBACK_BEHAVIOR,
        participated: thread.hasCurrentUserParticipated,
        highlight: !!actions?.tweaks?.highlight,
        notify: !!actions?.notify,
        roomMuted: getNotificationType(mx, room.roomId) === NotificationType.Mute,
      });
      if (decision === 'none') return;

      // E2EE caveat: NewReply can fire before decryption, so MentionsOnly may
      // under-notify in encrypted rooms (same class as the main timeline path).
      // Plaintext body suppression for encrypted rooms is handled inside notify().
      deliverNotification(room, mEvent, thread.id);
    },
    [mx, notificationSelected, selectedRoomId, activeThreadId, threadPrefs, deliverNotification],
  );
  useRoomsListener(mx, ThreadEvent.NewReply, handleNewReply);

  return (
    <audio ref={audioRef} style={{ display: 'none' }} aria-hidden="true">
      <source src={soundSrc ?? NotificationSound} type="audio/ogg" />
    </audio>
  );
}

type ClientNonUIFeaturesProps = {
  children: ReactNode;
};

function DeepLinkNavigator() {
  useDeepLinkNavigate();
  return null;
}

function ReminderMonitor() {
  const mx = useMatrixClient();
  const { reminders, removeReminder } = useReminders();
  const setToast = useSetAtom(toastQueueAtom);
  const mDirects = useAtomValue(mDirectAtom);
  const firedRef = useRef<Set<string>>(new Set());
  const removingRef = useRef<Set<string>>(new Set());
  // Read the latest reminders / DM map via refs so the poll interval below is
  // created once — not torn down and restarted (which resets its 30s countdown
  // and can indefinitely defer a near-due reminder) on every reminder sync (N115).
  const remindersRef = useRef(reminders);
  remindersRef.current = reminders;
  const mDirectsRef = useRef(mDirects);
  mDirectsRef.current = mDirects;

  useEffect(() => {
    const check = () => {
      const now = Date.now();
      remindersRef.current.forEach((r) => {
        if (r.timestamp > now) return;
        const key = `${r.eventId}-${r.timestamp}`;
        // Show the toast exactly once.
        if (!firedRef.current.has(key)) {
          firedRef.current.add(key);
          const room = mx.getRoom(r.roomId);
          const hashPath = mDirectsRef.current.has(r.roomId)
            ? getDirectRoomPath(r.roomId, r.eventId)
            : getHomeRoomPath(r.roomId, r.eventId);
          setToast({
            id: `reminder-${key}`,
            displayName: 'Reminder',
            body: r.message,
            roomName: room?.name ?? 'Unknown Room',
            roomId: r.roomId,
            hashPath,
          });
        }
        // Persist the removal, retrying on a later tick if it fails — without
        // re-showing the toast (N114). The server echo drops it from
        // `reminders` once the write lands.
        if (!removingRef.current.has(key)) {
          removingRef.current.add(key);
          removeReminder(r.eventId, r.timestamp).catch(() => {
            removingRef.current.delete(key);
          });
        }
      });
    };

    check();
    const interval = setInterval(check, 30_000);
    const onVisible = () => {
      if (document.visibilityState === 'visible') check();
    };
    document.addEventListener('visibilitychange', onVisible);
    return () => {
      clearInterval(interval);
      document.removeEventListener('visibilitychange', onVisible);
    };
  }, [mx, setToast, removeReminder]);

  return null;
}

const TAURI_UPDATE_CHECK_INTERVAL = 12 * 60 * 60_000; // 12 hours
const TAURI_UPDATE_LAST_CHECK_KEY = 'lotus.tauriUpdateLastCheck';

function TauriUpdateFeature() {
  const { isTauri, status, check, install } = useTauriUpdater();
  const setToast = useSetAtom(toastQueueAtom);
  const firedRef = useRef<string | null>(null);

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

    const runCheck = () => {
      const last = Number(localStorage.getItem(TAURI_UPDATE_LAST_CHECK_KEY) ?? '0');
      if (Date.now() - last < TAURI_UPDATE_CHECK_INTERVAL) return;
      localStorage.setItem(TAURI_UPDATE_LAST_CHECK_KEY, String(Date.now()));
      check();
    };

    runCheck();
    const interval = setInterval(runCheck, TAURI_UPDATE_CHECK_INTERVAL);
    return () => clearInterval(interval);
  }, [isTauri, check]);

  useEffect(() => {
    if (status.state !== 'available') return;
    if (firedRef.current === status.version) return;
    firedRef.current = status.version;
    setToast({
      id: `tauri-update-${status.version}`,
      displayName: '⬆ Update Available',
      body: `Lotus Chat ${status.version} is ready. Click to install and restart.`,
      roomName: 'System',
      roomId: '',
      onClick: install,
      sticky: true,
    });
  }, [status, setToast, install]);

  return null;
}

function LotusDenoiseFeature() {
  const setToast = useSetAtom(toastQueueAtom);

  useEffect(() => {
    const handleMessage = (event: MessageEvent) => {
      if (event.data?.type === 'lotus-denoise-status') {
        const { active, error } = event.data;
        if (!active) {
          setToast({
            id: `denoise-fail-${Date.now()}`,
            displayName: 'Audio Quality',
            body: `ML Noise Suppression failed: ${error || 'Unknown error'}. Falling back to raw mic.`,
            roomName: 'System',
            roomId: '',
          });
        }
      }
    };

    window.addEventListener('message', handleMessage);
    return () => window.removeEventListener('message', handleMessage);
  }, [setToast]);

  return null;
}

// Registers the global `?` shortcut (ignored while typing) and renders the
// keyboard-shortcuts help dialog. Headless — the dialog self-gates on its atom.
function KeyboardShortcutsFeature() {
  useKeyboardShortcutsTrigger();
  return <KeyboardShortcutsDialog />;
}

export function ClientNonUIFeatures({ children }: ClientNonUIFeaturesProps) {
  return (
    <>
      <SystemEmojiFeature />
      <PageZoomFeature />
      <FaviconUpdater />
      <PresenceUpdater />
      <InviteNotifications />
      <MessageNotifications />
      <ReminderMonitor />
      <TauriUpdateFeature />
      <TauriDesktopFeatures />
      <LotusDenoiseFeature />
      <DeepLinkNavigator />
      <KeyboardShortcutsFeature />
      {children}
    </>
  );
}
