import React, {Fragment, useState} from 'react';
import {
  ActivityIndicator,
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  View,
} from 'react-native';
import {useQuery, useMutation, useQueryClient} from '@tanstack/react-query';
import {
  Colors,
  fontSz,
  globalStyles,
  ms,
  suggestedPlanColors,
  SuggestedPlansOptionsType,
  wp,
} from '../utils';
import {Text} from '../components/Text';
import {Button, CustomPressable, FloatButton} from '../components/Button';
import Header from '../components/Header';
import {ScreenParams, CommonScreenProps} from '../navigation/app';
import {PoweredBy} from '../components/Common/poweredBy';
import {useSDKConfig} from '../contexts/SDKConfigContext';
import {getAllPlans, createPlan} from '../services/actions';
import AddPlanModal from '../components/Modals/addPlan';

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

const SuggestedPlans = ({params, navigate, goBack, isInitialScreen}: Props) => {
  const [selected, setSelected] = useState<SuggestedPlansOptionsType | null>(
    null,
  );
  const [isModalVisible, setIsModalVisible] = useState(false);
  const {apiKey, primaryColor} = useSDKConfig();
  const queryClient = useQueryClient();

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

  // Mutation for creating plans
  const createPlanMutation = useMutation({
    mutationFn: (planName: string) => createPlan(apiKey, planName),
    onSuccess: (response) => {
      if (response?.success || response?.statusCode === 201) {
        // Invalidate and refetch plans
        queryClient.invalidateQueries({ queryKey: ['allPlans', apiKey] });
      } else {
        throw new Error(response?.message || 'Failed to create plan');
      }
    },
    onError: (error: any) => {
      console.error('Failed to create plan:', error);
      throw error;
    },
  });

  const handleCreatePlan = async (planName: string) => {
    await createPlanMutation.mutateAsync(planName);
  };

  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}} />}
        />
        <View style={{flex: 1, paddingHorizontal: wp(10), paddingTop: ms(14)}}>
          <View style={styles.content}>
            <Text
              fontSize={fontSz(16)}
              lineHeight={fontSz(20)}
              fontFamily="Gordita-Medium"
              fontWeight="500"
              textAlign={'left'}
              text={'Suggested Plans'}
              color={Colors.headerText}
              style={{
                paddingBottom: ms(20),
              }}
            />
            {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 type options */}
            <View style={{rowGap: 20}}>
              {!isLoading &&
                Array.isArray(data) &&
                data.map((option: SuggestedPlansOptionsType, index: any) => {
                  const {name, id} = option;
                  return (
                    <Fragment key={index}>
                      <CustomPressable
                        onPress={() => {
                          navigate('savingsForm', {
                            savingsOption: params.savingsOption,
                            suggestedPlan: option,
                          });
                        }}
                        style={{
                          paddingVertical: ms(22.5),
                          paddingHorizontal: ms(20),
                          backgroundColor: suggestedPlanColors[index % suggestedPlanColors.length],
                          borderRadius: ms(4),
                          borderWidth: ms(1),
                          borderColor:
                            id === selected?.id
                              ? primaryColor
                              : suggestedPlanColors[index % suggestedPlanColors.length],
                        }}>
                        <Text
                          fontSize={fontSz(16)}
                          lineHeight={fontSz(20)}
                          fontFamily="Gordita-Medium"
                          fontWeight="500"
                          textAlign={'left'}
                          text={name}
                          color={Colors.headerText}
                        />
                      </CustomPressable>
                    </Fragment>
                  );
                })}
            </View>
            {/* <View
              style={{
                position: 'absolute',
                alignSelf: 'center',
                bottom: ms(-25),
              }}>
              <PoweredBy />
            </View> */}
          </View>
        </View>
        <View
          style={{
            alignItems: 'flex-end',
            position: 'absolute',
            bottom: ms(50),
            right: wp(20),
            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={() => setIsModalVisible(true)}
          />
        </View>

        <AddPlanModal
          visible={isModalVisible}
          onClose={() => setIsModalVisible(false)}
          onCreatePlan={handleCreatePlan}
          isLoading={createPlanMutation.isPending}
        />
      </SafeAreaView>
    </>
  );
};

export default SuggestedPlans;

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