import { StackScreenProps } from '@react-navigation/stack';
import React, { useState, useCallback, useEffect } from 'react';
import { Platform, View, KeyboardAvoidingView } from 'react-native';
import { Div, Button, Image, Text, Avatar } from 'react-native-magnus';
import { GiftedChat } from 'react-native-gifted-chat';
import { ScrollView } from 'react-native-gesture-handler';
import * as Localization from 'expo-localization';
import useModel from 'flooks';
import User from '../stores/User';
import IM from './model';
import { parse } from '../utils/TimeUtils';
import { useTranslation } from 'react-i18next';

import { useRequest } from 'ahooks';

export default function ChatScreen({ navigation, route }: StackScreenProps) {
  const { params } = route;
  const { toUserId, toUserName } = params;
  const { t } = useTranslation();

  if (toUserName) {
    navigation.setOptions({
      title: toUserName,
    });
  }

  const { id, userInfo, chatInfo } = useModel(User, [
    'id',
    'chatInfo',
    'userInfo',
  ]);

  const [messages, setMessages] = useState([]);
  const { sendMessage } = useModel(IM, []);

  const { loading, run } = useRequest(
    `/chat/showChat?userOne=${id}&userTwo=${toUserId}`,
    {
      defaultLoading: false,
      initialData: [],
      onSuccess: (data) => {
        const list = data.map((item, index) => {
          return {
            _id: index,
            text: item.content,
            createdAt: parse(item.sendTime),
            user: {
              _id: item.sendUserId,
              name: item.sendNickName,
              avatar: item.sendAvatar,
            },
          };
        });
        setMessages(list);
      },
    }
  );

  React.useEffect(() => {
    if (chatInfo && chatInfo.from === toUserId.toString()) {
      run();
    }
  }, [chatInfo]);

  const onSend = useCallback((messages = []) => {
    console.log(messages);
    sendMessage(messages[0].text, toUserId);
    setMessages((previousMessages) =>
      GiftedChat.append(previousMessages, messages)
    );
  }, []);

  return (
    <Div flex={1}>
      <GiftedChat
        placeholder={t('qing-shu-ru-liao-tian-nei-rong')}
        messages={messages}
        onSend={(messages) => onSend(messages)}
        showUserAvatar={true}
        user={{
          _id: userInfo.id,
          avatar: userInfo.avatar,
        }}
      />
      {/* {Platform.OS === 'android' && <KeyboardAvoidingView behavior="padding" />} */}
    </Div>
  );
}
