import React, {useState, useEffect} from 'react';
import {
  ActivityIndicator,
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  View,
} from 'react-native';
import {useQuery} from '@tanstack/react-query';
import {Button} from '../components/Button';
import {PoweredBy} from '../components/Common/poweredBy';
import Header from '../components/Header';
import SavingsCategory from '../components/SavingsCategory';
import {Text} from '../components/Text';
import {useSDKConfig} from '../contexts/SDKConfigContext';
import {ScreenParams, CommonScreenProps} from '../navigation/app';
import {getAllSavingsCategories} from '../services/actions';
import {
  Colors,
  fontSz,
  getSaveAsYouCollectInterestRange,
  globalStyles,
  ms,
  SavingsCategoryType,
  wp,
} from '../utils';

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

export const saveAsYouCollectBenefits: string[] = [
  'Save a part of every inflow into your wallet',
  'Auto save  on',
  'Halaal Compliant',
];

const saveAsYouCollectOption: SavingsCategoryType = {
  id: 3,
  name: 'Save as you collect',
  interestRate: 0,
  isLocked: null,
  lockedPenaltyFeePercentage: null,
  minimumLockDuration: null,
  withdrawalLimit: null,
};

const Savings = ({params, navigate, goBack, isInitialScreen}: Props) => {
  const [selected, setSelected] = useState<SavingsCategoryType | null>(null);
  const {apiKey, primaryColor} = useSDKConfig();

  // Use React Query directly
  const {data, isLoading, isError, refetch} = useQuery({
    queryKey: ['allSavingsCategories', apiKey],
    queryFn: () => getAllSavingsCategories(apiKey),
    staleTime: 5 * 60 * 1000, // 5 minutes
    retry: 2,
  });

  // Set pre-selected category if provided
  useEffect(() => {
    if (params?.preSelectedCategory) {
      setSelected(params.preSelectedCategory);
    }
  }, [params?.preSelectedCategory]);

  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}} />}
        />
        <ScrollView
          showsVerticalScrollIndicator={false}
          keyboardShouldPersistTaps="handled"
          contentContainerStyle={{
            paddingHorizontal: wp(10),
            paddingTop: ms(14),
            paddingBottom: ms(25),
            position: 'relative',
          }}>
          <View style={styles.content}>
            <Text
              fontSize={fontSz(16)}
              lineHeight={fontSz(20)}
              fontFamily="Gordita-Medium"
              fontWeight="500"
              textAlign={'center'}
              text={'We are happy to see you committed to growing your wealth'}
              color={Colors.headerText}
              style={{
                paddingBottom: ms(10),
              }}
            />
            <Text
              fontSize={fontSz(14)}
              lineHeight={fontSz(20)}
              fontFamily="Gordita-Medium"
              fontWeight="500"
              textAlign={'center'}
              text={'Select one of the plans available'}
              color={Colors.chooseAccountTypeText}
              style={{
                paddingBottom: ms(15),
              }}
            />
            {isLoading && (
              <View
                style={{
                  flex: 1,
                  justifyContent: 'center',
                  alignItems: 'center',
                  minHeight: ms(100),
                  paddingTop: ms(20),
                }}>
                <ActivityIndicator size="small" color={primaryColor} />
              </View>
            )}
            {/* map of the savings options */}
            <View style={{rowGap: ms(10)}}>
              {!isLoading &&
                Array.isArray(data) &&
                data?.map((option: SavingsCategoryType, index: any) => {
                  return (
                    <SavingsCategory
                      key={index}
                      position={index}
                      onPress={data => setSelected(data)}
                      option={option}
                      selected={selected}
                    />
                  );
                })}
              {/* {!isLoading && Array.isArray(data) && (
                <SavingsCategory
                  position={2}
                  onPress={data => setSelected(data)}
                  option={saveAsYouCollectOption}
                  selected={selected}
                  range={`${getSaveAsYouCollectInterestRange(data)}`}
                />
              )} */}
            </View>
            {!isLoading &&
              (!Array.isArray(data) || data.length === 0 || isError) && (
                <View
                  style={{
                    flex: 1,
                    justifyContent: 'center',
                    alignItems: 'center',
                    minHeight: ms(100),
                    paddingTop: ms(20),
                  }}>
                  <Text
                    fontSize={fontSz(14)}
                    lineHeight={fontSz(20)}
                    fontFamily="Gordita-Medium"
                    fontWeight="500"
                    textAlign={'center'}
                    text={'No savings options available at the moment.'}
                    color={Colors.chooseAccountTypeText}
                    style={{
                      paddingBottom: ms(10),
                    }}
                  />
                </View>
              )}
          </View>
          <View
            style={{position: 'absolute', alignSelf: 'center', bottom: ms(0)}}>
            <PoweredBy />
          </View>
        </ScrollView>
        <View
          style={{
            paddingHorizontal: wp(20),
          }}>
          <Button
            title={'Get Started'}
            onPress={() => {
              if (selected && (selected.id === 2 || selected.id === 1)) {
                navigate('suggestedPlans', {savingsOption: selected});
              } else if (selected) {
                navigate('savingsForm', {savingsOption: selected});
              }
            }}
            style={{}}
            disabled={selected === null}
          />
        </View>
      </SafeAreaView>
    </>
  );
};

export default Savings;

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