import { MaterialCommunityIcons, MaterialIcons } from '@expo/vector-icons';
import { useNavigation } from '@react-navigation/native';
import React, { useEffect, useMemo, useState } from 'react';
import { TouchableOpacity, View, Text, Image } from 'react-native';

import { NAVBAR_REQUESTS } from '../../constants/appLoading';
import { useUpdateLoadingStatus } from '../../hooks/useAppLoading';
import { usePersonPhoto } from '../../hooks/usePerson';
import { useUserInfo } from '../../hooks/useStorage';
import { useLogout, useUserDetail, useUserRoles } from '../../hooks/useUser';
import { updateQueryClient } from '../../services/reactQuery/client';
import IconButton from '../Button/IconButton';
import ConfirmationModal from '../Modal/ConfirmationModal';
import { NavProps } from '../Routes/Routes';
import UserRoleModal from './components/UserRoleModal/UserRoleModal';

const NavBar = () => {
  const navigation = useNavigation<NavProps>();
  updateQueryClient(navigation);

  const [userInfo, setUserInfo] = useUserInfo();
  const updateLoadingStatus = useUpdateLoadingStatus();

  const [isUserRoleModalVisible, setIsUserRoleModalVisible] = useState(false);
  const [isLogoutModalVisible, setIsLogoutModalVisible] = useState(false);

  const { data: userRoles, isLoading: isUserRolesLoading } = useUserRoles(
    userInfo.token,
    userInfo.userId,
  );

  const { isLoading: isUserDetailLoading } = useUserDetail(
    userInfo.token,
    userInfo.userId,
    userInfo,
    setUserInfo,
  );

  const { data: userPhoto, isLoading: isPhotoLoading } = usePersonPhoto(
    userInfo.token,
    userInfo.personId,
  );
  const { refetch: logout } = useLogout(userInfo.token);

  useEffect(() => {
    updateLoadingStatus(
      isUserRolesLoading || isUserDetailLoading || isPhotoLoading,
      NAVBAR_REQUESTS,
    );
  }, [isUserRolesLoading, isUserDetailLoading, isPhotoLoading]);

  const userRole = useMemo(
    () => userRoles?.find(r => r.id === userInfo.roleId)?.displayName || 'Neznámá role',
    [userRoles, userInfo.roleId],
  );

  const onUserPress = () => {
    navigation.navigate('PersonDetail', { id: userInfo.personId, isFromCatalog: false });
  };

  return (
    <View className="flex-row items-center justify-between pr-5">
      {!isUserRolesLoading && !isUserDetailLoading && !isPhotoLoading && (
        <>
          <View className="mr-5">
            {userPhoto?.photoContent ? (
              <TouchableOpacity onPress={onUserPress}>
                <Image
                  className="h-[38px] w-[28px]"
                  source={{ uri: `data:image/png;base64,${userPhoto?.photoContent}` }}
                />
              </TouchableOpacity>
            ) : (
              <IconButton variant="primary" onPress={onUserPress}>
                <MaterialIcons name="person" size={38} />
              </IconButton>
            )}
          </View>

          <TouchableOpacity
            className="flex-1 flex-row items-center justify-center"
            onPress={() => {
              setIsUserRoleModalVisible(true);
            }}
          >
            <Text className="text-center text-md">{userRole}</Text>
            <Text className="text-lg text-secondary">
              <MaterialIcons name="keyboard-arrow-down" size={24} />
            </Text>
          </TouchableOpacity>

          <View className="ml-5">
            <IconButton
              variant="secondary"
              onPress={() => {
                setIsLogoutModalVisible(true);
              }}
            >
              <MaterialCommunityIcons name="logout" size={32} />
            </IconButton>
          </View>
          <UserRoleModal
            userRoles={userRoles || []}
            isVisible={isUserRoleModalVisible}
            setIsVisible={setIsUserRoleModalVisible}
          />

          <ConfirmationModal
            isVisible={isLogoutModalVisible}
            setIsVisible={setIsLogoutModalVisible}
            title="Odhlášení"
            text="Opravdu se chcete odhlásit?"
            onConfirm={() => {
              navigation.replace('Landing');
              logout();
            }}
          />
        </>
      )}
    </View>
  );
};

export default NavBar;
