import React, { useState, useEffect, useRef } from 'react';
import {
  View, Text, TextInput, TouchableOpacity,
  ActivityIndicator, FlatList, Platform, StyleSheet,
  KeyboardAvoidingView, Keyboard, Animated, Easing
} from 'react-native';
import moment from 'moment';
import { connect } from 'react-redux';
import Container from '../../components/container';
import CustomHeader from '../../components/customHeader';
import { mapStateToProps, mapDispatchToProps } from '../../reducers/contextProvider';
import { SvgXml } from 'react-native-svg';
import SendIcon from "../../assets/icons/SendIcon.svg";
import CPMChatAPI from "../../utils/cpmChatAPI";
import { CONFIG } from '../../constants/constants';
import Markdown from 'react-native-markdown-display';

const markdownStyles = {
  body: {
    color: '#1A1A1A',
    fontSize: 14,
    fontWeight: '440',
    lineHeight: 17,
  },
  paragraph: {
    marginBottom: 5,
  },
  strong: {
    fontWeight: '500',
  },
  em: {
    fontStyle: 'italic',
  },
  code_inline: {
    backgroundColor: '#ffffff1A',
    paddingHorizontal: 6,
    paddingVertical: 2,
    borderRadius: 4,
    fontFamily: Platform.OS === 'ios' ? 'Courier' : 'monospace',
  },
  link: {
    color: '#4DA8FF',
    textDecorationLine: 'underline',
  },
};

function ChatScreen(props) {
  const [messages, setMessages] = useState([]);
  const [currentMessage, setCurrentMessage] = useState("");
  const [disclaimer, setDisclaimer] = useState(CONFIG.DEFAULT_DISCLAIMER);
  const [sessionId, setSessionId] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const chatAPI = useRef(null);
  const flatListRef = useRef(null);
  const dotOpacity1 = useRef(new Animated.Value(0.3)).current;
  const dotOpacity2 = useRef(new Animated.Value(0.3)).current;
  const dotOpacity3 = useRef(new Animated.Value(0.3)).current;

  const config = {
    userId: props.UserId || CONFIG.DEFAULT_USER_ID,
    userName: props.EmployeeName || CONFIG.DEFAULT_USER_NAME,
  };

  useEffect(() => {
    let Chatbot_Creds = props.Chatbot_Creds != null && props.Chatbot_Creds != "" ? JSON.parse(props.Chatbot_Creds) : [];
    let Chatbot_CredsObj = Chatbot_Creds.length > 0 ? Chatbot_Creds[0] : {};
    setDisclaimer(Chatbot_CredsObj?.CHATBOT_DISCLAIMER || CONFIG.DEFAULT_DISCLAIMER)
    chatAPI.current = new CPMChatAPI(
      Chatbot_CredsObj?.CHATBOT_BASE_URL || CONFIG.API_BASE_URL,
      Chatbot_CredsObj?.CLIENT_ID || CONFIG.CLIENT_ID,
      Chatbot_CredsObj?.CLIENT_SECRET || CONFIG.CLIENT_SECRET
    );
    startChat();
  }, []);

  useEffect(() => {
    if (isLoading) {
      console.log('Starting typing animation');
      const animateDot = (dot, delay) => {
        Animated.loop(
          Animated.sequence([
            Animated.timing(dot, {
              toValue: 1,
              duration: 300,
              delay,
              easing: Easing.inOut(Easing.ease),
              useNativeDriver: true,
            }),
            Animated.timing(dot, {
              toValue: 0.3,
              duration: 300,
              easing: Easing.inOut(Easing.ease),
              useNativeDriver: true,
            }),
          ])
        ).start();
      };
      animateDot(dotOpacity1, 0);
      animateDot(dotOpacity2, 100);
      animateDot(dotOpacity3, 200);
    } else {
      console.log('Stopping typing animation');
      dotOpacity1.setValue(0.3);
      dotOpacity2.setValue(0.3);
      dotOpacity3.setValue(0.3);
    }
  }, [isLoading]);

  const startChat = async () => {
    try {
      setIsLoading(true);
      const response = await chatAPI.current.initChat(config.userId, config.userName);
      setSessionId(response.sessionId);

      const formattedMessages = response.messages.map((msg) => ({
        ...msg,
        timestamp: new Date(msg.timestamp),
      }));

      setMessages(response.isNewSession
        ? [...formattedMessages, {
          sender: "ai",
          text: CONFIG.WELCOME_MESSAGE,
          timestamp: new Date(),
        }]
        : formattedMessages
      );
    } catch (err) {
      console.log('Start chat error:', err);
    } finally {
      setIsLoading(false);
    }
  };

  const sendMessage = async () => {
    Keyboard.dismiss();
    if (!currentMessage.trim() || !sessionId) return;

    const userMessage = {
      sender: "user",
      text: currentMessage,
      timestamp: new Date(),
    };

    setMessages(prev => [...prev, userMessage]);
    setCurrentMessage("");
    setIsLoading(true);

    try {
      const response = await chatAPI.current.sendMessage(config.userId, sessionId, currentMessage);
      const aiMessage = {
        sender: "ai",
        text: response,
        timestamp: new Date(),
      };
      setMessages(prev => [...prev, aiMessage]);
    } catch (err) {
      setMessages(prev => [...prev, {
        sender: "system",
        text: `Error: ${err.message}`,
        timestamp: new Date(),
      }]);
    } finally {
      setIsLoading(false);
    }
  };

  const formatRelativeTime = (timestamp) => {
    return moment(timestamp).calendar(null, {
      sameDay: '[Today] h:mm A',
      lastDay: '[Yesterday] h:mm A',
      lastWeek: 'MMM D, YYYY h:mm A',
      sameElse: 'MMM D, YYYY h:mm A'
    });
  };

  useEffect(() => {
    if (flatListRef.current && messages.length > 0) {
      setTimeout(() => {
        if (flatListRef.current) {
          flatListRef.current.scrollToOffset({ offset: 0, animated: true });
        }
      }, 100);
    }
  }, [messages]);


  const renderItem = ({ item, index }) => {
    let nText = item?.text?.replace(/\n\[.*?\]/g, '').trim();
    // Since FlatList is inverted, the first item (index 0) is the most recent
    const isLastUserMessage = index === 0 && item.sender === 'user' && isLoading;

    return (
      <View style={styles.chatBlock}>
        {item.sender === 'user' ? (
          <TouchableOpacity style={styles.questionButton}>
            <Text style={styles.questionButtonText}>{nText}</Text>
          </TouchableOpacity>
        ) : (
          <View style={styles.leftMessageRow}>
            <View style={styles.leftBubble}>
              <Markdown style={markdownStyles}>{nText}</Markdown>
              <Text style={styles.bubbleTimestamp}>{formatRelativeTime(item.timestamp)}</Text>
            </View>
          </View>
        )}
        {isLastUserMessage && (
          <View style={styles.typingIndicator}>
            <Animated.View style={[styles.dot, { opacity: dotOpacity1 }]} />
            <Animated.View style={[styles.dot, { opacity: dotOpacity2 }]} />
            <Animated.View style={[styles.dot, { opacity: dotOpacity3 }]} />
          </View>
        )}
      </View>
    );
  };

  return (
    <Container {...props} pt={0} avoidSafeArea={Platform.OS === 'ios'}>
      <CustomHeader {...props} title="Gyan Buddy" />
      <View style={styles.container}>
        <FlatList
          ref={flatListRef}
          data={[...messages].reverse()}
          renderItem={renderItem}
          keyExtractor={(item, index) => index.toString()}
          inverted={true}
          contentContainerStyle={styles.flatListContent}
          showsVerticalScrollIndicator={false}
        />
        <KeyboardAvoidingView
          behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
          keyboardVerticalOffset={Platform.OS === 'ios' ? 100 : 20}
          style={styles.keyboardAvoidingView}
        >
          <View style={styles.inputCard}>
            <TextInput
              placeholder="Ask me anything..."
              placeholderTextColor="#888"
              value={currentMessage}
              onChangeText={setCurrentMessage}
              style={styles.input}
              multiline
              maxLength={500}
            />
            <TouchableOpacity onPress={sendMessage} disabled={isLoading}>
              <SendIcon width={32} height={32} />
            </TouchableOpacity>
          </View>
        </KeyboardAvoidingView>
        <Text style={styles.footerText}> {disclaimer}</Text>
      </View>
    </Container>
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(ChatScreen);

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5F7FA',
    width: '100%'
  },
  flatListContent: {
    paddingBottom: 2,
    paddingTop: 10,
  },
  chatBlock: {
    marginBottom: 15,
    paddingHorizontal: 15,
  },
  questionButton: {
    alignSelf: 'flex-end',
    backgroundColor: 'white',
    paddingVertical: 12,
    paddingHorizontal: 10,
    borderBottomRightRadius: 1,
    borderRadius: 15,
    maxWidth: '75%',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  questionButtonText: {
    fontSize: 14,
    fontWeight: '500',
    color: '#1A1A1A',
    lineHeight: 20,
  },
  leftMessageRow: {
    alignSelf: 'flex-start',
    maxWidth: '100%',
  },
  leftBubble: {
    backgroundColor: '#CFE5FF',
    borderRadius: 16,
    padding: 8,
    borderTopLeftRadius: 1,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  bubbleTimestamp: {
    fontSize: 12,
    color: '#1A1A1A',
    marginTop: 4,
    alignSelf: 'flex-end',
  },
  inputCard: {
    flexDirection: 'row',
    backgroundColor: '#FFFFFF',
    borderRadius: 24,
    marginLeft: 8,
    marginRight: 8,
    padding: 8,
    alignItems: 'center',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.15,
    shadowRadius: 6,
    elevation: 2,
  },
  input: {
    flex: 1,
    fontSize: 15,
    color: '#1A1A1A',
    minHeight: 40,
    maxHeight: 100,
    paddingVertical: 8,
  },
  footerText: {
    textAlign: 'center',
    fontSize: 10,
    color: '#666',
    marginVertical: 5,
    paddingHorizontal: 20,
    fontStyle: 'normal',
  },
  keyboardAvoidingView: {
    paddingBottom: 2,
  },
  typingIndicator: {
    flexDirection: 'row',
    alignSelf: 'flex-start',
    marginLeft: 12,
    marginTop: 8,
  },
  dot: {
    width: 8,
    height: 8,
    backgroundColor: 'black',
    borderRadius: 4,
    marginHorizontal: 2,
  },
});