import { useEffect, useMemo, useState } from 'react';
import { DeviceEventEmitter } from 'react-native';
import { useAgent } from '@credo-ts/react-hooks';
import { useTranslation } from 'react-i18next';
import { Screens, TabStacks } from '../../../types/navigators';
import { ScrollView, StyleSheet, Text, View } from 'react-native';
import { formatDifPexCredentialsForRequest } from '../displayProof';
import { testIdWithKey } from '../../../utils/testable';
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';
import { useOpenIDCredentials } from '../context/OpenIDCredentialRecordProvider';
import { CredentialCard } from '../../../components/misc';
import { getCredentialForDisplay } from '../display';
import { buildFieldsFromW3cCredsCredential } from '../../../utils/oca';
import ScreenLayout from '../../../layout/ScreenLayout';
import { isSdJwtProofRequest, isW3CProofRequest } from '../utils/utils';
const OpenIDProofPresentation = ({
  navigation,
  route: {
    params: {
      credential
    }
  }
}) => {
  const [declineModalVisible, setDeclineModalVisible] = useState(false);
  const [buttonsVisible, setButtonsVisible] = useState(true);
  const [acceptModalVisible, setAcceptModalVisible] = useState(false);
  const [credentialsRequested, setCredentialsRequested] = useState([]);
  const {
    getW3CCredentialById,
    getSdJwtCredentialById
  } = useOpenIDCredentials();
  const {
    ColorPallet,
    ListItems,
    TextTheme
  } = useTheme();
  const {
    t
  } = useTranslation();
  const {
    agent
  } = useAgent();
  const toggleDeclineModalVisible = () => setDeclineModalVisible(!declineModalVisible);
  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
    },
    cardContainer: {
      paddingHorizontal: 25,
      paddingVertical: 16,
      backgroundColor: ColorPallet.brand.secondaryBackground,
      marginBottom: 20
    },
    cardAttributes: {
      flexDirection: 'row',
      flexWrap: 'wrap',
      borderColor: ColorPallet.grayscale.lightGrey,
      borderWidth: 1,
      borderRadius: 8,
      padding: 8
    },
    cardGroupContainer: {
      borderRadius: 8,
      borderWidth: 2,
      borderColor: 'rgba(255, 255, 255, 0.2)'
    },
    cardGroupHeader: {
      padding: 8,
      marginVertical: 8
    }
  });
  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]: {
          id: entry.credentials[0].id,
          claimFormat: entry.credentials[0].claimFormat
        }
      };
    }
    return acc;
  }, {}), [submission]);
  useEffect(() => {
    async function fetchCreds() {
      if (!selectedCredentials) return;
      const creds = [];
      for (const [inputDescriptorID, {
        id,
        claimFormat
      }] of Object.entries(selectedCredentials)) {
        let credential;
        if (isW3CProofRequest(claimFormat)) {
          credential = await getW3CCredentialById(id);
        } else if (isSdJwtProofRequest(claimFormat)) {
          credential = await getSdJwtCredentialById(id);
        }
        if (credential && inputDescriptorID) {
          creds.push(credential);
        }
      }
      setCredentialsRequested(creds);
    }
    fetchCreds();
  }, [selectedCredentials, getW3CCredentialById, getSdJwtCredentialById]);
  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 handleDismiss = async () => {
    var _navigation$getParent2;
    (_navigation$getParent2 = navigation.getParent()) === null || _navigation$getParent2 === void 0 || _navigation$getParent2.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.normal
    }, t('ProofRequest.ReceiveProofTitle')), '\n', /*#__PURE__*/React.createElement(Text, {
      style: TextTheme.title
    }, verifierName ? verifierName : '')));
  };
  const selectAltCredentail = () => {};
  const renderCard = (sub, selectedCredential, hasMultipleCreds) => {
    const credential = credentialsRequested.find(c => c.id === selectedCredential.id);
    if (!credential) {
      return null;
    }
    const credentialDisplay = getCredentialForDisplay(credential);
    const fields = buildFieldsFromW3cCredsCredential(credentialDisplay);
    const requestedAttributes = selectedCredential.requestedAttributes;
    const fieldsMapped = fields.filter(field => requestedAttributes === null || requestedAttributes === void 0 ? void 0 : requestedAttributes.includes(field.name));
    return /*#__PURE__*/React.createElement(CredentialCard, {
      credential: credential,
      displayItems: fieldsMapped,
      hasAltCredentials: hasMultipleCreds,
      handleAltCredChange: selectAltCredentail
    });
  };
  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];
      const globalSubmissionName = submission.name;
      const globalSubmissionPurpose = submission.purpose;
      const submissionName = s.name;
      const submissionPurpose = s.purpose;
      const name = submissionName || globalSubmissionName || undefined;
      const purpose = submissionPurpose || globalSubmissionPurpose || undefined;
      return /*#__PURE__*/React.createElement(View, {
        key: i
      }, /*#__PURE__*/React.createElement(View, {
        style: styles.cardContainer
      }, /*#__PURE__*/React.createElement(View, {
        style: styles.cardGroupContainer
      }, name && purpose && /*#__PURE__*/React.createElement(View, {
        style: styles.cardGroupHeader
      }, /*#__PURE__*/React.createElement(Text, {
        style: TextTheme.labelSubtitle
      }, name), /*#__PURE__*/React.createElement(Text, {
        style: TextTheme.labelSubtitle
      }, purpose)), s.isSatisfied && selectedCredential !== null && selectedCredential !== void 0 && selectedCredential.requestedAttributes ? renderCard(s, selectedCredential, s.credentials.length > 1) : /*#__PURE__*/React.createElement(Text, {
        style: TextTheme.normal
      }, t('ProofRequest.CredentialNotInWallet')))));
    }));
  };
  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
      }
    }, selectedCredentials && Object.keys(selectedCredentials).length > 0 ? /*#__PURE__*/React.createElement(React.Fragment, null, 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, footerButton(t('Global.Dismiss'), handleDismiss, ButtonType.Primary, testIdWithKey('DismissCredentialOffer'), t('Global.Dismiss'))));
  };
  return /*#__PURE__*/React.createElement(ScreenLayout, {
    screen: Screens.OpenIDCredentialDetails
  }, /*#__PURE__*/React.createElement(ScrollView, null, /*#__PURE__*/React.createElement(View, {
    style: styles.pageContent
  }, renderHeader(), 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