import React from 'react';
import { Screens, TabStacks } from '../../../types/navigators';
import { getCredentialForDisplay } from '../display';
import { SafeAreaView } from 'react-native-safe-area-context';
import CommonRemoveModal from '../../../components/modals/CommonRemoveModal';
import { ModalUsage } from '../../../types/remove';
import { useState } from 'react';
import { DeviceEventEmitter, FlatList, StyleSheet, Text, View } from 'react-native';
import { TextTheme } from '../../../theme';
import { useTranslation } from 'react-i18next';
import Button, { ButtonType } from '../../../components/buttons/Button';
import { testIdWithKey } from '../../../utils/testable';
import RecordHeader from '../../../components/record/RecordHeader';
import RecordFooter from '../../../components/record/RecordFooter';
import { useTheme } from '../../../contexts/theme';
import OpenIDCredentialCard from '../components/OpenIDCredentialCard';
import { buildFieldsFromOpenIDTemplate } from '../utils/utils';
import RecordField from '../../../components/record/RecordField';
import { BifoldError } from '../../../types/error';
import { EventTypes } from '../../../constants';
import { useAgent } from '@credo-ts/react-hooks';
import CredentialOfferAccept from '../../../screens/CredentialOfferAccept';
import RecordRemove from '../../../components/record/RecordRemove';
import { useOpenIDCredentials } from '../context/OpenIDCredentialRecordProvider';
export let OpenIDCredScreenMode = /*#__PURE__*/function (OpenIDCredScreenMode) {
  OpenIDCredScreenMode[OpenIDCredScreenMode["offer"] = 0] = "offer";
  OpenIDCredScreenMode[OpenIDCredScreenMode["details"] = 1] = "details";
  return OpenIDCredScreenMode;
}({});
const OpenIDCredentialDetails = ({
  navigation,
  route
}) => {
  // FIXME: change params to accept credential id to avoid 'non-serializable' warnings
  const {
    credential,
    screenMode
  } = route.params;
  const credentialDisplay = getCredentialForDisplay(credential);
  const {
    display,
    attributes
  } = credentialDisplay;
  const fields = buildFieldsFromOpenIDTemplate(attributes);
  const {
    t
  } = useTranslation();
  const {
    ColorPallet
  } = useTheme();
  const {
    agent
  } = useAgent();
  const {
    storeCredential,
    removeCredential
  } = useOpenIDCredentials();
  const [isRemoveModalDisplayed, setIsRemoveModalDisplayed] = useState(false);
  const [buttonsVisible, setButtonsVisible] = useState(true);
  const [acceptModalVisible, setAcceptModalVisible] = useState(false);
  const styles = StyleSheet.create({
    headerTextContainer: {
      paddingHorizontal: 25,
      paddingVertical: 16
    },
    headerText: {
      ...TextTheme.normal,
      flexShrink: 1
    },
    footerButton: {
      paddingTop: 10
    }
  });
  const toggleDeclineModalVisible = () => setIsRemoveModalDisplayed(!isRemoveModalDisplayed);
  const handleDeclineTouched = async () => {
    var _navigation$getParent;
    toggleDeclineModalVisible();
    if (screenMode === OpenIDCredScreenMode.offer) (_navigation$getParent = navigation.getParent()) === null || _navigation$getParent === void 0 || _navigation$getParent.navigate(TabStacks.HomeStack, {
      screen: Screens.Home
    });else handleRemove();
  };
  const handleAcceptTouched = async () => {
    try {
      if (!agent) {
        return;
      }
      await storeCredential(credential);
      setAcceptModalVisible(true);
    } catch (err) {
      setButtonsVisible(true);
      const error = new BifoldError(t('Error.Title1024'), t('Error.Message1024'), (err === null || err === void 0 ? void 0 : err.message) ?? err, 1024);
      DeviceEventEmitter.emit(EventTypes.ERROR_ADDED, error);
    }
  };
  const handleRemove = async () => {
    try {
      await removeCredential(credential);
      navigation.pop();
    } catch (err) {
      const error = new BifoldError(t('Error.Title1025'), t('Error.Message1025'), (err === null || err === void 0 ? void 0 : err.message) ?? err, 1025);
      DeviceEventEmitter.emit(EventTypes.ERROR_ADDED, error);
    }
  };
  const footerButton = (title, buttonPress, buttonType, testID, accessibilityLabel) => {
    return /*#__PURE__*/React.createElement(View, {
      style: styles.footerButton
    }, /*#__PURE__*/React.createElement(Button, {
      title: title,
      accessibilityLabel: accessibilityLabel,
      testID: testID,
      buttonType: buttonType,
      onPress: buttonPress,
      disabled: !buttonsVisible
    }));
  };
  const header = () => {
    return /*#__PURE__*/React.createElement(React.Fragment, null, screenMode === OpenIDCredScreenMode.offer && /*#__PURE__*/React.createElement(View, {
      style: styles.headerTextContainer
    }, /*#__PURE__*/React.createElement(Text, {
      style: styles.headerText,
      testID: testIdWithKey('HeaderText')
    }, /*#__PURE__*/React.createElement(Text, null, display.issuer.name || t('ContactDetails.AContact')), ' ', t('CredentialOffer.IsOfferingYouACredential'))), credential && /*#__PURE__*/React.createElement(View, {
      style: {
        marginHorizontal: 15,
        marginBottom: 16
      }
    }, /*#__PURE__*/React.createElement(OpenIDCredentialCard, {
      credentialDisplay: display
    })));
  };
  const footer = () => {
    const paddingHorizontal = 24;
    const paddingVertical = 16;
    const paddingBottom = 26;
    return /*#__PURE__*/React.createElement(View, {
      style: {
        marginBottom: 50
      }
    }, screenMode === OpenIDCredScreenMode.offer ? /*#__PURE__*/React.createElement(View, {
      style: {
        paddingHorizontal: paddingHorizontal,
        paddingVertical: paddingVertical,
        paddingBottom: paddingBottom,
        backgroundColor: ColorPallet.brand.secondaryBackground
      }
    }, footerButton(t('Global.Accept'), handleAcceptTouched, ButtonType.Primary, testIdWithKey('AcceptCredentialOffer'), t('Global.Accept')), footerButton(t('Global.Decline'), toggleDeclineModalVisible, ButtonType.Secondary, testIdWithKey('DeclineCredentialOffer'), t('Global.Decline'))) : /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(View, {
      style: {
        backgroundColor: ColorPallet.brand.secondaryBackground,
        marginTop: paddingVertical,
        paddingHorizontal,
        paddingVertical
      }
    }, /*#__PURE__*/React.createElement(Text, {
      testID: testIdWithKey('IssuerName')
    }, /*#__PURE__*/React.createElement(Text, {
      style: [TextTheme.title]
    }, t('CredentialDetails.IssuedBy') + ' '), /*#__PURE__*/React.createElement(Text, {
      style: [TextTheme.normal]
    }, display.issuer.name || t('ContactDetails.AContact')))), /*#__PURE__*/React.createElement(RecordRemove, {
      onRemove: toggleDeclineModalVisible
    })));
  };
  const body = () => {
    return /*#__PURE__*/React.createElement(FlatList, {
      data: fields,
      keyExtractor: ({
        name
      }, index) => name || index.toString(),
      renderItem: ({
        item: attr,
        index
      }) => /*#__PURE__*/React.createElement(RecordField, {
        field: attr,
        hideFieldValue: false,
        shown: true,
        hideBottomBorder: index === fields.length - 1
      }),
      ListHeaderComponent: /*#__PURE__*/React.createElement(RecordHeader, null, header()),
      ListFooterComponent: footer ? /*#__PURE__*/React.createElement(RecordFooter, null, footer()) : null
    });
  };
  const screenEdges = screenMode === OpenIDCredScreenMode.offer ? ['bottom', 'left', 'right'] : ['left', 'right'];
  return /*#__PURE__*/React.createElement(SafeAreaView, {
    style: {
      flexGrow: 1
    },
    edges: screenEdges
  }, body(), screenMode === OpenIDCredScreenMode.offer && /*#__PURE__*/React.createElement(CredentialOfferAccept, {
    visible: acceptModalVisible,
    credentialId: '',
    confirmationOnly: true
  }), /*#__PURE__*/React.createElement(CommonRemoveModal, {
    usage: screenMode === OpenIDCredScreenMode.offer ? ModalUsage.CredentialOfferDecline : ModalUsage.CredentialRemove,
    visible: isRemoveModalDisplayed,
    onSubmit: handleDeclineTouched,
    onCancel: toggleDeclineModalVisible
  }));
};
export default OpenIDCredentialDetails;
//# sourceMappingURL=OpenIDCredentialOffer.js.map