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

import { ClickableFlatList } from '../../../../components/List/ClickableList';
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 MessageList = () => {
  const navigation = useNavigation<NavProps>();
  const [userInfo] = useUserInfo();

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

  return (
    <View className="mx-4 mb-4 flex-1 bg-primary-bg">
      {!isMessagesFetching ? (
        <ClickableFlatList
          items={messages?.map(msg => {
            return {
              title: msg.header,
              subtitle: msg.group,
              info: getDateAsString(msg.created, true),
              icon: <FontAwesome name={`envelope${msg.isRead ? '-o' : ''}`} size={24} />,
              onPress: () => navigation.navigate('MessageDetail', { id: msg.id }),
            };
          })}
          emptyElement={
            <Text className="rounded bg-secondary-bg p-4">Nebyly nalezeny žádné zprávy.</Text>
          }
          refreshControl={
            <RefreshControl refreshing={isMessagesFetching} onRefresh={refetchMessages} />
          }
        />
      ) : (
        <Loader />
      )}
    </View>
  );
};

export default MessageList;
