import {
  GlobalThemeView,
  ThemeText,
} from '../../../../../functions/CustomElements';
import CustomSettingsTopBar from '../../../../../functions/CustomElements/settingsTopBar';
import { ScrollView, StyleSheet, TouchableOpacity, View } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import {
  COLORS,
  INSET_WINDOW_WIDTH,
  SIZES,
} from '../../../../../constants/theme';
import {
  NWC_ACCOUNT_UUID,
  useActiveCustodyAccount,
} from '../../../../../../context-store/activeAccount';
import ThemeIcon from '../../../../../functions/CustomElements/themeIcon';
import GetThemeColors from '../../../../../hooks/themeColors';
import { useTranslation } from 'react-i18next';
import { useCallback, useMemo } from 'react';
import AccountProfileImage from '../../accounts/accountProfileImage';
import { useGlobalThemeContext } from '../../../../../../context-store/theme';
import { useGlobalContextProvider } from '../../../../../../context-store/context';
import { useToast } from '../../../../../../context-store/toastManager';
import CustomButton from '../../../../../functions/CustomElements/button';
import { CENTER } from '../../../../../constants';
import CustomToggleSwitch from '../../../../../functions/CustomElements/switch';

export default function EditAccountPage(props) {
  const { showToast } = useToast();
  const selectedAccount = props?.route?.params?.account;
  const fromPage = props?.route?.params?.from;
  const { getAccountMnemonic, custodyAccounts, activeAccount } =
    useActiveCustodyAccount();
  const { toggleMasterInfoObject, masterInfoObject } =
    useGlobalContextProvider();
  const { backgroundOffset, backgroundColor, textColor } = GetThemeColors();
  const { theme, darkModeType } = useGlobalThemeContext();
  const { t } = useTranslation();

  const accountInformation = useMemo(() => {
    return (
      custodyAccounts?.find(item => item.uuid === selectedAccount.uuid) ||
      selectedAccount ||
      {}
    );
  }, [custodyAccounts, selectedAccount.uuid]);

  const pinnedAccountUUIDs = masterInfoObject?.pinnedAccounts || [];

  const isPinned = pinnedAccountUUIDs.includes(
    accountInformation.uuid || accountInformation.name,
  );
  const isActive = activeAccount.uuid === accountInformation.uuid;

  const navigate = useNavigation();

  const handleProfileImage = () => {
    if (accountInformation.uuid === NWC_ACCOUNT_UUID) return;
    navigate.navigate('EmojiAvatarSelector', { account: accountInformation });
  };

  console.log(
    'Selected Account:',
    selectedAccount,
    accountInformation,
    custodyAccounts,
    'redndering',
  );

  const handleNavigateView = useCallback(async () => {
    const mnemonic = await getAccountMnemonic(selectedAccount);
    navigate.navigate('SeedPhraseWarning', {
      mnemonic: mnemonic,
      extraData: { canViewQrCode: false },
      fromPage: 'accounts',
    });
  }, [selectedAccount]);

  const handleEditName = useCallback(async () => {
    navigate.navigate('EditAccountName', {
      account: accountInformation,
    });
  }, [accountInformation]);

  const handlePinInfo = useCallback(() => {
    navigate.navigate('InformationPopup', {
      textContent: t(
        'settings.accountComponents.editAccountPage.pin_account_info',
      ),
      buttonText: t('constants.back'),
    });
  }, [navigate, t]);

  const handleAccountTypeInfo = useCallback(() => {
    const isDerived = accountInformation.accountType === 'derived';
    navigate.navigate('InformationPopup', {
      textContent: t(
        isDerived
          ? 'settings.accountComponents.editAccountPage.accountTypeDerivedInfo'
          : 'settings.accountComponents.editAccountPage.accountTypeImportedInfo',
      ),
      buttonText: t('constants.back'),
    });
  }, [navigate, t, accountInformation.accountType]);

  const handlePinToggle = useCallback(() => {
    const accountId = accountInformation.uuid || accountInformation.name;
    const currentPins = masterInfoObject.pinnedAccounts || [];
    const isPinned = currentPins.includes(accountId);

    if (isPinned) {
      toggleMasterInfoObject({
        pinnedAccounts: currentPins.filter(id => id !== accountId),
      });
    } else {
      if (currentPins.length >= 2) {
        showToast({
          type: 'error',
          title: t('settings.hub.maxPinsReached'),
        });
        return;
      }
      toggleMasterInfoObject({
        pinnedAccounts: [...currentPins, accountId],
      });
    }
  }, [
    masterInfoObject.pinnedAccounts,
    toggleMasterInfoObject,
    showToast,
    t,
    accountInformation,
  ]);

  return (
    <GlobalThemeView useStandardWidth={true}>
      <CustomSettingsTopBar
        label={t('settings.accountComponents.editAccountPage.title')}
      />
      <ScrollView
        contentContainerStyle={{ paddingTop: 10 }}
        showsVerticalScrollIndicator={false}
        keyboardShouldPersistTaps={'handled'}
      >
        <View style={styles.avatarContainer}>
          <TouchableOpacity
            activeOpacity={
              accountInformation.uuid === NWC_ACCOUNT_UUID ? 1 : 0.2
            }
            onPress={handleProfileImage}
            style={[styles.avatar, { backgroundColor: backgroundOffset }]}
          >
            <AccountProfileImage imageSize={120} account={accountInformation} />
            {accountInformation.uuid !== NWC_ACCOUNT_UUID && (
              <View
                style={[
                  styles.editBadge,
                  { backgroundColor: COLORS.darkModeText },
                ]}
              >
                <ThemeIcon
                  colorOverride={COLORS.lightModeText}
                  iconName="Edit"
                  size={18}
                />
              </View>
            )}
          </TouchableOpacity>
        </View>

        {/* Account info */}
        {accountInformation.uuid === NWC_ACCOUNT_UUID && (
          <View style={[styles.card, { backgroundColor: backgroundOffset }]}>
            {/* Account Name */}
            <View style={styles.row}>
              <View style={styles.infoContainer}>
                <ThemeText
                  styles={[styles.rowLabel, { marginRight: 5, width: 'unset' }]}
                  content={t(
                    'settings.accountComponents.editAccountPage.account',
                    {
                      context: isPinned ? 'unpin' : 'pin',
                    },
                  )}
                />
                <TouchableOpacity onPress={handlePinInfo}>
                  <ThemeIcon size={20} iconName={'Info'} />
                </TouchableOpacity>
              </View>
              <CustomToggleSwitch
                stateValue={isPinned}
                toggleSwitchFunction={handlePinToggle}
                page={'pinAccount'}
              />
            </View>
          </View>
        )}

        <View style={[styles.card, { backgroundColor: backgroundOffset }]}>
          {/* Account Name */}
          {accountInformation.uuid !== NWC_ACCOUNT_UUID && (
            <TouchableOpacity style={styles.row} onPress={handleEditName}>
              <ThemeText
                styles={styles.rowLabel}
                content={t(
                  'settings.accountComponents.editAccountPage.accountNameLabel',
                )}
              />
              <View style={styles.rowRight}>
                <ThemeText
                  CustomNumberOfLines={1}
                  adjustsFontSizeToFit={true}
                  styles={styles.rowValue}
                  content={accountInformation.name}
                />
                <ThemeIcon iconName="ChevronRight" size={18} />
              </View>
            </TouchableOpacity>
          )}

          {accountInformation.uuid !== NWC_ACCOUNT_UUID && (
            <View style={[styles.divider, { backgroundColor }]} />
          )}

          {accountInformation.uuid !== NWC_ACCOUNT_UUID && (
            <View style={styles.row}>
              <View style={styles.infoContainer}>
                <ThemeText
                  styles={[styles.rowLabel, { marginRight: 5, width: 'unset' }]}
                  content={t(
                    'settings.accountComponents.editAccountPage.accountTypeLabel',
                  )}
                />
                <TouchableOpacity onPress={handleAccountTypeInfo}>
                  <ThemeIcon size={20} iconName={'Info'} />
                </TouchableOpacity>
              </View>
              <View style={[styles.rowRight, { gap: 5 }]}>
                <View
                  style={[
                    styles.accountTypePill,
                    {
                      backgroundColor,
                    },
                  ]}
                >
                  <ThemeText
                    styles={[styles.accountTypePillText]}
                    content={t(
                      `settings.accountComponents.editAccountPage.accountType`,
                      { context: accountInformation.accountType },
                    )}
                  />
                </View>
              </View>
            </View>
          )}

          {accountInformation.uuid !== NWC_ACCOUNT_UUID && (
            <View style={[styles.divider, { backgroundColor }]} />
          )}

          {/* Show Recovery Phrase */}
          <TouchableOpacity style={styles.row} onPress={handleNavigateView}>
            <ThemeText
              styles={[styles.rowLabel]}
              content={t(
                'settings.accountComponents.editAccountPage.showRecoveryPhraseLabel',
              )}
            />
            <ThemeIcon iconName="ChevronRight" size={18} />
          </TouchableOpacity>
        </View>

        {/* Pin Contact */}
        {accountInformation.uuid !== NWC_ACCOUNT_UUID && (
          <View style={[styles.card, { backgroundColor: backgroundOffset }]}>
            {/* Account Name */}
            <View style={styles.row}>
              <View style={styles.infoContainer}>
                <ThemeText
                  styles={[styles.rowLabel, { marginRight: 5, width: 'unset' }]}
                  content={t(
                    'settings.accountComponents.editAccountPage.account',
                    {
                      context: isPinned ? 'unpin' : 'pin',
                    },
                  )}
                />
                <TouchableOpacity onPress={handlePinInfo}>
                  <ThemeIcon size={20} iconName={'Info'} />
                </TouchableOpacity>
              </View>
              <CustomToggleSwitch
                stateValue={isPinned}
                toggleSwitchFunction={handlePinToggle}
                page={'pinAccount'}
              />
            </View>
          </View>
        )}
      </ScrollView>
      {/* Danger Zone */}
      {accountInformation.uuid !== NWC_ACCOUNT_UUID && (
        <CustomButton
          textContent={t(
            'settings.accountComponents.editAccountPage.removeAccountLabel',
          )}
          actionFunction={() => {
            if (isActive) {
              navigate.navigate('ErrorScreen', {
                errorMessage: t(
                  'settings.accountComponents.editAccountPage.activeAccountError',
                ),
              });
              return;
            }
            navigate.navigate('RemoveAccountPage', {
              account: accountInformation,
              from: fromPage,
            });
          }}
          buttonStyles={styles.buttonContainer}
        />
      )}
    </GlobalThemeView>
  );
}
const styles = StyleSheet.create({
  avatarContainer: {
    marginBottom: 25,
    alignSelf: 'center',
  },

  avatar: {
    width: 120,
    height: 120,
    borderRadius: 60,
    alignItems: 'center',
    justifyContent: 'center',
  },

  editBadge: {
    position: 'absolute',
    bottom: 6,
    right: 6,
    width: 28,
    height: 28,
    borderRadius: 14,
    alignItems: 'center',
    justifyContent: 'center',
  },

  card: {
    alignSelf: 'center',
    width: INSET_WINDOW_WIDTH,
    borderRadius: 16,
    marginBottom: 16,
    overflow: 'hidden',
  },

  row: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingVertical: 18,
    paddingHorizontal: 16,
    gap: 15,
  },
  infoContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },

  rowLabel: {
    width: '100%',
    flexShrink: 1,
    includeFontPadding: false,
  },

  rowRight: {
    width: '100%',
    flexShrink: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'flex-end',
  },

  rowValue: {
    fontSize: SIZES.small,
    opacity: 0.6,
    flexShrink: 1,
    includeFontPadding: false,
  },

  divider: {
    height: 2,
    marginLeft: 16,
  },

  dangerRow: {
    justifyContent: 'center',
  },
  buttonContainer: {
    width: INSET_WINDOW_WIDTH,
    ...CENTER,
  },
  dangerText: {
    color: COLORS.cancelRed,
    includeFontPadding: false,
    textAlign: 'center',
  },
  pinButton: {
    height: 35,
    width: 35,
    borderRadius: 12,
    alignItems: 'center',
    justifyContent: 'center',
  },

  accountTypePill: {
    paddingHorizontal: 10,
    paddingVertical: 4,
    borderRadius: 20,
  },
  accountTypePillText: {
    fontSize: SIZES.small,
    includeFontPadding: false,
  },
});
