import React, {FC, useState} from 'react';
import * as Sentry from '@sentry/react-native';
import {Severity} from '@sentry/types';
import _ from 'lodash';
import {useNavigation} from '@react-navigation/native';
import {Modal} from 'react-native';
import {usePost} from '@hooks/api';
import Loader from '@components/Loader';
import useLoader from '@contexts/loader';
import useUser from '@contexts/user';
import DeleteIcon from '@assets/svg/DeleteIcon';
import {IClaimableCredentialProps} from '@components/Credential/types';
import {DELETE_CLAIMABLE} from '@constants/api';
import {
  Overlay,
  Wrapper,
  Description,
  DeleteIconWrapper,
  Footer,
  FooterButton,
} from '@styles/components/delete-credential-modal';

interface IProps {
  onHide: () => void;
  onError?: (value: string) => void;
  visible?: boolean;
  credentials: IClaimableCredentialProps[];
  navigateToPrevScreen?: boolean;
  onDelete?: () => void;
}

const DeleteCredentialModal: FC<IProps> = ({
  visible,
  credentials,
  onHide,
  onError,
  navigateToPrevScreen = true,
  onDelete,
}) => {
  const navigation = useNavigation();
  const {showLoader, hideLoader} = useLoader();
  const {sdk, setCredentials, getPhoneNumber} = useUser();
  const [deleted, setDeleted] = useState<boolean>(false);
  const {mutateAsync} = usePost();

  const deleteCredential = async () => {
    const phoneNumber = await getPhoneNumber();
    let error_message = '';
    for (let index = 0; index < credentials.length; index++) {
      const credential = credentials[index];
      if (credential?.verified) {
        const credentialId = credential.id;
        if (credentialId) {
          showLoader();
          try {
            await sdk?.deleteCredentialById(credentialId);
          } catch (err: any) {
            error_message = err?.message;
            Sentry.captureMessage(
              `Error while deleting the credential from SDk, ${err?.message} / Mobile Number ${phoneNumber} / credentialId : ${credentialId}`,
              Severity.Error,
            );
          } finally {
            hideLoader();
          }
        }
      } else {
        try {
          const data = {
            userId: phoneNumber,
            draftVCId: credential?.DraftVCId,
          };

          await mutateAsync({url: DELETE_CLAIMABLE, data});
        } catch (e: any) {
          Sentry.captureMessage(
            `Error while deleting the claimable credential, ${
              e?.message
            } / Mobile Number ${phoneNumber} / Payload : ${JSON.stringify({
              userId: phoneNumber,
              draftVCId: credential?.DraftVCId,
            })}`,
            Severity.Error,
          );
        }
      }
    }
    if (error_message === '') {
      setDeleted(true);
      if (navigateToPrevScreen) {
        await setCredentials(undefined);
        setTimeout(() => navigation?.goBack(), 500);
      }

      if (_.isFunction(onDelete)) {
        onDelete();
      }
    } else {
      if (_.isFunction(onError)) {
        onError(error_message);
      }
      onHide();
    }
  };
  return (
    <Modal
      animationType="fade"
      transparent={true}
      visible={visible}
      onRequestClose={onHide}
      testID="dltCredMdl">
      <Overlay onPress={onHide} activeOpacity={1} testID="overlay" />
      <Wrapper edges={['bottom']}>
        <DeleteIconWrapper>
          <DeleteIcon />
        </DeleteIconWrapper>

        <Description>
          {deleted
            ? 'Learnet certificate successfully deleted'
            : 'Are you sure you want to delete learnet credential?'}
        </Description>

        {!deleted && (
          <Footer>
            <FooterButton
              title="No"
              variant="text"
              onPress={onHide}
              testID="noDlt"
            />
            <FooterButton
              title="Yes"
              onPress={deleteCredential}
              testID="yesDlt"
            />
          </Footer>
        )}
      </Wrapper>
      <Loader />
    </Modal>
  );
};

export default DeleteCredentialModal;
