import { FontAwesome, FontAwesome5 } from '@expo/vector-icons';
import { useNavigation } from '@react-navigation/native';
import React from 'react';
import { View, Text } from 'react-native';

import IconButton from '../../../../components/Button/IconButton';
import ClickableList from '../../../../components/List/ClickableList';
import Title from '../../../../components/List/components/Title';
import Loader from '../../../../components/Loader/Loader';
import { NavProps } from '../../../../components/Routes/Routes';
import { getDateAsString } from '../../../../helpers/stringHelpers';
import { useMessages } from '../../../../hooks/useMessage';
import { useUserInfo } from '../../../../hooks/useStorage';

const RecentMessages = () => {
  const [userInfo] = useUserInfo();
  const navigation = useNavigation<NavProps>();

  const {
    data: messages,
    isFetching: isMessagesLoading,
    refetch: refetchMessages,
  } = useMessages(userInfo.token);

  const recentMessages = messages?.filter(msg => !msg.isRead).slice(0, 3);

  return (
    <>
      <View className="flex-row items-center justify-between">
        <Title text="Poslední zprávy" />

        <View className="flex-row space-x-2">
          <View>
            <IconButton variant="secondary" onPress={() => refetchMessages()}>
              <FontAwesome name="repeat" size={24} />
            </IconButton>
          </View>

          <View>
            <IconButton variant="secondary" onPress={() => navigation.navigate('MessageList')}>
              <FontAwesome5 name="inbox" size={24} />
            </IconButton>
          </View>
        </View>
      </View>
      {!isMessagesLoading ? (
        <View className="mt-4">
          <ClickableList
            items={recentMessages?.map(msg => {
              return {
                title: msg.header,
                subtitle: msg.group,
                info: getDateAsString(msg.created, true),
                onPress: () => navigation.navigate('MessageDetail', { id: msg.id }),
              };
            })}
            emptyElement={
              <Text className="rounded bg-secondary-bg p-4">
                Nebyly nalezeny žádné nepřečtené zprávy.
              </Text>
            }
          />
        </View>
      ) : (
        <Loader />
      )}
    </>
  );
};

export default RecentMessages;
