import * as React from 'react';
import { View, Text, Button, Pressable } from 'react-native';
import { useTranslation } from 'react-i18next';
import { LobyScreenProps } from '../types';
import { useEffect } from 'react';
import { CommonMancalaGame } from 'mancala.js';
import { channel_cancel_new_game, channel_on_game_start } from '@mancala/core';
import CircularPanel from '../components/CircularPanel';
import { getColorByBrightness } from '../util/ColorUtil';
import { SvgXml } from 'react-native-svg';
import helpSvg from '../svg/help';

export default function LobyScreen({ navigation, route }: LobyScreenProps) {

    const { context } = route.params;
    const { t } = useTranslation();

    const onGameStart = async (message: Object) => {
        const newGame: CommonMancalaGame = message as CommonMancalaGame;
        const userKey = await context.userKeyStore.getUserKey();
        navigation.replace("Game", { context, gameId: newGame.id, userKey })
    }


    const onCancelNewGameClick = () => {
        if (context.rtmt.connectionState === "connected") {
            context.rtmt.sendMessage(channel_cancel_new_game, "");
        }
        navigation.replace("Home", { context })
    }

    useEffect(() => {
        context.rtmt.addMessageListener(channel_on_game_start, onGameStart);
        context.rtmt.sendMessage("new_game", {});
        return () => {
            context.rtmt.removeMessageListener(channel_on_game_start, onGameStart);
        }
    }, []);

    const textColorOnAppBar = getColorByBrightness(
        context.themeManager.theme.appBarBgColor,
        context.themeManager.theme.textColor,
        context.themeManager.theme.textLightColor
      );
    
      const updateHeaderButton = () => {
        navigation.setOptions({
          headerRight: () => (
            <Pressable onPress={() => {
              navigation.push("Help", { context })
            }}>
              <SvgXml xml={helpSvg.replaceAll("customColor", textColorOnAppBar)} width="24" height="24" />
            </Pressable>
          ),
        });
      }
    
      React.useEffect(() => {
        updateHeaderButton();
      }, []);

    return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: context.themeManager.theme?.background }}>
            <CircularPanel color={context.themeManager.theme?.boardColor} children={<Text style={{ color: "#000" }}>{t('SearchingOpponent') + " " + t('PleaseWait') + "..."}</Text>} />
            <View style={{height: 10}}></View>
            <Pressable onPress={onCancelNewGameClick}>
                <CircularPanel color={context.themeManager.theme?.boardColor} children={<Text style={{ color: context.themeManager.theme.textColor }}>{t('Cancel')}</Text>} />
            </Pressable>
        </View>
    );
}