import { StyleSheet, View, TouchableOpacity, ScrollView } from 'react-native';
import { CENTER } from '../../constants';
import { useNavigation } from '@react-navigation/native';
import { copyToClipboard } from '../../functions';
import { GlobalThemeView, ThemeText } from '../../functions/CustomElements';
import { useToast } from '../../../context-store/toastManager';
import { useTranslation } from 'react-i18next';
import CustomSettingsTopBar from '../../functions/CustomElements/settingsTopBar';
import ThemeIcon from '../../functions/CustomElements/themeIcon';
import {
  HIDDEN_OPACITY,
  INSET_WINDOW_WIDTH,
  SIZES,
} from '../../constants/theme';
import { useGlobalContacts } from '../../../context-store/globalContacts';
import FormattedSatText from '../../functions/CustomElements/satTextDisplay';
import formatTokensNumber from '../../functions/lrc20/formatTokensBalance';
import { useSparkWallet } from '../../../context-store/sparkContext';
import { useImageCache } from '../../../context-store/imageCache';
import GetThemeColors from '../../hooks/themeColors';
import ContactProfileImage from '../../components/admin/homeComponents/contacts/internalComponents/profileImage';
import { useGlobalThemeContext } from '../../../context-store/theme';

export default function TechnicalTransactionDetails(props) {
  console.log('Transaction Details Page');
  const { showToast } = useToast();
  const navigate = useNavigation();
  const { t } = useTranslation();
  const { sparkInformation } = useSparkWallet();
  const { decodedAddedContacts } = useGlobalContacts();
  const { theme, darkModeType } = useGlobalThemeContext();
  const { cache } = useImageCache();
  const { backgroundColor, backgroundOffset } = GetThemeColors();

  const { transaction } = props.route.params;
  const { details, sparkID } = transaction;

  const isBulkPayment = !!details?.isBulkPayment;
  const bulkPaymentGroup = details?.bulkPaymentGroup ?? [];

  // Show per-person breakdown only when the split is unequal
  const successfulGroup = bulkPaymentGroup.filter(e => e.status !== 'failed');

  const isLRC20Payment = details?.isLRC20Payment;
  const selectedToken = isLRC20Payment
    ? sparkInformation.tokens?.[details?.LRC20Token]
    : '';
  const isPending = transaction.paymentStatus === 'pending';
  const isConfirmed = transaction.paymentStatus === 'completed';

  let paymentDetails = [];
  let infoValues = [];

  if (transaction.paymentType === 'spark') {
    if (details.isFlashnetStablecoin) {
      paymentDetails = [
        t('screens.inAccount.technicalTransactionDetails.paymentId'),
        t('screens.inAccount.technicalTransactionDetails.quoteId'),
        t('screens.inAccount.technicalTransactionDetails.destinationAddress'),
        t('screens.inAccount.technicalTransactionDetails.destinationAsset'),
        t('screens.inAccount.technicalTransactionDetails.destinationChain'),
      ];
      infoValues = [
        sparkID,
        details.quoteId,
        details.destinationAddress,
        details.destinationAsset,
        details.destinationChain,
      ];
    } else if (details.isLRC20Payment) {
      paymentDetails = [
        t('screens.inAccount.technicalTransactionDetails.txHash'),
      ];
      infoValues = [sparkID];
    } else {
      paymentDetails = [
        t('screens.inAccount.technicalTransactionDetails.paymentId'),
      ];
      infoValues = [sparkID];
    }
  } else if (transaction.paymentType === 'lightning') {
    paymentDetails = [
      t('screens.inAccount.technicalTransactionDetails.paymentId'),
      t('screens.inAccount.technicalTransactionDetails.preimage'),
      t('screens.inAccount.technicalTransactionDetails.address'),
    ];
    infoValues = [sparkID, details.preimage, details.address];

    if (details.isRootstockSwap) {
      paymentDetails.push(
        t('screens.inAccount.technicalTransactionDetails.rootstockSwapId'),
        !isConfirmed &&
          t(
            'screens.inAccount.technicalTransactionDetails.rootstockSwapStatus',
          ),
        !isConfirmed &&
          t(
            'screens.inAccount.technicalTransactionDetails.rootstockPaymentTxId',
          ),
      );
      infoValues.push(
        details.rootstockSwapId,
        !isConfirmed && details.rootstockSwapStatus,
        !isConfirmed && (details.rootstockPaymentTxId || details.lockTxHash),
      );
    }

    if (details.bitrefillInvoiceId) {
      paymentDetails.push(
        t('screens.inAccount.technicalTransactionDetails.bitrefillInvoiceId'),
      );
      infoValues.push(details.bitrefillInvoiceId);
    }
  } else {
    // bitcoin
    const bitcoinLabels = [
      t('screens.inAccount.technicalTransactionDetails.paymentId'),
      t('screens.inAccount.technicalTransactionDetails.bitcoinTxId'),
      t('screens.inAccount.technicalTransactionDetails.address'),
      t('screens.inAccount.technicalTransactionDetails.paymentExp'),
    ];
    const bitcoinValues = [
      sparkID,
      details.onChainTxid,
      details.address,
      details.expiresAt || 'N/A',
    ];
    const count = details.direction === 'OUTGOING' && isPending ? 4 : 3;
    paymentDetails = bitcoinLabels.slice(0, count);
    infoValues = bitcoinValues.slice(0, count);
  }

  const infoElements = paymentDetails.filter(Boolean).map((item, id) => {
    const txItem = infoValues[id];

    const isBitcoinTxId =
      transaction.paymentType === 'bitcoin' &&
      item === t('screens.inAccount.technicalTransactionDetails.bitcoinTxId');

    return (
      <View key={id}>
        <View style={styles.headerContainer}>
          <ThemeText content={item} styles={{ ...styles.headerText }} />
          {!isPending && !txItem && (
            <TouchableOpacity
              onPress={() => {
                navigate.navigate('InformationPopup', {
                  textContent: t(
                    'screens.inAccount.technicalTransactionDetails.noInformationLabel',
                    { item },
                  ),
                  buttonText: t('constants.understandText'),
                });
              }}
            >
              <ThemeIcon size={20} iconName={'Info'} />
            </TouchableOpacity>
          )}
        </View>
        <TouchableOpacity
          onPress={() => {
            if (isBitcoinTxId) {
              navigate.navigate('CustomWebView', {
                webViewURL: `https://mempool.space/tx/${txItem}`,
              });
              return;
            }
            copyToClipboard(txItem, showToast);
          }}
        >
          <ThemeText
            CustomNumberOfLines={2}
            content={txItem || 'N/A'}
            styles={{ ...styles.descriptionText }}
          />
        </TouchableOpacity>
      </View>
    );
  });

  return (
    <GlobalThemeView useStandardWidth={true}>
      <CustomSettingsTopBar />
      <ScrollView
        showsVerticalScrollIndicator={false}
        style={styles.innerContainer}
      >
        {infoElements}

        {isBulkPayment && !!bulkPaymentGroup.length && (
          <>
            <ThemeText
              content={t(
                'screens.inAccount.technicalTransactionDetails.transferIds',
              )}
              styles={styles.headerText}
            />

            <View style={[styles.amountsBreakdown]}>
              {successfulGroup.map((entry, index) => {
                const contact = decodedAddedContacts?.find(
                  c => c.uuid === entry.contactUUID,
                );
                const displayName =
                  contact?.name || contact?.uniqueName || entry.contactUUID;
                const transferId = entry?.transferId || '';

                // BTC: raw sats passed directly.
                // USD: amountCents * 10_000 = micros (matches DB amount unit and
                //      what FormattedSatText + formatTokensNumber expect for LRC20).

                const isLast = index === successfulGroup.length - 1;

                return (
                  <TouchableOpacity
                    onPress={() => copyToClipboard(transferId, showToast)}
                    key={entry.contactUUID}
                  >
                    <View style={styles.infoRow}>
                      <View
                        style={[
                          styles.profileImage,
                          { backgroundColor: backgroundColor },
                        ]}
                      >
                        <ContactProfileImage
                          updated={cache[entry.contactUUID]?.updated}
                          uri={cache[entry.contactUUID]?.localUri}
                          darkModeType={darkModeType}
                          theme={theme}
                        />
                      </View>
                      <View style={styles.transactionRow}>
                        <ThemeText
                          content={displayName}
                          styles={styles.infoName}
                          CustomNumberOfLines={1}
                        />
                        {!details.isLRC20Payment && (
                          <ThemeText
                            content={entry?.transferId}
                            styles={styles.transferId}
                            CustomNumberOfLines={1}
                          />
                        )}
                      </View>
                    </View>
                    {!isLast && (
                      <View style={[styles.rowDivider, { backgroundColor }]} />
                    )}
                  </TouchableOpacity>
                );
              })}
            </View>
          </>
        )}
      </ScrollView>
    </GlobalThemeView>
  );
}

const styles = StyleSheet.create({
  innerContainer: {
    width: INSET_WINDOW_WIDTH,
    ...CENTER,
  },
  headerContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 5,
  },
  headerText: { includeFontPadding: false, marginRight: 5 },
  descriptionText: {
    marginBottom: 30,
  },
  amountsBreakdown: {
    width: '100%',
    marginTop: 8,
  },

  infoRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 15,
  },
  infoName: {
    includeFontPadding: false,
    flexShrink: 1,
  },
  transferId: {
    fontSize: SIZES.small,
    opacity: HIDDEN_OPACITY,
    includeFontPadding: false,
    flexShrink: 1,
  },
  infoNameSmall: {
    fontSize: SIZES.smedium,
    opacity: HIDDEN_OPACITY,
    includeFontPadding: false,
    flexShrink: 1,
  },
  infoValue: {
    marginLeft: 8,
  },
  rowDivider: {
    height: 1,
  },
  transactionRow: {
    flex: 1,
  },
  profileImage: {
    width: 36,
    height: 36,
    borderRadius: 18,
    alignItems: 'center',
    justifyContent: 'center',
    overflow: 'hidden',
    marginRight: 10,
  },
});
