import React, { useMemo } from "react";
import {
  FlatList,
  Pressable,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import { useNavigation } from "@react-navigation/native";
import type { NativeStackNavigationProp } from "@react-navigation/native-stack";
import type { ChatStackParamList } from "../../navigation/types";
import { useSession } from "../../state/session-context";
import { buildThreads } 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 | null) {
  if (!value) return "";
  return new Date(value).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
}

export default function ChatListScreen() {
  const manager = useSession();
  const navigation = useNavigation<NativeStackNavigationProp<ChatStackParamList>>();
  const { t } = useI18n();
  const theme = useTheme();
  const styles = useMemo(() => createStyles(theme), [theme]);

  const threads = useMemo(() => {
    if (!manager.session) return [];
    return buildThreads(manager.session, manager.me?.id ?? null, manager.isBanker);
  }, [manager.session, manager.me, manager.isBanker]);

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

  return (
    <View style={styles.container}>
      <Text style={styles.title}>{t("chat.title")}</Text>
      <FlatList
        data={threads}
        keyExtractor={(item) => item.id}
        contentContainerStyle={styles.list}
        renderItem={({ item }) => (
          <Pressable
            style={styles.listItem}
            onPress={() => navigation.navigate("ChatThread", { chatId: item.id })}
          >
            <View style={styles.avatar}>
              <Text style={styles.avatarText}>
                {item.kind === "global" ? "#" : item.name.charAt(0).toUpperCase()}
              </Text>
            </View>
            <View style={styles.meta}>
              <View style={styles.metaRow}>
                <Text style={styles.name}>{item.name}</Text>
                <Text style={styles.time}>{formatTime(item.lastMessage?.createdAt)}</Text>
              </View>
              <Text style={styles.preview}>
                {item.lastMessage?.body ?? t("chat.noMessages")}
              </Text>
            </View>
          </Pressable>
        )}
      />

      <TouchableOpacity
        style={styles.fab}
        onPress={() => navigation.navigate("ChatNew")}
      >
        <Text style={styles.fabText}>+</Text>
      </TouchableOpacity>
      <EmpOverlay visible={showEmp} reason={manager.session.blackoutReason} />
    </View>
  );
}

const createStyles = (theme: AppTheme) =>
  StyleSheet.create({
    container: {
      flex: 1,
      padding: 20,
      backgroundColor: theme.colors.background,
      position: "relative",
    },
    title: {
      fontSize: 20,
      fontWeight: "700",
      marginBottom: 16,
      color: theme.colors.text,
    },
    list: {
      gap: 12,
      paddingBottom: 80,
    },
    listItem: {
      backgroundColor: theme.colors.surface,
      borderRadius: 16,
      padding: 12,
      flexDirection: "row",
      alignItems: "center",
      gap: 12,
    },
    avatar: {
      width: 44,
      height: 44,
      borderRadius: 16,
      backgroundColor: theme.colors.listAvatarBackground,
      justifyContent: "center",
      alignItems: "center",
    },
    avatarText: {
      fontWeight: "700",
      color: theme.colors.listAvatarText,
    },
    meta: {
      flex: 1,
    },
    metaRow: {
      flexDirection: "row",
      justifyContent: "space-between",
      alignItems: "center",
    },
    name: {
      fontWeight: "600",
      color: theme.colors.text,
    },
    time: {
      fontSize: 12,
      color: theme.colors.textMuted,
    },
    preview: {
      color: theme.colors.textMuted,
      marginTop: 4,
    },
    helper: {
      color: theme.colors.textMuted,
    },
    fab: {
      position: "absolute",
      right: 20,
      bottom: 24,
      width: 52,
      height: 52,
      borderRadius: 26,
      backgroundColor: theme.colors.primary,
      alignItems: "center",
      justifyContent: "center",
    },
    fabText: {
      color: theme.colors.primaryText,
      fontSize: 26,
      fontWeight: "700",
    },
  });
