import React, {useState, useEffect, useCallback} from 'react';
import * as Sentry from '@sentry/react-native';
import {Severity} from '@sentry/types';
import {Image, RefreshControl, LogBox} from 'react-native';
import moment from 'moment';
import {useFocusEffect} from '@react-navigation/native';
import DeleteCredentialModal from '@components/DeleteCredentialModal';
import {usePost, useGet} from '@hooks/api';
import {CLAIM_ALL, CLAIMABLE} from '@constants/api';
import useUser from '@contexts/user';
import {IClaimableCredentialProps} from '@components/Credential/types';
import DocumentIcon from '@assets/svg/DocumentIcon';
import {
  StyledNotification,
  NotificationHeader,
  NotificationTitle,
  NotificationTime,
  DocumentIconWrapper,
  NotificationFooter,
  DeleteButton,
  AddToWalletButton,
  DeleteLabelStyles,
  NotificationsNotFound,
  Wrapper,
} from '@styles/screens/notifications';
import {NotificationWrapperStyle} from '@styles/screens/home';

const Notification = () => {
  const [deleteModalVisibility, setDeleteModalVisibility] = useState(false);

  const [deleteCredentialData, setDeleteCredentialData] = useState<
    IClaimableCredentialProps | undefined
  >(undefined);
  const {getPhoneNumber, sdk, setCredentials, user, setUser} = useUser();
  const [claimableCredentials, setClaimableCredentials] = useState<
    IClaimableCredentialProps[]
  >([]);
  const [phoneNumber, setPhoneNumber] = useState<string | undefined>(undefined);

  const {refetch} = useGet(CLAIMABLE, `${CLAIMABLE}?userId=${phoneNumber}`, {
    enabled: false,
  });

  const {mutateAsync} = usePost();

  useEffect(() => {
    (async () => {
      const value = await getPhoneNumber();
      if (value) {
        setPhoneNumber(value);
      }
    })();
  }, [getPhoneNumber]);
  useEffect(() => {
    LogBox.ignoreLogs(['Animated: `useNativeDriver`']);
  }, []);

  const getNotifications = async () => {
    if (!claimableCredentials?.length && phoneNumber) {
      try {
        const response = await refetch();
        if (response?.data?.data?.length) {
          setClaimableCredentials(response?.data?.data);
        } else {
          setUser({...user, hasNewNotifications: false});
        }
      } catch (error: any) {
        Sentry.captureMessage(
          `Error while fetching the claimable credentials, Mobile Number : ${phoneNumber}, Error : ${error?.message}`,
          Severity.Error,
        );
        console.error(error);
      }
    }
  };

  useEffect(() => {
    (async () => {
      await getNotifications();
    })();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [phoneNumber, claimableCredentials]);

  const onRefresh = useCallback(async () => {
    await getNotifications();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [phoneNumber]);

  useFocusEffect(
    useCallback(() => {
      setClaimableCredentials([]);
    }, []),
  );

  return (
    <Wrapper
      contentInsetAdjustmentBehavior="automatic"
      contentContainerStyle={NotificationWrapperStyle}
      refreshControl={
        <RefreshControl refreshing={false} onRefresh={onRefresh} />
      }>
      {claimableCredentials?.length === 0 && (
        <NotificationsNotFound>
          <Image
            source={require('@assets/images/notifications/notifications-not-found.png')}
          />
        </NotificationsNotFound>
      )}
      {claimableCredentials?.map((c: IClaimableCredentialProps, i: number) => {
        const diff = moment().diff(c?.CreatedAt, 'days');
        const {Status} = c;
        return (
          <StyledNotification key={`${c?.VCName}_${i}`} testID="notifItm">
            <NotificationHeader>
              <DocumentIconWrapper>
                <DocumentIcon />
              </DocumentIconWrapper>
              <NotificationTitle>{c?.VCName}</NotificationTitle>
              {diff > 0 && <NotificationTime>{diff}d</NotificationTime>}
            </NotificationHeader>

            <NotificationFooter>
              <AddToWalletButton
                title={Status === 'PROCESSING' ? 'Adding' : 'Add to wallet'}
                disabled={Status === 'PROCESSING'}
                showLoader={Status === 'PROCESSING'}
                onPress={async () => {
                  if (Status === 'PROCESSING') {
                    return;
                  }
                  try {
                    if (c?.CredentialOfferRequestToken) {
                      const offerResponseToken =
                        await sdk?.createCredentialOfferResponseToken(
                          c?.CredentialOfferRequestToken,
                        );
                      const payload = {
                        offerResponseToken,
                        userId: phoneNumber,
                        draftVCId: c?.DraftVCId,
                        issuerId: c?.IssuerId,
                      };

                      await mutateAsync({url: CLAIM_ALL, data: [payload]});
                      await setCredentials(undefined);
                      setClaimableCredentials([]);
                    }
                  } catch (e: any) {
                    Sentry.captureMessage(
                      `Error while fetching the claiming the credential, Mobile Number : ${phoneNumber}, Error : ${e?.message}`,
                      Severity.Error,
                    );
                  }
                }}
                testID="addNtfWlt"
              />
              <DeleteButton
                title="Delete"
                labelStyles={DeleteLabelStyles}
                disabled={Status === 'PROCESSING'}
                onPress={() => {
                  if (Status === 'PROCESSING') {
                    return;
                  }
                  setDeleteCredentialData(c);
                  setDeleteModalVisibility(true);
                }}
                testID="dltNtf"
              />
            </NotificationFooter>
          </StyledNotification>
        );
      })}
      {deleteModalVisibility && deleteCredentialData && (
        <DeleteCredentialModal
          credentials={[deleteCredentialData]}
          visible={deleteModalVisibility}
          navigateToPrevScreen={false}
          onHide={() => {
            setDeleteModalVisibility(false);
            setDeleteCredentialData(undefined);
          }}
          onDelete={() => {
            setDeleteModalVisibility(false);
            setDeleteCredentialData(undefined);
            setClaimableCredentials([]);
          }}
        />
      )}
    </Wrapper>
  );
};

export default Notification;
