// @ts-nocheck
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
import * as Linking from 'expo-linking'
import AppLoading from 'expo-app-loading'
import * as SplashScreen from 'expo-splash-screen';
import React, { Component,useCallback,useEffect  } from 'react'
import { StyleSheet, View, Text, Platform, Alert,KeyboardAvoidingView } from 'react-native'
import {
  Bubble,
  GiftedChat,
  SystemMessage,
  IMessage,
  Send,
  SendProps,
} from 'react-native-gifted-chat'

import AccessoryBar from './chat/AccesoryBar'
import CustomActions from './chat/CustomActions'
import CustomView from './chat/CustomView'
//import messagesData from './chat/data/messages'
//import earlierMessages from './chat/data/earlierMessages'
import { NavBar } from './chat/navbar'
import ChatState from './state';
import AsyncStorage from '@react-native-async-storage/async-storage';
// import { IUser } from '../../context/interfaces';

const styles = StyleSheet.create({
  container: { flex: 1 },
})

const filterBotMessages = (message : any) =>
  !message.system && message.user && message.user._id && message.user._id === 2
const findStep = (step : any) => (message : any) => message._id === step


interface ChatUser {
  _id:number;
  name:string;
}

interface IProps {
  title:string;
  user:any;
  chatUser:ChatUser;
  messages:any[];
  
  onAddMessage:any;
  onRefresh(id:number):Promise<any>;
  refreshData:number;
}

export default function(props:IProps) {
  return <ChatApp {...props}/>
}

class ChatApp extends Component<IProps,any> {
  chatUser = {
    // _id: 1,
    // name: 'Developer',


  }

  otherUser = {
    _id: 2,
    name: 'Chofer',
    //avatar:'https://i.ibb.co/n6Wc32n/chofer.jpg'
    avatar:"https://cdn-icons-png.flaticon.com/512/4634/4634905.png"
    //avatar:'https://facebook.github.io/react/img/logo_og.png',
  }
  
  user:any;

  _isMounted = false

  constructor(props) {
    super(props);
    console.disableYellowBox = true;

    this.state = {
      inverted: false,
      step: 0,
      messages: [],
      loadEarlier: true,
      typingText: null,
      isLoadingEarlier: false,
      appIsReady: false,
      isTyping: false,
      interval:-1
    };

    this.user = this.props.user;
    this.chatUser = this.props.chatUser;

    this.chatUser.avatar = this.chatUser._id == 2 ?
    "https://image.pngaaa.com/97/4824097-small.png" : 
    "https://toppng.com/uploads/preview/user-account-management-logo-user-icon-11562867145a56rus2zwu.png";
  }
  componentDidMount() {
    this._isMounted = true;
     let self = this;
    // init with only system messages
    this.setState({
      //...this.state,
      messages:  this.props.messages,
      appIsReady: true,
      isTyping: false,
    })
  }
  

  addMessages(messagesToAdd) {
    this.setState({
      //...this.state,
      messages : [...messages,...messagesToAdd]
    })
  }

  componentWillUnmount() {
    try {
    if (this.state.interval!= -1) {
      clearInterval(this.state.interval);
    }
  }
  catch (e) {
  }

    this._isMounted = false
  }

  onLoadEarlier = () => {
  }

  onSend = (messages : any[] = [], refresh:boolean=false) => {
    if (this.state) {
    const step = this.state.step + 1;

    let sentMessages = messages!= null && messages.length > 0 ?
     [{ ...messages[0], sent: true, received: true,createdAt:new Date() }] : [];

    if (refresh && messages != null && messages.length > 0) {
      sentMessages=[];
      for (var i=0;i<messages.length;i++) {
        var msg = messages[i];
      //  msg.user.avatar =  
        

        msg._id = Math.round(Math.random() * 1000000);
        sentMessages.push({
          ...msg,
          sent:true,
          received:true,
          createdAt:new Date()
        });
      }
    }

    if (this.props.onAddMessage && !refresh) {
      this.props.onAddMessage(sentMessages[0]);
    }

    if (refresh) {
      this.setState({
          messages: GiftedChat.append(
            [],
            sentMessages,
            Platform.OS !== 'web',
          ),
          step,
        }
      );
    }
    else {
       this.setState((previousState: any) => {
         return {
          messages: GiftedChat.append(
            previousState.messages,
            sentMessages,
            Platform.OS !== 'web',
          ),
          step,
       }
      })
     }
   }
  }

  botSend = (step = 0) => {
    const newMessage = (messagesData as IMessage[])
      .reverse()
      .find(findStep(step))
    if (newMessage) {
      this.setState((previousState: any) => ({
        messages: GiftedChat.append(
          previousState.messages,
          [newMessage],
          Platform.OS !== 'web',
        ),
      }))
    }
  }

  parsePatterns = (_linkStyle: any) => {
    return [
      {
        pattern: /#(\w+)/,
        style: { textDecorationLine: 'underline', color: 'darkorange' },
        onPress: () => Linking.openURL('http://gifted.chat'),
      },
    ]
  }

  renderCustomView(props:any) {
    return <CustomView {...props} />
  }

  onReceive = (text: string) => {
    this.setState((previousState: any) => {
      return {
        messages: GiftedChat.append(
          previousState.messages as any,
          [
            {
              _id: Math.round(Math.random() * 1000000),
              text,
              createdAt: new Date(),
              user: otherUser,
            },
          ],
          Platform.OS !== 'web',
        ),
      }
    })
  }

  onSendFromUser = (messages: IMessage[] = []) => {
    const createdAt = new Date()
    const messagesToUpload = messages.map(message => ({
      ...message,
      user: this.chatUser,
      createdAt,
      _id: Math.round(Math.random() * 1000000),
    }))
    this.onSend(messagesToUpload)
  }

  setIsTyping = () => {
    if (this.state) {
    this.setState({
      ...this.state,
      isTyping: !this.state.isTyping,
    })
  }
  else {
    this.setState({
      ...this.state,
      isTyping: false,
    })
  }
}

  refreshMessages = () => {
    
    this.props.onRefresh(this.props.refreshData).then(e => { 
      this.onSend(e.data,true) 
    })


  }

  renderAccessory = () => (
    <AccessoryBar onSend={this.onSendFromUser} refresh={this.refreshMessages} isTyping={this.setIsTyping} />
  )

  renderCustomActions = (props:any) =>
    Platform.OS === 'web' ? null : (
      <CustomActions {...props} onSend={this.onSendFromUser} />
    )

  renderBubble = (props: any) => {
    return <Bubble {...props} />
  }

  renderSystemMessage = (props:any) => {
    return (
      <SystemMessage
        {...props}
        containerStyle={{
          marginBottom: 15,
        }}
        textStyle={{
          fontSize: 14,
        }}
      />
    )
  }

  getUniqueId() {
    return Math.round(Math.random() * 1000000);
  }
  onQuickReply = (replies:any) => {
    const createdAt = new Date()
    if (replies.length === 1) {
      this.onSend([
        {
          createdAt,
          _id: this.getUniqueId(),
          text: replies[0].title,
          user:this.chatUser,
        },
      ])
    } else if (replies.length > 1) {
      this.onSend([
        {
          createdAt,
          _id: this.getUniqueId(),
          text: replies.map((reply:any) => reply.title).join(', '),
          user:this.chatUser,
        },
      ])
    } else {
      console.warn('replies param is not set correctly')
    }
  }

  renderQuickReplySend = () => <Text>{' custom send =>'}</Text>

  renderSend = (props: SendProps<IMessage>) => (
    <Send {...props} containerStyle={{ justifyContent: 'center' }}>
      <MaterialIcons size={30} color={'tomato'} name={'send'} />
    </Send>
  )


  async showSplash() {
    try {
      // Keep the splash screen visible while we fetch resources
      await SplashScreen.preventAutoHideAsync();
    } catch (e) {
      console.warn(e);
    } finally {
      // Tell the application to render
      this.setState({...self.state,appIsReady:true})
    }
  }

  async hideSplash() {
    if (this.state && this.state.appIsReady) {
        await SplashScreen.hideAsync();
    }
  }

  render() {

    if (!this.state || !this.state.appIsReady) {
       this.showSplash();
    }

    return (
      <View
        style={styles.container}
        accessibilityLabel='main'
        testID='main'
        onLayout={this.hideSplash}
      >
        <NavBar title={this.props.title}/>
        <GiftedChat
        placeholder="Escriba su mensaje..."
          messages={this.state ? this.state.messages : []}
          
          onSend={this.onSend}
          // loadEarlier={this.state.loadEarlier}
          onLoadEarlier={this.onLoadEarlier}
          isLoadingEarlier={this.state && this.state.isLoadingEarlier}
          parsePatterns={this.parsePatterns}
          user={this.chatUser}
          scrollToBottom
          onLongPressAvatar={userPress => {}
          //  Alert.alert(JSON.stringify(userPress))
          }
          onPressAvatar={(e) => {}
            //Alert.alert('short press')
          }
          onPress={() => {
            //Alert.alert('Bubble pressed')
          }}
          onQuickReply={this.onQuickReply}
          keyboardShouldPersistTaps='never'
          renderAccessory={Platform.OS === 'web' ? null : this.renderAccessory}
          //renderActions={this.renderCustomActions}
          renderBubble={this.renderBubble}
          renderSystemMessage={this.renderSystemMessage}
          renderCustomView={this.renderCustomView}
          renderSend={this.renderSend}
          quickReplyStyle={{ borderRadius: 2 }}
          quickReplyTextStyle={{
            fontWeight: '200',
          }}
          renderQuickReplySend={this.renderQuickReplySend}
          inverted={Platform.OS !== 'web'}
          timeTextStyle={{ left: { color: 'red' }, right: { color: 'yellow' } }}
          isTyping={this.state && this.state.isTyping}
          infiniteScroll
        />
         {
          Platform.OS === 'ios' && <KeyboardAvoidingView behavior="padding" />
         }
      </View>
    )
  }
}