import React, {Fragment, useMemo, useRef, useState, useEffect} from 'react';
import {
  Animated,
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text as BaseText,
  View,
  ActivityIndicator,
} from 'react-native';
import {ScreenParams, CommonScreenProps} from '../navigation/app';
import {
  calculateSavingsProgress,
  Colors,
  fontSz,
  formatAsCurrency,
  formatDate,
  globalStyles,
  groupArray,
  hp,
  Images,
  isTablet,
  ms,
  SavingsAccountListType,
  suggestedPlanColors,
  wp,
} from '../utils';
import Header from '../components/Header';
import {PoweredBy} from '../components/Common/poweredBy';
import {Button, CustomPressable, FloatButton} from '../components/Button';
import {Info} from '../components/Common/info';
import {Text} from '../components/Text';
import {useQuery} from '@tanstack/react-query';
import {getSavingsListByCustomerId} from '../services/actions';
import {useSDKConfig} from '../contexts/SDKConfigContext';
import PlanCard from '../components/PlanCard';

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

const AllPlan = ({params, navigate, goBack, isInitialScreen}: Props) => {
  const [screenData, setScreenData] = useState({
    data: {},
    isLoading: false,
    isError: false,
  });
  const listRef = useRef(null);
  const {apiKey, primaryColor} = useSDKConfig();

  // Use React Query directly
  const {data, isLoading, isError, refetch} = useQuery({
    queryKey: ['savingsListByCustomerId', apiKey],
    queryFn: () => getSavingsListByCustomerId(apiKey),
    retry: 2,
  });

  // Filter data based on category if provided
  const filteredData = useMemo(() => {
    if (!Array.isArray(data) || !params?.categoryFilter) {
      return data;
    }

    return data.filter((item: SavingsAccountListType) =>
      item.categoryName?.toLowerCase() === params.categoryFilter.name?.toLowerCase()
    );
  }, [data, params?.categoryFilter]);

  console.log('data', data);

  return (
    <>
      <StatusBar
        backgroundColor={Colors.white}
        barStyle={'dark-content'}
        animated={false}
      />
      <SafeAreaView style={[globalStyles.appContainer]}>
        <Header
          headerText={params?.plan ?? 'All plans'}
          containerStyle={{
            paddingBottom: ms(10),
            paddingTop: ms(4),
            borderBottomWidth: ms(1),
            borderBottomColor: Colors.headerBottomColor,
          }}
          onPressBack={() => {
            goBack();
          }}
          headerChild={<View style={{flex: 0.125}} />}
        />
        <View
          style={{
            flex: 1,
            paddingHorizontal: wp(20),
            paddingTop: ms(14),
          }}>
          <View style={styles.content}>
            <ScrollView
              nestedScrollEnabled
              contentContainerStyle={{rowGap: ms(15)}}
              showsVerticalScrollIndicator={false}
              keyboardShouldPersistTaps="handled">
              {isLoading && (
                <View
                  style={{
                    flex: 1,
                    justifyContent: 'center',
                    alignItems: 'center',
                    paddingTop: ms(20),
                  }}>
                  <ActivityIndicator size="small" color={primaryColor} />
                </View>
              )}
              {!isLoading &&
                Array.isArray(filteredData) &&
                filteredData?.map((option: SavingsAccountListType, index: any) => {
                  const isLockedSavings = option?.isLocked || false;

                  return (
                    <PlanCard
                      key={index}
                      data={option}
                      backgroundColor={suggestedPlanColors[index]}
                      progress={
                        calculateSavingsProgress(
                          option?.savingTarget,
                          option?.amountSaved,
                        ) ?? 0
                      }
                      onPress={() => {
                        navigate('plan', {
                          planId: option.savingsId,
                          planName: option.accountName,
                        });
                      }}
                      isLockedSavings={isLockedSavings}
                      startDate={option?.startDate}
                      endDate={option?.endDate}
                    />
                  );
                })}
              {!isLoading && Array.isArray(filteredData) && filteredData.length === 0 && (
                <View style={{alignItems: 'center', paddingTop: ms(20)}}>
                  <Text
                    color={Colors.neutral90}
                    fontWeight="400"
                    fontFamily={'Gordita-Regular'}
                    fontSize={fontSz(14)}
                    text={params?.categoryFilter ?
                      `No ${params.categoryFilter.name?.toLowerCase()} savings accounts found` :
                      'No savings accounts found'
                    }
                  />
                </View>
              )}
            </ScrollView>
          </View>
          {/* <View
            style={{
              alignSelf: 'center',
              marginTop: ms(10),
            }}>
            <PoweredBy />
          </View> */}
        </View>
        <View
          style={{
            alignItems: 'flex-end',
            position: 'absolute',
            bottom: ms(80),
            right: wp(35),
            zIndex: 1000,
          }}>
          <FloatButton
            title={'Create'}
            textStyle={{
              fontSize: fontSz(15),
              fontFamily: 'Gordita-Medium',
              fontWeight: '500',
              color: Colors.white,
            }}
            iconStyle={{
              width: ms(24),
              height: ms(24),
              tintColor: Colors.white,
            }}
            onPress={() => {
              if (params?.categoryFilter) {
                // Navigate to savings form with preselected category
                navigate('savings', {preSelectedCategory: params.categoryFilter});
              } else {
                // Navigate to savings form without preselection
                navigate('savings');
              }
            }}
          />
        </View>
      </SafeAreaView>
    </>
  );
};

export default AllPlan;

const styles = StyleSheet.create({
  content: {
    flex: 1,
    height: '100%',
    paddingVertical: ms(20),
    paddingHorizontal: ms(16),
    borderRadius: ms(8),
    backgroundColor: Colors.white,
    shadowColor: Colors.shadowColor,
    shadowOffset: {width: -1, height: 2},
    shadowOpacity: 0.2,
    shadowRadius: 3,
    elevation: 3,
  },
});
