import React, { useEffect } from 'react';
import { StyleSheet, View, ViewStyle } from 'react-native';
import {
  useChatRoom,
  useChatRoomActions,
  useLoadStickerPacksEffect,
  useStyles,
} from '../hooks';
import { ComponentStyleProp, LLComponentStyleFn } from '../types';
import { LLChatMessageList, LLChatMessageListProps } from './LLChatMessageList';
import {
  LLChatMessageComposer,
  LLChatMessageComposerProps,
} from './LLChatMessageComposer';
import { LLChatHeader, LLChatHeaderProps } from './LLChatHeader';
import { LLChatBanner, LLChatBannerProps } from './LLChatBanner';

export type LLChatStyles = {
  chatContainer: ViewStyle;
};

export type LLChatProps = ComponentStyleProp<LLChatStyles> & {
  roomId: string;
  userAvatarUrl?: string;
  HeaderComponent?: typeof LLChatHeader;
  HeaderComponentStyles?: LLChatHeaderProps['styles'];
  BannerComponent?: typeof LLChatBanner;
  BannerComponentStyles?: LLChatBannerProps['styles'];
  MessageListComponent?: typeof LLChatMessageList;
  MessageListComponentStyles?: LLChatMessageListProps['styles'];
  MessageComposerComponent?: typeof LLChatMessageComposer;
  MessageComposerComponentStyles?: LLChatMessageComposerProps['styles'];
};

export function LLChat({
  roomId,
  userAvatarUrl,
  HeaderComponent = LLChatHeader,
  BannerComponent = LLChatBanner,
  MessageListComponent = LLChatMessageList,
  MessageComposerComponent = LLChatMessageComposer,
  styles: stylesProp,
  BannerComponentStyles,
  HeaderComponentStyles,
  MessageComposerComponentStyles,
  MessageListComponentStyles,
}: LLChatProps) {
  const { chatRoom } = useChatRoom({ roomId });
  const chatStyles = useStyles({
    componentStylesFn: getChatStyles,
    stylesProp,
  });
  useLoadStickerPacksEffect();
  const chatRoomActions = useChatRoomActions({ roomId });
  useEffect(() => {
    if (roomId && userAvatarUrl) {
      chatRoomActions.updateChatConfig({
        roomId,
        userAvatarUrl,
      });
    }
  }, [roomId, userAvatarUrl]);

  return (
    <View style={chatStyles.chatContainer}>
      {chatRoom && (
        <HeaderComponent
          title={chatRoom.title}
          styles={HeaderComponentStyles}
        />
      )}
      <BannerComponent styles={BannerComponentStyles} />
      <MessageListComponent
        roomId={roomId}
        styles={MessageListComponentStyles}
      />
      <MessageComposerComponent
        roomId={roomId}
        styles={MessageComposerComponentStyles}
      />
    </View>
  );
}

const getChatStyles: LLComponentStyleFn<LLChatStyles> = ({ theme }) =>
  StyleSheet.create({
    chatContainer: {
      width: '100%',
      flex: 1,
      flexDirection: 'column',
      alignContent: 'center',
      justifyContent: 'center',
      backgroundColor: theme.background,
    },
  });
