import React, { useEffect, useMemo, useState } from 'react';
import { FlatList, Image, StyleSheet, TouchableOpacity, View } from 'react-native';
import { ThemedText } from '../../components/themed-text';
import { ThemedView } from '../../components/themed-view';
import { IconSymbol } from '../../components/ui/icon-symbol';
import { Separator } from '../../components/ui/separator';
import { useApi } from '../../lib/network/api';
import { useThemeColor } from '../../lib/hooks/use-theme-color';
import { useChatStore } from '../../lib/stores/chats';
import { getChannelName, Message, PrivateChannel } from '../../lib/types/discord';
import { useNavigation } from '@react-navigation/native';

const getMessagePreview = (msg?: Message) => {
  if (!msg) return "No messages yet";
  if (!msg.content || msg.content.trim() === "") return "(Attachment)";
  return msg.content;
};

export default function Chats() {
  const api = useApi();
  const navigation = useNavigation();

  const iconColor = useThemeColor("secondary");
  const [isLoading, setIsLoading] = useState(true);

  const privateChannels = useChatStore((s) => s.privateChannels)
  const messages = useChatStore((s) => s.messages);

  const sortedChannels = useMemo(() => {
    return Object.values(privateChannels).sort((a, b) => {
      const aLastMsg = messages[a.id]?.[0]?.timestamp
        ? new Date(messages[a.id][0].timestamp).getTime()
        : 0;
      const bLastMsg = messages[b.id]?.[0]?.timestamp
        ? new Date(messages[b.id][0].timestamp).getTime()
        : 0;
      return bLastMsg - aLastMsg;
    });
  }, [privateChannels, messages]);

  useEffect(() => {
    let isMounted = true;

    async function init() {
      const promises = Object.values(privateChannels).map((p) =>
        api.populateMessages(p.id, { limit: 1 })
      );
      await Promise.all(promises);
      if (isMounted) setIsLoading(false);
    }

    if (Object.keys(privateChannels).length > 0) {
      init();
    }

    return () => {
      isMounted = false;
    };
  }, [privateChannels]);

  const renderDM = ({ item }: { item: PrivateChannel }) => {
    const channelMessages = messages[item.id] ?? [];
    return (
      <TouchableOpacity
        onPress={() => navigation.navigate("Conversation", { id: item.id })}
        activeOpacity={0.7}
        style={styles.dmContainer}
      >
        <Image
          style={styles.avatar}
          source={api.getAvatarUrl(item.recipients[0].id, item.recipients[0].avatar)}
        />
        <View style={{ marginLeft: 12, flex: 1 }}>
          <ThemedText type="subtitle">{getChannelName(item)}</ThemedText>
          <ThemedText
            type="default"
            numberOfLines={1}
            ellipsizeMode="tail"
            style={{ opacity: 0.6, maxWidth: "100%" }}
          >
            {getMessagePreview(channelMessages[0])}
          </ThemedText>
        </View>
        <IconSymbol name="chevron-right" size={40} color={iconColor} style={{ marginLeft: "auto" }} />
      </TouchableOpacity>
    );
  };

  return (
    <ThemedView style={styles.container}>
      <ThemedText type="title">Chats</ThemedText>
      {!isLoading ? <FlatList
        data={sortedChannels}
        keyExtractor={(item) => item.id}
        renderItem={renderDM}
        style={{ marginTop: 10 }}
        ItemSeparatorComponent={() => <Separator thickness={1} />}
      /> : null}
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    marginTop: 10
  },
  avatar: {
    width: 55,
    height: 55,
    borderRadius: 1000,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 6 },
    shadowOpacity: 0.25,
    shadowRadius: 12,
  },
  dmContainer: {
    paddingTop: 15,
    paddingBottom: 15,
    marginBottom: 5,
    display: "flex",
    flexDirection: "row",
    alignItems: "center"
  }
});
