import { StatusBar } from "expo-status-bar";
import { useMemo, useState } from "react";
import { StyleSheet, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";

import { ConversationHeader } from "@/features/im/components/conversation-header";
import { ConversationList } from "@/features/im/components/conversation-list";
import { ConversationSearchBar } from "@/features/im/components/conversation-search-bar";
import { useConversationList } from "@/features/im/hooks/use-conversation-list";
import { useConversationSearch } from "@/features/im/hooks/use-conversation-search";
import { mockConversations } from "@/features/im/mocks/mock-conversations";
import type { ConversationItem } from "@/features/im/types/conversation";

const SYSTEM_MESSAGE_ITEM: ConversationItem = {
  id: "system-message",
  kind: "system",
  title: "系统消息",
  preview: "[系统消息]",
  timeLabel: "",
};

export default function IndexRoute() {
  const insets = useSafeAreaInsets();
  const [keyword, setKeyword] = useState("");
  const { items, isLoading, isLoggedIn } = useConversationList();

  const sourceItems = isLoggedIn ? items : mockConversations;
  const conversationItems = useMemo(
    () => [SYSTEM_MESSAGE_ITEM, ...sourceItems.filter((item) => item.kind !== "system")],
    [sourceItems]
  );
  const filteredConversations = useConversationSearch(conversationItems, keyword);
  const unreadTotal = useMemo(() => {
    const total = sourceItems.reduce((sum, item) => sum + (item.unreadCount ?? 0), 0);
    if (total <= 0) {
      return "0";
    }
    return total > 99 ? "99+" : `${total}`;
  }, [sourceItems]);

  return (
    <View style={styles.screen}>
      <StatusBar style="dark" />

      <View style={[styles.headerBlock, { paddingTop: insets.top + 8 }]}>
        <ConversationHeader totalLabel={unreadTotal} />
        <ConversationSearchBar value={keyword} onChangeText={setKeyword} />
      </View>

      <View style={styles.listBlock}>
        <ConversationList data={filteredConversations} isLoading={isLoading && isLoggedIn} />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  screen: {
    backgroundColor: "#F7F7F8",
    flex: 1,
  },
  headerBlock: {
    gap: 12,
    paddingBottom: 14,
  },
  listBlock: {
    backgroundColor: "#FFFFFF",
    borderTopColor: "#F0F1F3",
    borderTopWidth: StyleSheet.hairlineWidth,
    flex: 1,
  },
});