import React, { useMemo, useRef, useState } from "react";
import {
  FlatList,
  KeyboardAvoidingView,
  Platform,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from "react-native";
import { useRoute } from "@react-navigation/native";
import type { RouteProp } from "@react-navigation/native";
import { useHeaderHeight } from "@react-navigation/elements";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import type { ChatStackParamList } from "../../navigation/types";
import { useSession } from "../../state/session-context";
import { buildThreads, getThreadMessages } from "./chat-utils";
import { useI18n } from "../../i18n";
import { useTheme } from "../../theme";
import type { AppTheme } from "../../theme";
import EmpOverlay from "../../components/EmpOverlay";

function formatTime(value: number) {
  return new Date(value).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
}

export default function ChatThreadScreen() {
  const manager = useSession();
  const route = useRoute<RouteProp<ChatStackParamList, "ChatThread">>();
  const [message, setMessage] = useState("");
  const listRef = useRef<FlatList>(null);
  const headerHeight = useHeaderHeight();
  const insets = useSafeAreaInsets();
  const keyboardOffset = Platform.OS === "ios" ? headerHeight : 0;
  const { t } = useI18n();
  const theme = useTheme();
  const styles = useMemo(() => createStyles(theme), [theme]);
  const placeholderColor = theme.colors.placeholder;

  if (!manager.session || !manager.me) {
    return (
      <View style={styles.container}>
        <Text style={styles.helper}>{t("common.loadingChat")}</Text>
      </View>
    );
  }

  const threads = buildThreads(manager.session, manager.me.id, manager.isBanker);
  const thread = threads.find((item) => item.id === route.params.chatId);
  const messages = thread ? getThreadMessages(manager.session, thread.id) : [];
  const threadKindLabel = thread
    ? thread.kind === "global"
      ? t("chat.global")
      : thread.kind === "direct"
      ? t("chat.direct")
      : t("chat.group")
    : "";

  if (!thread) {
    return (
      <View style={styles.container}>
        <Text style={styles.helper}>{t("chat.notFound")}</Text>
      </View>
    );
  }
  const activeThread = thread;
  const showEmp = manager.session.blackoutActive && !manager.isBanker;

  function handleSend() {
    if (showEmp) return;
    if (!message.trim()) return;
    manager.sendMessage({
      type: "chat_send",
      sessionId: manager.sessionId,
      playerId: manager.me?.id,
      body: message.trim(),
      groupId: activeThread.id === "global" ? null : activeThread.id,
    });
    setMessage("");
  }

  return (
    <View style={styles.wrapper}>
      <KeyboardAvoidingView
        style={styles.container}
        behavior={Platform.OS === "ios" ? "padding" : undefined}
        keyboardVerticalOffset={keyboardOffset}
      >
        <View style={styles.header}>
          <Text style={styles.headerTitle}>{activeThread.name}</Text>
          <Text style={styles.headerSubtitle}>{threadKindLabel}</Text>
        </View>

        <FlatList
          ref={listRef}
          data={messages}
          keyExtractor={(item) => item.id}
          contentContainerStyle={styles.list}
          keyboardShouldPersistTaps="handled"
          onContentSizeChange={() => listRef.current?.scrollToEnd({ animated: true })}
          renderItem={({ item }) => {
            const isMe = item.fromId === manager.me?.id;
            return (
              <View style={[styles.bubbleRow, isMe ? styles.bubbleRowMe : null]}>
                <View style={[styles.bubble, isMe ? styles.bubbleMe : null]}>
                  <Text style={styles.bubbleText}>{item.body}</Text>
                  <Text style={styles.bubbleTime}>{formatTime(item.createdAt)}</Text>
                </View>
              </View>
            );
          }}
        />

        <View style={[styles.composer, { paddingBottom: Math.max(insets.bottom, 8) }]}>
          <TextInput
            style={styles.input}
            placeholder={t("chat.messagePlaceholder")}
            placeholderTextColor={placeholderColor}
            value={message}
            onChangeText={setMessage}
            returnKeyType="send"
            onSubmitEditing={handleSend}
            blurOnSubmit={false}
          />
          <TouchableOpacity
            style={styles.sendButton}
            onPress={handleSend}
          >
            <Text style={styles.sendText}>{t("common.send")}</Text>
          </TouchableOpacity>
        </View>
      </KeyboardAvoidingView>
      <EmpOverlay visible={showEmp} reason={manager.session.blackoutReason} />
    </View>
  );
}

const createStyles = (theme: AppTheme) =>
  StyleSheet.create({
    wrapper: {
      flex: 1,
      position: "relative",
    },
    container: {
      flex: 1,
      backgroundColor: theme.colors.background,
    },
    header: {
      padding: 16,
      borderBottomWidth: 1,
      borderBottomColor: theme.colors.borderMuted,
      backgroundColor: theme.colors.surface,
    },
    headerTitle: {
      fontSize: 18,
      fontWeight: "700",
      color: theme.colors.text,
    },
    headerSubtitle: {
      color: theme.colors.textMuted,
      fontSize: 12,
      marginTop: 4,
    },
    list: {
      padding: 16,
      gap: 10,
    },
    bubbleRow: {
      flexDirection: "row",
      justifyContent: "flex-start",
    },
    bubbleRowMe: {
      justifyContent: "flex-end",
    },
    bubble: {
      maxWidth: "75%",
      backgroundColor: theme.colors.surface,
      padding: 10,
      borderRadius: 16,
    },
    bubbleMe: {
      backgroundColor: theme.colors.bubbleMe,
    },
    bubbleText: {
      fontSize: 14,
      color: theme.colors.text,
    },
    bubbleTime: {
      fontSize: 10,
      color: theme.colors.textMuted,
      marginTop: 6,
      textAlign: "right",
    },
    composer: {
      flexDirection: "row",
      padding: 12,
      gap: 10,
      borderTopWidth: 1,
      borderTopColor: theme.colors.borderMuted,
      backgroundColor: theme.colors.surface,
    },
    input: {
      flex: 1,
      borderWidth: 1,
      borderColor: theme.colors.border,
      backgroundColor: theme.colors.inputBackground,
      color: theme.colors.inputText,
      borderRadius: 999,
      paddingHorizontal: 12,
      paddingVertical: 8,
    },
    sendButton: {
      backgroundColor: theme.colors.primary,
      borderRadius: 999,
      paddingHorizontal: 16,
      justifyContent: "center",
    },
    sendText: {
      color: theme.colors.primaryText,
      fontWeight: "600",
    },
    helper: {
      color: theme.colors.textMuted,
    },
  });
