import React, {useState} from 'react';
import {useNavigation} from '@react-navigation/native';
import Credential from '@components/Credential';
import useUser from '@contexts/user';
import {CREDENTIAL_DETAIL} from '@constants/navigation/credential-detail';
import {Body, CredentialsWrapper} from '@styles/screens/home';

const Credentials = () => {
  const {credentials} = useUser();
  const [selectedItem, setSelectedItem] = useState<number>(0);
  const navigation = useNavigation<any>();

  const calculateZIndex = (i: number, length: number) => {
    let x = 0;
    if (selectedItem === i) {
      x = length - 1;
    } else if (selectedItem < i) {
      x = length - 1 - i;
    }
    return x;
  };
  return (
    <Body>
      {credentials &&
        credentials?.map((c, i) => {
          const credential = {
            VCName: c?.credentialSubject?.displayName || c?.type[1],
            CreatedAt: c?.issuanceDate,
            IssuerId: c?.credentialSubject?.issuerName,
            credentialId: c?.id,
            selfDeclared: c?.type?.includes('SelfIssuedDataUAF'),
          };
          return (
            <CredentialsWrapper
              key={i}
              active={selectedItem === i}
              zIndex={calculateZIndex(i, credentials?.length)}
              index={i}>
              <Credential
                active={selectedItem === i}
                credential={credential}
                onSelect={() => setSelectedItem(i)}
                onPress={async () =>
                  navigation.navigate({
                    name: CREDENTIAL_DETAIL.SCREEN,
                    params: [{...c, verified: true}],
                  })
                }
              />
            </CredentialsWrapper>
          );
        })}
    </Body>
  );
};

export default Credentials;
