import React, {useMemo, useRef, useState} from 'react';
import {
  ActivityIndicator,
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  View,
} from 'react-native';
import {useQuery} from '@tanstack/react-query';
import {
  Colors,
  fontSz,
  formatAsCurrency,
  formatDate,
  getInterestRange,
  globalStyles,
  groupArray,
  hp,
  Images,
  isTablet,
  ms,
  savingTypeColors,
  savingTypeDeepColors,
  suggestedPlanColors,
  wp,
  SavingsAccountListType,
  calculateSavingsProgress,
} from '../utils';
import dayjs from 'dayjs';
import Header from '../components/Header';
import {Text} from '../components/Text';
import {ScreenParams, CommonScreenProps} from '../navigation/app';
import {PoweredBy} from '../components/Common/poweredBy';
import {SmartImage} from '../components/Images/SmartImage';
import {CustomPressable} from '../components/Button';
import ThreePaneToggleTabs from '../components/ToggleTab/threePane';
import {HomeNavigationCard} from '../components/Common/homeNavigationCard';
import {useSDKConfig} from '../contexts/SDKConfigContext';
import {
  getAllSavingsCategories,
  getSavingsListByCustomerId,
  getTotalAccountTransactionsByCustomerId,
} from '../services/actions';
import {getCategoryIcon} from '../components/SavingsCategory';
import PlanCard from '../components/PlanCard';
import TransactionsList from '../components/TransactionsList';

type Props = CommonScreenProps & {
  params: ScreenParams['existingSavings'];
};

const ExistingSavings = ({
  params,
  navigate,
  goBack,
  isInitialScreen,
}: Props) => {
  const listRef = useRef(null);
  const [tabRoute, setTabRoute] = useState<0 | 1 | 2>(0);
  const {apiKey, primaryColor} = useSDKConfig();

  // Query for savings categories (for navigation cards)
  const {data: categoriesData, isLoading: categoriesLoading} = useQuery({
    queryKey: ['allSavingsCategories', apiKey],
    queryFn: () => getAllSavingsCategories(apiKey),
    retry: 2,
  });

  // Query for user's savings accounts (for accounts list)
  const {data: savingsData, isLoading: savingsLoading} = useQuery({
    queryKey: ['savingsListByCustomerId', apiKey],
    queryFn: () => getSavingsListByCustomerId(apiKey),
    retry: 2,
  });

  // Query for total account transactions (for total savings amount)
  const {data: totalData, isLoading: totalLoading} = useQuery({
    queryKey: ['totalAccountTransactionsByCustomerId', apiKey],
    queryFn: () => getTotalAccountTransactionsByCustomerId(apiKey),
    retry: 2,
  });

  // Combined loading state
  const isLoading = categoriesLoading || savingsLoading || totalLoading;

  // Filter savings data based on selected tab
  const filteredSavingsData = useMemo(() => {
    if (!Array.isArray(savingsData)) {
      return [];
    }

    switch (tabRoute) {
      case 0: // All
        return savingsData;
      case 1: // Flexible
        return savingsData.filter(
          (item: SavingsAccountListType) =>
            item.categoryName?.toLowerCase().includes('flexible') ||
            item.categoryName?.toLowerCase().includes('flexi'),
        );
      case 2: // Locked
        return savingsData.filter(
          (item: SavingsAccountListType) =>
            item.categoryName?.toLowerCase().includes('locked') ||
            item.categoryName?.toLowerCase().includes('lock'),
        );
      default:
        return savingsData;
    }
  }, [savingsData, tabRoute]);

  const getWalletBalanceLoader = () => {
    const totalAmount = totalData?.totalAmountInSavingsAccount || 0;
    return (
      <View style={globalStyles.rowCenter}>
        <Text
          style={{
            color: Colors.payLaterHeaderText,
          }}
          fontWeight="500"
          fontFamily={'Gordita-Medium'}
          textAlign={'center'}
          fontSize={fontSz(25)}
          text={`${formatAsCurrency(Number(totalAmount))}`}
        />
      </View>
    );
  };

  const displayWalletCard = () => {
    return (
      <View
        style={{
          width: '100%',
          alignItems: 'center',
          position: 'relative',
          marginTop: ms(15),
          marginVertical: ms(10),
          borderRadius: ms(10),
          ...(isTablet
            ? {
                minHeight: 220,
                backgroundColor: primaryColor,
              }
            : {}),
        }}>
        <SmartImage
          style={[styles.walletCardImage]}
          source={Images.walletCard}
        />
        <View style={styles.walletCardOverlay}>
          <View style={[globalStyles.rowEnd, {}]}>
            {/* <CustomPressable
              activeOpacity={0.9}
              onPress={() => {
                navigate('allPlan');
              }}
              style={[
                {
                  flexDirection: 'row',
                  alignItems: 'center',
                  backgroundColor: Colors.purple50,
                  borderRadius: ms(20),
                  paddingHorizontal: wp(7.5),
                  paddingVertical: wp(4),
                  columnGap: ms(4),
                },
              ]}>
              <Text
                style={{
                  color: Colors.white,
                }}
                fontFamily={'Gordita-Medium'}
                fontWeight="500"
                fontSize={fontSz(12)}
                text={`View all plans`}
              />
              <SmartImage
                style={{
                  width: ms(12),
                  height: ms(12),
                }}
                source={Images.forward}
              />
            </CustomPressable> */}
          </View>
          <View
            style={[
              globalStyles.colCenter,
              {
                flex: 2,
                alignSelf: 'center',
                justifyContent: 'center',
                rowGap: ms(5),
                marginBottom: ms(12.0),
              },
            ]}>
            <Text
              style={{
                color: Colors.payLaterHeaderText,
              }}
              fontWeight="400"
              textAlign={'center'}
              fontSize={fontSz(17)}
              text={'Total Balance'}
            />
            {getWalletBalanceLoader()}
          </View>
        </View>
      </View>
    );
  };

  const displayCardNavigationRoutes = () => {
    return (
      <View
        style={[
          globalStyles.rowBetween,
          {
            flexWrap: 'wrap',
            paddingBottom: ms(2),
          },
        ]}>
        <HomeNavigationCard
          icon={
            <SmartImage
              source={Images.add}
              style={{
                width: ms(35),
                height: ms(35),
                tintColor: Colors.chooseAccountTypeText,
              }}
            />
          }
          topComponent={
            <View
              style={[
                {
                  paddingHorizontal: ms(5),
                  backgroundColor: Colors.transparent,
                  borderRadius: ms(12),
                },
              ]}>
              <Text
                fontSize={fontSz(9)}
                fontFamily="Gordita-Regular"
                fontWeight="500"
                textAlign={'left'}
                text={''}
                color={Colors.white}
              />
            </View>
          }
          title={'Create New'}
          backgroundColor={suggestedPlanColors[0]}
          onPress={() => {
            navigate('savings', {});
          }}
        />
        {!categoriesLoading &&
          Array.isArray(categoriesData) &&
          categoriesData?.map((item: any, index: number) => {
            const {name, id, interestRate, interestRange, isLocked} = item;
            const icon = getCategoryIcon(name);
            
            // Use interestRange for locked savings, single rate for flexible
            const displayText = isLocked && interestRange 
              ? `${interestRange}% per annum`
              : `${interestRate}% per annum`;
            
            return (
              <HomeNavigationCard
                key={`${index}-${id}`}
                icon={
                  <SmartImage
                    source={icon}
                    style={{
                      width: ms(27),
                      height: ms(27),
                      tintColor: Colors.chooseAccountTypeText,
                    }}
                  />
                }
                topComponent={
                  <View
                    style={[
                      {
                        paddingHorizontal: ms(5),
                        paddingVertical: ms(5),
                        backgroundColor: savingTypeDeepColors[index],
                        borderRadius: ms(8),
                      },
                    ]}>
                    <Text
                      fontSize={fontSz(8)}
                      fontFamily="Gordita-Regular"
                      fontWeight="500"
                      textAlign={'left'}
                      text={displayText}
                      color={Colors.white}
                    />
                  </View>
                }
                title={`${item?.name} Plan`}
                backgroundColor={savingTypeColors[index]}
                onPress={() => {
                  navigate('allPlan', {
                    plan: `${item?.name} Plans`,
                    categoryFilter: item,
                  });
                }}
              />
            );
          })}
      </View>
    );
  };

  return (
    <>
      <StatusBar
        backgroundColor={Colors.white}
        barStyle={'dark-content'}
        animated={false}
      />
      <SafeAreaView style={[globalStyles.appContainer]}>
        <Header
          headerText={'Savings'}
          containerStyle={{
            paddingBottom: ms(10),
            paddingTop: ms(4),
            borderBottomWidth: ms(1),
            borderBottomColor: Colors.headerBottomColor,
          }}
          onPressBack={() => goBack()}
          headerChild={<View style={{flex: 0.125}} />}
        />
        {isLoading ? (
          <View style={styles.loadingContainer}>
            <ActivityIndicator size="small" color={primaryColor} />
          </View>
        ) : (
          <View
            style={{
              flex: 1,
              paddingHorizontal: wp(10),
              paddingTop: ms(14),
            }}>
            <View style={styles.content}>
              <ScrollView
                nestedScrollEnabled
                showsVerticalScrollIndicator={false}
                keyboardShouldPersistTaps="handled"
                style={{flexGrow: 0}}>
                {displayWalletCard()}
                {displayCardNavigationRoutes()}
                <View
                  style={[
                    globalStyles.rowBetween,
                    {
                      paddingVertical: hp(10),
                    },
                  ]}>
                  <Text
                    color={Colors.accountTransactions}
                    fontWeight="500"
                    fontFamily={'Gordita-Medium'}
                    fontSize={fontSz(16)}
                    lineHeight={fontSz(16 * 1.5)}
                    text={'Savings History'}
                  />
                  {/* <CustomPressable
                    activeOpacity={0.9}
                    onPress={() => {
                      navigate('history');
                    }}>
                    <Text
                      color={primaryColor}
                      fontWeight="500"
                      fontFamily={'Gordita-Medium'}
                      fontSize={fontSz(14)}
                      lineHeight={fontSz(14 * 1.33)}
                      text={`View More`}
                    />
                  </CustomPressable> */}
                </View>
              </ScrollView>

              <TransactionsList
                useHistoryEndpoint={true}
                recordsPerPage={10}
                showScrollIndicator={false}
                scrollEnabled={true}
                showTabs={true}
              />
            </View>
            <View
              style={{
                alignSelf: 'center',
                marginTop: ms(10),
              }}>
              <PoweredBy />
            </View>
          </View>
        )}
      </SafeAreaView>
    </>
  );
};

export default ExistingSavings;

const styles = StyleSheet.create({
  content: {
    flex: 1,
    height: '100%',
    paddingVertical: ms(20),
    paddingTop: ms(5),
    paddingHorizontal: ms(16),
    borderRadius: ms(8),
    backgroundColor: Colors.white,
    shadowColor: Colors.shadowColor,
    shadowOffset: {width: -1, height: 2},
    shadowOpacity: 0.2,
    shadowRadius: 3,
    elevation: 3,
  },
  walletCardImage: {
    width: '100%',
    resizeMode: 'cover',
    borderRadius: ms(10),
  },
  walletCardOverlay: {
    width: '100%',
    height: '100%',
    alignSelf: 'flex-start',
    justifyContent: 'space-between',
    paddingHorizontal: ms(12.5),
    paddingTop: ms(12.5),
    paddingBottom: ms(15),
    position: 'absolute',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingTop: ms(75),
  },
  statisticsContainer: {},
  statisticsGrid: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: ms(16),
    columnGap: ms(12),
  },
  statisticCard: {
    flex: 1,
    alignItems: 'center',
    padding: ms(12),
    borderRadius: ms(12),
    backgroundColor: Colors.white,
    borderWidth: 1,
    borderColor: Colors.neutral10,
  },
  statisticIconContainer: {
    width: ms(40),
    height: ms(40),
    borderRadius: ms(20),
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: ms(12),
  },
  statisticIcon: {
    width: ms(24),
    height: ms(24),
  },
  statisticValue: {
    color: Colors.headerText,
    marginBottom: ms(4),
    textAlign: 'center',
  },
  statisticLabel: {
    color: Colors.neutral90,
    textAlign: 'center',
  },
});
