import React, { useMemo, useState } from "react";
import {
  View,
  Text,
  FlatList,
  TouchableOpacity,
  RefreshControl,
  StyleSheet,
  SafeAreaView,
} from "react-native";
import { router } from "expo-router";
import { MessageCircle } from "lucide-react-native";
import { useThemeColor } from "@/hooks/useThemeColor";
import { useColorScheme } from "@/hooks/useColorScheme";
import { useTablosList } from "@/hooks/tablos";
import { useChatUnread } from "@/hooks/chatUnread";
import { ColorMap, PRIMARY } from "@/constants/colors";
import { UserTablo } from "@/types/tablos.types";

export default function DiscussionsTab() {
  const colorScheme = useColorScheme();
  const isDark = colorScheme === "dark";
  const bgColor = useThemeColor({ light: "#f8fafc", dark: "#111827" }, "background");
  const textColor = useThemeColor({ light: "#1f2937", dark: "#f9fafb" }, "text");
  const subtextColor = useThemeColor({ light: "#6b7280", dark: "#9ca3af" }, "text");
  const borderColor = isDark ? "#374151" : "#e5e7eb";

  const { data: tablos, isLoading, refetch: refetchTablos } = useTablosList();
  const { getUnreadCount, refetch: refetchUnread } = useChatUnread();
  const [refreshing, setRefreshing] = useState(false);

  // Sort: unread first, then by name
  const sortedTablos = useMemo(() => {
    if (!tablos) return [];
    return [...tablos].sort((a, b) => {
      const unreadA = getUnreadCount(a.id);
      const unreadB = getUnreadCount(b.id);
      if (unreadA > 0 && unreadB === 0) return -1;
      if (unreadA === 0 && unreadB > 0) return 1;
      return (a.name ?? "").localeCompare(b.name ?? "");
    });
  }, [tablos, getUnreadCount]);

  const onRefresh = async () => {
    setRefreshing(true);
    await Promise.all([refetchTablos(), refetchUnread()]);
    setRefreshing(false);
  };

  const renderChannel = ({ item }: { item: UserTablo }) => {
    const unread = getUnreadCount(item.id);
    const tabloColor = item.color ? ColorMap[item.color] ?? PRIMARY : PRIMARY;

    return (
      <TouchableOpacity
        style={[styles.channelRow, { borderBottomColor: borderColor }]}
        onPress={() => router.push(`/channel/${item.id}`)}
        activeOpacity={0.7}
      >
        <View style={[styles.colorDot, { backgroundColor: tabloColor }]} />
        <Text
          style={[
            styles.channelName,
            { color: textColor },
            unread > 0 && styles.channelNameBold,
          ]}
          numberOfLines={1}
        >
          {item.name}
        </Text>
        {unread > 0 && (
          <View style={styles.unreadBadge}>
            <Text style={styles.unreadText}>{unread > 99 ? "99+" : unread}</Text>
          </View>
        )}
      </TouchableOpacity>
    );
  };

  if (isLoading && !tablos) {
    return (
      <SafeAreaView style={[styles.container, { backgroundColor: bgColor }]}>
        <View style={styles.centered}>
          <Text style={{ color: subtextColor }}>Chargement...</Text>
        </View>
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={[styles.container, { backgroundColor: bgColor }]}>
      <View style={[styles.header, { borderBottomColor: borderColor }]}>
        <Text style={[styles.headerTitle, { color: textColor }]}>Discussions</Text>
      </View>
      <FlatList
        data={sortedTablos}
        keyExtractor={(item) => item.id}
        renderItem={renderChannel}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
        }
        ListEmptyComponent={
          <View style={styles.centered}>
            <MessageCircle size={48} color={subtextColor} strokeWidth={1.5} />
            <Text style={[styles.emptyText, { color: subtextColor }]}>
              Aucune discussion
            </Text>
          </View>
        }
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    paddingHorizontal: 16,
    paddingVertical: 14,
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  headerTitle: {
    fontSize: 28,
    fontWeight: "800",
  },
  channelRow: {
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 14,
    paddingHorizontal: 16,
    borderBottomWidth: StyleSheet.hairlineWidth,
    gap: 12,
  },
  colorDot: {
    width: 12,
    height: 12,
    borderRadius: 6,
  },
  channelName: {
    flex: 1,
    fontSize: 16,
  },
  channelNameBold: {
    fontWeight: "700",
  },
  unreadBadge: {
    backgroundColor: PRIMARY,
    borderRadius: 10,
    minWidth: 20,
    height: 20,
    paddingHorizontal: 6,
    alignItems: "center",
    justifyContent: "center",
  },
  unreadText: {
    color: "#ffffff",
    fontSize: 11,
    fontWeight: "700",
  },
  centered: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
    paddingTop: 60,
    gap: 12,
  },
  emptyText: {
    fontSize: 16,
  },
});
