"use strict";

import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { CenterContainer, UserInfo, UserName, ModalContainerFullScreen, ActionButton, Label, BorderedContainer, LabelData, ModalBackground, ModalContainer, CloseButton, ModalTitle, GroupContainer } from '../styledModalComponents';
import { ChatIcon, DeleteIcon, EditIcon, IconDoc, LeaveIcon, MoreIcon } from '../../../assets/icons';
import ModalHeaderComponent from '../ModalHeaderComponent';
import { ProfileImagePlaceholder } from '../../MainComponents/ProfileImagePlaceholder';
import Button from '../../styled/Button';
import DropdownMenu from '../../DropdownMenu/DropdownMenu';
import { logout, setActiveModal, setLangSource, setSelectedUser } from '../../../roomStore/chatSettingsSlice';
import { addRoomViaApi, setCurrentRoom, setLogoutState } from '../../../roomStore/roomsSlice';
import EditUserModal from './EditUserModal';
import { walletToUsername } from '../../../helpers/walletUsername';
import { useXmppClient } from '../../../context/xmppProvider';
import Select from '../../MainComponents/Select';
import { useAppDispatch } from '../../../hooks/hooks';
import { ScrollView, Text, View } from 'react-native';
import { postPrivateRoom } from '../../../networking/api-requests/rooms.api';
import { createRoomFromApi } from '../../../helpers/createRoomFromApi';
import { useToast } from '../../../context/ToastContext';
import { LANGUAGE_OPTIONS } from '../../../helpers/constants/LANGUAGE_OPTIONS';
import { deleteDocument, getDocuments } from '../../../networking/api-requests/user.api';
import { useChatSettingState } from '../../../hooks/useChatSettingState';
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
const UserProfileModal = ({
  handleCloseModal
}) => {
  const dispatch = useAppDispatch();
  const {
    client
  } = useXmppClient();
  const {
    showToast
  } = useToast();
  const {
    config,
    user,
    selectedUser,
    langSource
  } = useChatSettingState();
  const [isEditing, setIsEditing] = useState(false);
  const [documents, setDocuments] = useState([]);
  const [deleteDocumentId, setDeleteDocumentId] = useState('');
  const [showDelete, setShowDelete] = useState(false);
  const handleDeleteDocument = async () => {
    try {
      await deleteDocument(deleteDocumentId);
      setDocuments(documents.filter(doc => doc._id !== deleteDocumentId));
      showToast({
        id: Date.now().toString(),
        title: 'Success',
        message: 'Document deleted successfully',
        type: 'success'
      });
      // handleGetDocs();
    } catch (error) {
      console.error('Error deleting document', error);
      showToast({
        id: Date.now().toString(),
        title: 'Error',
        message: 'Failed to delete document',
        type: 'error'
      });
    } finally {
      setShowDelete(false);
    }
  };
  const handleGetDocs = async () => {
    try {
      const {
        data
      } = await getDocuments(user?.defaultWallet?.walletAddress);
      const items = data.results.filter(el => el.locations[0]);
      setDocuments(items);
    } catch (error) {
      console.error('Error getting docs', error);
    }
  };
  useEffect(() => {
    handleGetDocs();
  }, []);
  const handleBackClick = useCallback(() => {
    dispatch(setSelectedUser(undefined));
    handleCloseModal();
  }, []);
  const handleLogout = useCallback(() => {
    dispatch(logout());
    dispatch(setLogoutState());
  }, []);
  const menuOptions = useMemo(() => [{
    label: 'Log Out',
    icon: /*#__PURE__*/_jsx(LeaveIcon, {}),
    onClick: () => {
      handleLogout();
    },
    styles: {
      color: 'red'
    }
  }], []);
  const handleSelect = selected => {
    dispatch(setLangSource(selected.id));
  };
  const EditClick = useCallback(() => {
    setIsEditing(true);
  }, []);
  const handleRoomCreation = async (newChat, usersArrayLength) => {
    try {
      const normalizedChat = createRoomFromApi(newChat, config?.xmppSettings?.conference, usersArrayLength);
      if (!normalizedChat || !client) return;
      dispatch(addRoomViaApi({
        room: normalizedChat,
        xmpp: client
      }));
      dispatch(setCurrentRoom({
        roomJID: normalizedChat?.jid || ''
      }));
      showToast({
        id: Date.now().toString(),
        title: 'Success!',
        message: 'Room created succusfully!',
        type: 'success',
        duration: 3000
      });
    } catch (error) {
      console.error('Error handling room creation:', error);
    }
  };
  const handlePrivateMessage = useCallback(async () => {
    showToast({
      id: Date.now().toString(),
      title: 'Room creation',
      message: 'Room is being created...',
      type: 'info',
      duration: 3000
    });
    let newRoomJid = '';
    if (config?.newArch) {
      const newRoom = await postPrivateRoom(selectedUser?.userJID ?? (selectedUser?.id || ''));
      handleRoomCreation(newRoom, 2);
      newRoomJid = newRoom.name;
    } else {
      const selectedUserUsername = walletToUsername(selectedUser?.id || '');
      const myUsername = walletToUsername(user.defaultWallet.walletAddress);
      const combinedWalletAddress = [myUsername, selectedUserUsername].sort().join('.');
      const roomJid = combinedWalletAddress.toLowerCase();
      const combinedUsersName = [user.firstName, selectedUser?.name?.split(' ')?.[0] || ''].sort().join(' and ');
      newRoomJid = (await client?.createPrivateRoomStanza(combinedUsersName, `Private chat ${combinedUsersName}`, roomJid)) || '';
      if (newRoomJid) {
        await client?.inviteRoomRequestStanza(selectedUserUsername, newRoomJid);
        await client?.getRoomsStanza();
      }
    }
    dispatch(setActiveModal(undefined));
  }, [selectedUser]);
  const modalUser = selectedUser ?? user;
  const findLanguage = () => {
    if (!langSource) {
      return null;
    }
    const language = LANGUAGE_OPTIONS.find(lang => lang.id === langSource);
    return language || null;
  };
  const showDeleteModal = docId => {
    setDeleteDocumentId(docId);
    setShowDelete(true);
  };
  const DefaultBody = useMemo(() => /*#__PURE__*/_jsxs(_Fragment, {
    children: [/*#__PURE__*/_jsx(ModalHeaderComponent, {
      handleCloseModal: handleBackClick,
      headerTitle: 'Profile',
      rightMenu: !selectedUser && /*#__PURE__*/_jsxs(_Fragment, {
        children: [/*#__PURE__*/_jsx(Button, {
          onPress: EditClick,
          children: /*#__PURE__*/_jsx(EditIcon, {
            color: "#8C8C8C"
          })
        }), /*#__PURE__*/_jsx(DropdownMenu, {
          options: menuOptions,
          position: "right",
          menuIcon: /*#__PURE__*/_jsx(MoreIcon, {})
        })]
      })
    }), /*#__PURE__*/_jsxs(CenterContainer, {
      children: [/*#__PURE__*/_jsx(ProfileImagePlaceholder, {
        icon: modalUser?.profileImage ?? null,
        name: modalUser?.name ?? modalUser?.firstName,
        size: 120
      }), /*#__PURE__*/_jsx(UserInfo, {
        children: /*#__PURE__*/_jsx(UserName, {
          children: modalUser?.name ? `${modalUser?.name}` : `${modalUser?.firstName} ${modalUser?.lastName}`
        })
      }), !selectedUser && config?.translates?.enabled && /*#__PURE__*/_jsx(BorderedContainer, {
        children: /*#__PURE__*/_jsx(Select, {
          options: LANGUAGE_OPTIONS,
          placeholder: 'Select your language',
          onSelect: handleSelect,
          accentColor: config?.colors?.primary,
          selectedValue: findLanguage()
        })
      }), /*#__PURE__*/_jsxs(BorderedContainer, {
        children: [/*#__PURE__*/_jsx(Label, {
          children: "About"
        }), /*#__PURE__*/_jsx(LabelData, {
          children: modalUser?.description && modalUser?.description?.length > 4 ? modalUser.description : 'No description'
        })]
      }), selectedUser && /*#__PURE__*/_jsxs(_Fragment, {
        children: [/*#__PURE__*/_jsx(ActionButton, {
          StartIcon: /*#__PURE__*/_jsx(ChatIcon, {}),
          onPress: handlePrivateMessage,
          variant: "filled",
          children: /*#__PURE__*/_jsx(Text, {
            style: {
              color: '#ffffff'
            },
            children: "Message"
          })
        }), /*#__PURE__*/_jsx(ActionButton, {
          onPress: () => {}
          // onPress={() => handleCopyClick(selectedUser.id)}
          ,
          variant: "filled",
          children: /*#__PURE__*/_jsx(Text, {
            style: {
              color: '#ffffff'
            },
            children: "Copy User Id"
          })
        })]
      }), /*#__PURE__*/_jsx(BorderedContainer, {
        children: /*#__PURE__*/_jsx(ScrollView, {
          style: {
            maxHeight: 400
          },
          showsVerticalScrollIndicator: true,
          nestedScrollEnabled: true,
          children: documents.map(doc => /*#__PURE__*/_jsxs(View, {
            style: {
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
              gap: 24,
              backgroundColor: '#F3F6FC',
              marginBottom: 8,
              paddingVertical: 8,
              paddingHorizontal: 16,
              borderRadius: 8
            },
            children: [/*#__PURE__*/_jsxs(View, {
              style: {
                flexDirection: 'row',
                alignItems: 'center',
                gap: 24
              },
              children: [/*#__PURE__*/_jsx(View, {
                children: /*#__PURE__*/_jsx(IconDoc, {})
              }), /*#__PURE__*/_jsxs(View, {
                children: [/*#__PURE__*/_jsx(Label, {
                  style: {
                    paddingBottom: 4
                  },
                  children: doc.documentName
                }), /*#__PURE__*/_jsx(LabelData, {
                  children: new Date(doc.createdAt).toLocaleDateString('en-GB', {
                    day: '2-digit',
                    month: 'short',
                    year: 'numeric'
                  }) + ' ' + new Date(doc.createdAt).toLocaleTimeString('en-GB', {
                    hour: '2-digit',
                    minute: '2-digit'
                  })
                })]
              })]
            }), /*#__PURE__*/_jsx(Button, {
              onPress: () => showDeleteModal(doc._id),
              children: /*#__PURE__*/_jsx(DeleteIcon, {})
            })]
          }, doc._id))
        })
      })]
    })]
  }), [modalUser, documents]);
  const EditingBody = useMemo(() => /*#__PURE__*/_jsx(EditUserModal, {
    setIsEditing: setIsEditing,
    modalUser: modalUser,
    config: config
  }), [modalUser]);
  return /*#__PURE__*/_jsxs(_Fragment, {
    children: [/*#__PURE__*/_jsx(ModalContainerFullScreen, {
      children: !isEditing ? DefaultBody : EditingBody
    }), showDelete && /*#__PURE__*/_jsx(ModalBackground, {
      style: {
        position: 'absolute',
        zIndex: 9999
      },
      children: /*#__PURE__*/_jsxs(ModalContainer, {
        children: [/*#__PURE__*/_jsx(CloseButton, {
          onPress: () => setShowDelete(false),
          children: /*#__PURE__*/_jsx(Text, {
            style: {
              fontSize: 24
            },
            children: "\xD7"
          })
        }), /*#__PURE__*/_jsx(ModalTitle, {
          children: "Delete this document?"
        }), /*#__PURE__*/_jsxs(GroupContainer, {
          children: [/*#__PURE__*/_jsx(Button, {
            onPress: () => setShowDelete(false),
            text: 'Cancel',
            style: {
              width: '100%'
            },
            unstyled: true,
            variant: "filled",
            color: "white"
          }), /*#__PURE__*/_jsx(Button, {
            onPress: handleDeleteDocument,
            text: 'Delete',
            style: {
              width: '100%',
              borderWidth: 1,
              borderColor: 'red'
            },
            color: "red",
            unstyled: true,
            variant: "outlined"
          })]
        })]
      })
    })]
  });
};
export default UserProfileModal;
//# sourceMappingURL=UserProfileModal.js.map