import { useMemo, useState } from 'react';
import { DeviceEventEmitter } from 'react-native';
import { useAgent } from '@credo-ts/react-hooks';
import { useTranslation } from 'react-i18next';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Screens, TabStacks } from '../../../types/navigators';
import { ScrollView, StyleSheet, Text, View } from 'react-native';
import { ListItems, TextTheme } from '../../../theme';
import { formatDifPexCredentialsForRequest } from '../displayProof';
import { testIdWithKey } from '../../../utils/testable';
import { sanitizeString } from '../utils/utils';
import { OpenIDCredentialRowCard } from '../components/CredentialRowCard';
import CommonRemoveModal from '../../../components/modals/CommonRemoveModal';
import { ModalUsage } from '../../../types/remove';
import Button, { ButtonType } from '../../../components/buttons/Button';
import { useTheme } from '../../../contexts/theme';
import { BifoldError } from '../../../types/error';
import { EventTypes } from '../../../constants';
import { shareProof } from '../resolverProof';
import ProofRequestAccept from '../../../screens/ProofRequestAccept';
const styles = StyleSheet.create({
  pageContent: {
    flexGrow: 1,
    justifyContent: 'space-between',
    padding: 10
  },
  credentialsList: {
    marginTop: 20,
    justifyContent: 'space-between'
  },
  headerTextContainer: {
    paddingVertical: 16
  },
  headerText: {
    ...ListItems.recordAttributeText,
    flexShrink: 1
  },
  footerButton: {
    paddingTop: 10
  }
});
const OpenIDProofPresentation = ({
  navigation,
  route: {
    params: {
      credential
    }
  }
}) => {
  //   console.log('DUMp Record:', JSON.stringify(credential))

  const [declineModalVisible, setDeclineModalVisible] = useState(false);
  const [buttonsVisible, setButtonsVisible] = useState(true);
  const [acceptModalVisible, setAcceptModalVisible] = useState(false);
  const {
    ColorPallet
  } = useTheme();
  const {
    t
  } = useTranslation();
  const {
    agent
  } = useAgent();
  const toggleDeclineModalVisible = () => setDeclineModalVisible(!declineModalVisible);
  const submission = useMemo(() => credential && credential.credentialsForRequest ? formatDifPexCredentialsForRequest(credential.credentialsForRequest) : undefined, [credential]);
  const selectedCredentials = useMemo(() => submission === null || submission === void 0 ? void 0 : submission.entries.reduce((acc, entry) => {
    if (entry.isSatisfied) {
      //TODO: Support multiplae credentials
      return {
        ...acc,
        [entry.inputDescriptorId]: entry.credentials[0].id
      };
    }
    return acc;
  }, {}), [submission]);
  const {
    verifierName
  } = useMemo(() => {
    return {
      verifierName: credential === null || credential === void 0 ? void 0 : credential.verifierHostName
    };
  }, [credential]);
  const handleAcceptTouched = async () => {
    try {
      if (!agent || !credential.credentialsForRequest || !selectedCredentials) {
        return;
      }
      await shareProof({
        agent,
        authorizationRequest: credential.authorizationRequest,
        credentialsForRequest: credential.credentialsForRequest,
        selectedCredentials
      });
      setAcceptModalVisible(true);
    } catch (err) {
      setButtonsVisible(true);
      const error = new BifoldError(t('Error.Title1027'), t('Error.Message1027'), (err === null || err === void 0 ? void 0 : err.message) ?? err, 1027);
      DeviceEventEmitter.emit(EventTypes.ERROR_ADDED, error);
    }
  };
  const handleDeclineTouched = async () => {
    var _navigation$getParent;
    toggleDeclineModalVisible();
    (_navigation$getParent = navigation.getParent()) === null || _navigation$getParent === void 0 || _navigation$getParent.navigate(TabStacks.HomeStack, {
      screen: Screens.Home
    });
  };
  const renderHeader = () => {
    return /*#__PURE__*/React.createElement(View, {
      style: styles.headerTextContainer
    }, /*#__PURE__*/React.createElement(Text, {
      style: styles.headerText,
      testID: testIdWithKey('HeaderText')
    }, /*#__PURE__*/React.createElement(Text, {
      style: TextTheme.title
    }, "You have received an information request", verifierName ? ` from ${verifierName}` : '', ".")));
  };
  const renderBody = () => {
    if (!submission) return null;
    return /*#__PURE__*/React.createElement(View, {
      style: styles.credentialsList
    }, submission.entries.map((s, i) => {
      //TODO: Support multiplae credentials
      const selectedCredential = s.credentials[0];
      return /*#__PURE__*/React.createElement(View, {
        key: i
      }, /*#__PURE__*/React.createElement(OpenIDCredentialRowCard, {
        name: s.name,
        issuer: verifierName,
        onPress: () => {}
      }), s.isSatisfied && selectedCredential !== null && selectedCredential !== void 0 && selectedCredential.requestedAttributes ? /*#__PURE__*/React.createElement(View, {
        style: {
          marginTop: 16,
          gap: 8
        }
      }, s.description && /*#__PURE__*/React.createElement(Text, {
        style: TextTheme.labelSubtitle
      }, s.description), /*#__PURE__*/React.createElement(View, {
        style: {
          flexDirection: 'row',
          flexWrap: 'wrap'
        }
      }, selectedCredential.requestedAttributes.map(a => /*#__PURE__*/React.createElement(View, {
        key: a,
        style: {
          flexBasis: '50%'
        }
      }, /*#__PURE__*/React.createElement(Text, {
        style: TextTheme.normal
      }, "\u2022 ", sanitizeString(a)))))) : /*#__PURE__*/React.createElement(Text, {
        style: TextTheme.title
      }, "This credential is not present in your wallet."));
    }));
  };
  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 footer = () => {
    return /*#__PURE__*/React.createElement(View, {
      style: {
        paddingHorizontal: 25,
        paddingVertical: 16,
        paddingBottom: 26,
        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')));
  };
  return /*#__PURE__*/React.createElement(SafeAreaView, {
    style: {
      flexGrow: 1
    },
    edges: ['bottom', 'left', 'right']
  }, /*#__PURE__*/React.createElement(ScrollView, null, /*#__PURE__*/React.createElement(View, {
    style: styles.pageContent
  }, renderHeader(), (submission === null || submission === void 0 ? void 0 : submission.purpose) && /*#__PURE__*/React.createElement(Text, {
    style: TextTheme.labelSubtitle
  }, submission.purpose), renderBody())), footer(), /*#__PURE__*/React.createElement(ProofRequestAccept, {
    visible: acceptModalVisible,
    proofId: '',
    confirmationOnly: true
  }), /*#__PURE__*/React.createElement(CommonRemoveModal, {
    usage: ModalUsage.ProofRequestDecline,
    visible: declineModalVisible,
    onSubmit: handleDeclineTouched,
    onCancel: toggleDeclineModalVisible
  }));
};
export default OpenIDProofPresentation;
//# sourceMappingURL=OpenIDProofPresentation.js.map