"use client";

import React, { createContext, useContext, useState, useCallback, useEffect } from "react";

interface MessengerContextValue {
  isOpen: boolean;
  selectedRoomId: string | null;
  unreadCount: number;
  notificationEnabled: boolean;
  mutedRooms: Set<string>;
  openMessenger: (roomId?: string) => void;
  closeMessenger: () => void;
  selectRoom: (roomId: string) => void;
  setUnreadCount: (count: number) => void;
  toggleNotification: () => void;
  toggleRoomMute: (roomId: string) => void;
}

const MessengerContext = createContext<MessengerContextValue | undefined>(undefined);

export function MessengerProvider({ children }: { children: React.ReactNode }) {
  const [isOpen, setIsOpen] = useState(false);
  const [selectedRoomId, setSelectedRoomId] = useState<string | null>(null);
  const [unreadCount, setUnreadCount] = useState(0);
  const [notificationEnabled, setNotificationEnabled] = useState(true);
  const [mutedRooms, setMutedRooms] = useState<Set<string>>(new Set());

  useEffect(() => {
    const stored = localStorage.getItem("messenger_notification");
    if (stored !== null) setNotificationEnabled(stored === "true");
    try {
      const muted = JSON.parse(localStorage.getItem("messenger_muted_rooms") || "[]");
      setMutedRooms(new Set(muted));
    } catch {}
  }, []);

  const openMessenger = useCallback((roomId?: string) => {
    setIsOpen(true);
    if (roomId) setSelectedRoomId(roomId);
  }, []);

  const closeMessenger = useCallback(() => {
    setIsOpen(false);
  }, []);

  const selectRoom = useCallback((roomId: string) => {
    setSelectedRoomId(roomId);
  }, []);

  const toggleNotification = useCallback(() => {
    setNotificationEnabled((prev) => {
      const next = !prev;
      localStorage.setItem("messenger_notification", String(next));
      return next;
    });
  }, []);

  const toggleRoomMute = useCallback((roomId: string) => {
    setMutedRooms((prev) => {
      const next = new Set(prev);
      if (next.has(roomId)) next.delete(roomId);
      else next.add(roomId);
      localStorage.setItem("messenger_muted_rooms", JSON.stringify([...next]));
      return next;
    });
  }, []);

  return (
    <MessengerContext.Provider
      value={{
        isOpen,
        selectedRoomId,
        unreadCount,
        notificationEnabled,
        mutedRooms,
        openMessenger,
        closeMessenger,
        selectRoom,
        setUnreadCount,
        toggleNotification,
        toggleRoomMute,
      }}
    >
      {children}
    </MessengerContext.Provider>
  );
}

export function useMessengerContext() {
  const ctx = useContext(MessengerContext);
  if (!ctx) throw new Error("useMessengerContext must be used within MessengerProvider");
  return ctx;
}
