import { FontAwesome } from '@expo/vector-icons';
import { useNavigation, useRoute } from '@react-navigation/native';
import React, { useEffect, useLayoutEffect, useState } from 'react';
import { Text, View } from 'react-native';
import { WebView } from 'react-native-webview';

import IconButton from '../../../../../../components/Button/IconButton';
import Title from '../../../../../../components/List/components/Title';
import Loader from '../../../../../../components/Loader/Loader';
import ConfirmationModal from '../../../../../../components/Modal/ConfirmationModal';
import { NavProps, RouteProps } from '../../../../../../components/Routes/Routes';
import { getDateAsString } from '../../../../../../helpers/stringHelpers';
import {
  useMessageDelete,
  useMessageDetail,
  useMessages,
} from '../../../../../../hooks/useMessage';
import { useUserInfo } from '../../../../../../hooks/useStorage';

const MessageDetail = () => {
  const { id } = useRoute<RouteProps<'MessageDetail'>>().params;
  const [isModalVisible, setIsModalVisible] = useState(false);

  const [userInfo] = useUserInfo();
  const navigation = useNavigation<NavProps>();
  const { refetch: refetchMessages } = useMessages(userInfo.token, false);
  const { data: message, isLoading: isMessageLoading } = useMessageDetail(userInfo.token, id);
  const { mutate: deleteMessage } = useMessageDelete(
    userInfo.token,
    refetchMessages,
    navigation.goBack,
  );

  useEffect(() => {
    refetchMessages();
  }, [message]);

  useLayoutEffect(() => {
    navigation.setOptions({
      headerRight: () => {
        return (
          <IconButton variant="secondary" onPress={() => setIsModalVisible(true)}>
            <FontAwesome name="trash" size={28} />
          </IconButton>
        );
      },
    });
  }, []);

  return (
    <View className="m-4 flex-1 bg-primary-bg">
      <>
        {!isMessageLoading ? (
          <>
            <Title text={message?.header || ''} />
            <View className="my-2 flex-row justify-between">
              <Text className="text-sm">{message?.group}</Text>
              <Text className="text-sm">
                {message?.created && getDateAsString(message?.created, true)}
              </Text>
            </View>

            {message?.isHTML ? (
              <View className="flex-1">
                <WebView source={{ html: message?.body || '' }} scalesPageToFit={false} />
              </View>
            ) : (
              <View className="rounded bg-secondary-bg p-4">
                <Text className="mt-2">{message?.body}</Text>
              </View>
            )}
          </>
        ) : (
          <Loader />
        )}
      </>
      <ConfirmationModal
        isVisible={isModalVisible}
        setIsVisible={setIsModalVisible}
        title="Smazat zprávu"
        text="Opravdu chcete zprávu smazat?"
        onConfirm={() => {
          deleteMessage(id);
        }}
      />
    </View>
  );
};

export default MessageDetail;
