// ChatScreen.tsx
import React, { useEffect, useRef, useState } from "react";
import {
    Dimensions,
    Keyboard,
    Platform,
    ScrollView,
    StyleSheet,
    Text,
    TextInput,
    TouchableOpacity,
    View,
} from "react-native";
import {
    SafeAreaView
} from "react-native-safe-area-context";

type Message = {
  id: string;
  text: string;
  sender: "me" | "other";
  timestamp: Date;
};

const { height: SCREEN_HEIGHT } = Dimensions.get("window");

const ChatScreen: React.FC = () => {
  const [messages, setMessages] = useState<Message[]>([
    {
      id: "1",
      text: "Hai!",
      sender: "other",
      timestamp: new Date(Date.now() - 300000),
    },
    {
      id: "2",
      text: "Halo juga!",
      sender: "me",
      timestamp: new Date(Date.now() - 240000),
    },
    {
      id: "3",
      text: "Apa kabar?",
      sender: "other",
      timestamp: new Date(Date.now() - 180000),
    },
  ]);
  const [inputText, setInputText] = useState<string>("");
  const [keyboardHeight, setKeyboardHeight] = useState<number>(0);
  const scrollViewRef = useRef<ScrollView>(null);

  useEffect(() => {
    const show = Keyboard.addListener("keyboardDidShow", (e) => {
      let kbHeight = e.endCoordinates.height;
      // Di Android dengan edge-to-edge, kadang tinggi termasuk navigation bar
      if (Platform.OS === "android") {
        // Batasi maksimal 60% layar
        kbHeight = Math.min(kbHeight, SCREEN_HEIGHT * 2);
      }
      setKeyboardHeight(kbHeight);
    });

    const hide = Keyboard.addListener("keyboardDidHide", () => {
      setKeyboardHeight(0);
    });

    return () => {
      show.remove();
      hide.remove();
    };
  }, []);

  useEffect(() => {
    // Scroll ke bawah setelah pesan baru atau keyboard muncul
    const timer = setTimeout(() => {
      scrollViewRef.current?.scrollToEnd({ animated: true });
    }, 100); // delay kecil untuk pastikan layout stabil
    return () => clearTimeout(timer);
  }, [messages, keyboardHeight]);

  const handleSend = () => {
    if (!inputText.trim()) return;
    setMessages((prev) => [
      ...prev,
      {
        id: Date.now().toString(),
        text: inputText.trim(),
        sender: "me",
        timestamp: new Date(),
      },
    ]);
    setInputText("");
  };


  return (
    <SafeAreaView style={styles.safeArea}>
      {/* Kontainer utama dengan padding bottom = tinggi keyboard */}
      <View style={[styles.container, { paddingBottom: keyboardHeight }]}>
        <ScrollView
          ref={scrollViewRef}
          style={styles.messagesContainer}
          contentContainerStyle={styles.messagesContent}
          keyboardShouldPersistTaps="handled"
        >
          {messages.map((msg) => (
            <View
              key={msg.id}
              style={[
                styles.messageBubble,
                msg.sender === "me" ? styles.myMessage : styles.otherMessage,
              ]}
            >
              <Text style={styles.messageText}>{msg.text}</Text>
              <Text style={styles.timestamp}>
                {msg.timestamp.toLocaleTimeString([], {
                  hour: "2-digit",
                  minute: "2-digit",
                })}
              </Text>
            </View>
          ))}
        </ScrollView>

        <View style={[styles.inputContainer, { paddingBottom: 10 }]}>
          <TextInput
            value={inputText}
            onChangeText={setInputText}
            placeholder="Ketik pesan..."
            style={styles.textInput}
            multiline
            blurOnSubmit={false}
            scrollEnabled={Platform.OS === "ios"} // ✅ Aktifkan scroll hanya di iOS
            textAlignVertical="top"
          />
          <TouchableOpacity
            style={styles.sendButton}
            onPress={handleSend}
            disabled={!inputText.trim()}
          >
            <Text style={styles.sendButtonText}>Kirim</Text>
          </TouchableOpacity>
        </View>
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: "#e5ddd5",
  },
  container: {
    flex: 1,
    backgroundColor: "#e5ddd5",
  },
  messagesContainer: {
    flex: 1,
    paddingHorizontal: 10,
  },
  messagesContent: {
    paddingBottom: 10,
  },
  messageBubble: {
    maxWidth: "80%",
    padding: 10,
    marginVertical: 4,
    borderRadius: 12,
  },
  myMessage: {
    alignSelf: "flex-end",
    backgroundColor: "#dcf8c6",
  },
  otherMessage: {
    alignSelf: "flex-start",
    backgroundColor: "#ffffff",
  },
  messageText: {
    fontSize: 16,
    color: "#000",
  },
  timestamp: {
    fontSize: 10,
    color: "#666",
    textAlign: "right",
    marginTop: 4,
  },
  inputContainer: {
    flexDirection: "row",
    alignItems: "flex-end",
    paddingHorizontal: 10,
    paddingTop: 8,
    backgroundColor: "#f0f0f0",
    borderTopWidth: 1,
    borderTopColor: "#ddd",
  },
  textInput: {
    flex: 1,
    borderWidth: 1,
    borderColor: "#ccc",
    borderRadius: 20,
    paddingHorizontal: 12,
    paddingVertical: 8,
    fontSize: 16,
    backgroundColor: "#fff",
    maxHeight: 100,
  },
  sendButton: {
    marginLeft: 10,
    backgroundColor: "#34b7f1",
    paddingHorizontal: 16,
    paddingVertical: 10,
    borderRadius: 20,
  },
  sendButtonText: {
    color: "#fff",
    fontWeight: "bold",
  },
});

export default ChatScreen;
