import { useEffect, 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 = () => setIsExpanded(prev => !prev);

  const toggleRecentChats = () => setShowRecentChats(prev => !prev);

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

  const handlePreviousChatCharacterClick = (
    character: PrivateChatCharacter
  ) => {
    if (onPreviousChatCharacterClick) {
      onPreviousChatCharacterClick(character);
    }
    if (hideSearchCharacterUI) {
      hideSearchCharacterUI();
    }
  };

  return {
    showRecentChats,
    isExpanded,
    toggleExpand,
    toggleRecentChats,
    handleTabChange,
    handlePreviousChatCharacterClick,
    hasUnseenMessages:
      unseenMessageCharacterIds && unseenMessageCharacterIds?.length > 0,
  };
};
