import { useCallback, useEffect, useMemo, useState } from 'react';
import { PrivateChatCharacter } from '../components/ChatRevamp/types';

interface IUseChat {
  minimizedByDefault: boolean;
  isPrivate: boolean;
  onChangeTab: (tabId: string) => void;
  onPreviousChatCharacterClick?: (character: PrivateChatCharacter) => void;
  hideSearchCharacterUI?: () => void;
  unseenMessageCharacterIds?: string[];
}

export const useChat = ({
  minimizedByDefault,
  isPrivate,
  onChangeTab,
  onPreviousChatCharacterClick,
  hideSearchCharacterUI,
  unseenMessageCharacterIds,
}: IUseChat) => {
  const [showRecentChats, setShowRecentChats] = useState(false);
  const [isExpanded, setIsExpanded] = useState(!minimizedByDefault);

  useEffect(() => {
    if (isPrivate) {
      setIsExpanded(true);
    }
  }, [isPrivate]);

  const toggleExpand = useCallback(() => setIsExpanded(prev => !prev), []);

  const toggleRecentChats = useCallback(
    () => setShowRecentChats(prev => !prev),
    []
  );

  const handleTabChange = useCallback(
    (tabId: string) => {
      if (tabId === 'private') {
        setIsExpanded(true);
      }
      onChangeTab(tabId);
    },
    [onChangeTab]
  );

  const handlePreviousChatCharacterClick = useCallback(
    (character: PrivateChatCharacter) => {
      if (onPreviousChatCharacterClick) {
        onPreviousChatCharacterClick(character);
      }
      if (hideSearchCharacterUI) {
        hideSearchCharacterUI();
      }
    },
    [onPreviousChatCharacterClick, hideSearchCharacterUI]
  );

  const hasUnseenMessages = useMemo(
    () => unseenMessageCharacterIds && unseenMessageCharacterIds.length > 0,
    [unseenMessageCharacterIds]
  );

  return {
    showRecentChats,
    isExpanded,
    toggleExpand,
    toggleRecentChats,
    handleTabChange,
    handlePreviousChatCharacterClick,
    hasUnseenMessages,
  };
};
