import React, {Fragment, useEffect, useState, useMemo, useRef} from 'react';
import {
  Platform,
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  Switch,
  View,
  Text as BaseText,
  Animated,
  ActivityIndicator,
} from 'react-native';
import {ScreenParams, CommonScreenProps} from '../navigation/app';
import {
  calculateSavingsProgress,
  Colors,
  fontSz,
  formatAsCurrency,
  formatDate,
  getInterestRange,
  getOrdinalSuffix,
  globalStyles,
  hp,
  Images,
  isTablet,
  ms,
  wp,
} from '../utils';
import Header from '../components/Header';
import {Text} from '../components/Text';
import {PoweredBy} from '../components/Common/poweredBy';
import {CustomPressable} from '../components/Button';
import {Modal} from '../components/Common/modal';
import Withdraw from '../components/Modals/withdraw';
import {SmartImage} from '../components/Images/SmartImage';
import {Info} from '../components/Common/info';
import InterestCalculation from '../components/Modals/interestCalculation';
import Save from '../components/Modals/save';
import InterestBreakdown from '../components/Modals/interestBreakdown';
import {useSDKConfig} from '../contexts/SDKConfigContext';
import {useQuery} from '@tanstack/react-query';
import {
  getSavingsDetailsBySavingsId,
  getAllSavingsCategories,
} from '../services/actions';
import TransactionsList from '../components/TransactionsList';
import Notification from '../components/Feedback/Notification';

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

type PlanDetailsCardProps = {
  autoSave: boolean;
  setAutoSave: React.Dispatch<React.SetStateAction<boolean>>;
  endDate: string;
  planType: string;
  isLockedSavings?: boolean;
};

type PlanButtonsProps = {
  onPressWithdraw: () => void;
  onPressEdit: () => void;
  onPressSave: () => void;
  isEditDisabled?: boolean;
  isLockedSavings?: boolean;
};

type PlanProgressProps = {
  progress: number;
  savingTarget: number;
  accountBalance: number;
  amountSaved: number;
  proposedAmount?: number | null;
  isLockedSavings?: boolean;
  endDate?: string;
  startDate?: string;
};

const PlanDetailsCard = (props: PlanDetailsCardProps) => {
  const {autoSave, setAutoSave, endDate, planType, isLockedSavings} = props;

  // Check if endDate is valid
  const hasValidEndDate =
    endDate &&
    endDate !== 'Invalid Date' &&
    !isNaN(new Date(endDate).getTime());

  return (
    <View
      style={[
        globalStyles.colBetween,
        {
          rowGap: ms(15),
          backgroundColor: Colors.cardBg,
          paddingHorizontal: ms(15),
          paddingVertical: ms(17.5),
          borderRadius: ms(8),
          borderColor: Colors.disabledButton,
          borderWidth: ms(0.5),
        },
      ]}>
      {hasValidEndDate && (
        <View style={[globalStyles.rowBetween]}>
          <Text
            fontSize={fontSz(13)}
            fontFamily="Gordita-Regular"
            fontWeight="400"
            textAlign={'left'}
            text={isLockedSavings ? 'Maturity Date:' : 'End Date:'}
            color={Colors.completeTransactionTitle}
          />
          <Text
            fontSize={fontSz(13)}
            fontFamily="Gordita-Regular"
            fontWeight="500"
            textAlign={'right'}
            text={`${formatDate(endDate, 'DD-MMM-YYYY')}`}
            color={Colors.completeTransactionTitle}
          />
        </View>
      )}
      <View style={[globalStyles.rowBetween]}>
        <Text
          fontSize={fontSz(13)}
          fontFamily="Gordita-Regular"
          fontWeight="400"
          textAlign={'left'}
          text={'Plan:'}
          color={Colors.completeTransactionTitle}
        />
        <Text
          fontSize={fontSz(13)}
          fontFamily="Gordita-Regular"
          fontWeight="500"
          textAlign={'right'}
          text={planType}
          color={Colors.completeTransactionTitle}
        />
      </View>
      {/* Hide Auto Save section for locked savings */}
      {!isLockedSavings && (
        <View style={[globalStyles.rowBetween]}>
          <Text
            fontSize={fontSz(13)}
            fontFamily="Gordita-Regular"
            fontWeight="400"
            textAlign={'left'}
            text={'Autosave'}
            color={Colors.completeTransactionTitle}
          />
          <Switch
            value={autoSave}
            onValueChange={() => {
              setAutoSave(!autoSave);
            }}
            trackColor={{
              false: 'rgba(236, 236, 236, 1)',
              true: 'rgba(237, 230, 255, 1)',
            }}
            thumbColor={autoSave ? 'rgba(166, 130, 255, 1)' : '#979797'}
            ios_backgroundColor={
              autoSave ? 'rgba(166, 130, 255, 1)' : 'rgba(236, 236, 236, 1)'
            }
            style={[
              {
                marginLeft: ms(-7.5),
              },
              {
                transform: [
                  {scaleX: Platform.OS === 'android' ? 0.9 : 0.6},
                  {scaleY: Platform.OS === 'android' ? 0.9 : 0.6},
                ],
              },
            ]}
          />
        </View>
      )}
    </View>
  );
};

const PlanButtons = (props: PlanButtonsProps) => {
  const {
    onPressWithdraw,
    onPressEdit,
    onPressSave,
    isEditDisabled,
    isLockedSavings,
  } = props;
  return (
    <View
      style={[
        globalStyles.rowBetween,
        {marginBottom: ms(12), marginTop: ms(4)},
      ]}>
      <CustomPressable
        activeOpacity={0.85}
        onPress={onPressWithdraw}
        style={[
          styles.button,
          {
            borderColor: Colors.purple60,
            borderWidth: ms(1),
          },
        ]}>
        <Text
          fontSize={fontSz(14)}
          lineHeight={fontSz(16)}
          fontFamily="Gordita-Regular"
          fontWeight="400"
          textAlign={'left'}
          text={'Withdraw'}
          color={Colors.purple60}
        />
      </CustomPressable>
      <CustomPressable
        activeOpacity={0.85}
        onPress={isEditDisabled || isLockedSavings ? undefined : onPressEdit}
        style={[
          styles.button,
          {
            backgroundColor:
              isEditDisabled || isLockedSavings
                ? Colors.purple90
                : Colors.purple60,
          },
        ]}>
        <Text
          fontSize={fontSz(14)}
          lineHeight={fontSz(16)}
          fontFamily="Gordita-Regular"
          fontWeight="400"
          textAlign={'left'}
          text={'Edit'}
          color={Colors.white}
        />
      </CustomPressable>
      <CustomPressable
        activeOpacity={0.85}
        onPress={isLockedSavings ? undefined : onPressSave}
        style={[
          styles.button,
          {
            backgroundColor: isLockedSavings
              ? Colors.purple90
              : Colors.purple60,
          },
        ]}>
        <Text
          fontSize={fontSz(14)}
          lineHeight={fontSz(16)}
          fontFamily="Gordita-Regular"
          fontWeight="400"
          textAlign={'left'}
          text={'Save'}
          color={Colors.white}
        />
      </CustomPressable>
    </View>
  );
};

const PlanProgress = (props: PlanProgressProps) => {
  const {
    progress,
    savingTarget,
    proposedAmount,
    isLockedSavings,
    endDate,
    startDate,
  } = props;

  // Calculate days remaining and time-based progress for locked savings
  const getDaysRemaining = () => {
    if (!endDate || !isLockedSavings) {
      return null;
    }

    const today = new Date();
    const maturityDate = new Date(endDate);
    const timeDiff = maturityDate.getTime() - today.getTime();
    const daysRemaining = Math.ceil(timeDiff / (1000 * 3600 * 24));

    if (daysRemaining <= 0) {
      return 'Matured';
    }
    return `${daysRemaining} day${daysRemaining === 1 ? '' : 's'} left`;
  };

  // Calculate time-based progress for locked savings
  const getTimeBasedProgress = () => {
    if (!endDate || !startDate || !isLockedSavings) {
      return progress;
    }

    const today = new Date();
    const maturityDate = new Date(endDate);
    const lockStartDate = new Date(startDate);

    if (today >= maturityDate) {
      return 100;
    } // Matured

    // Calculate total lock duration in milliseconds
    const totalLockDuration = maturityDate.getTime() - lockStartDate.getTime();

    // Calculate elapsed time since lock started
    const elapsedTime = today.getTime() - lockStartDate.getTime();

    // Calculate progress as percentage of time elapsed
    const timeProgress = Math.max(
      0,
      Math.min(100, Math.round((elapsedTime / totalLockDuration) * 100)),
    );

    return timeProgress;
  };

  const displayProgress = isLockedSavings ? getTimeBasedProgress() : progress;
  const progressAnim = new Animated.Value(displayProgress);

  useEffect(() => {
    Animated.timing(progressAnim, {
      toValue: displayProgress,
      duration: 500,
      useNativeDriver: false,
    }).start();
  }, [displayProgress]);

  const widthInterpolated = progressAnim.interpolate({
    inputRange: [0, 100],
    outputRange: ['0%', '100%'],
  });

  return (
    <View
      style={{
        rowGap: ms(15),
        paddingHorizontal: ms(10),
        paddingVertical: ms(10),
        borderWidth: ms(1),
        borderColor: Colors.neutral100,
        borderRadius: ms(8),
        marginVertical: ms(10),
      }}>
      <View style={[globalStyles.rowBetween]}>
        <Text
          color={Colors.payLaterHeaderText}
          fontWeight="400"
          fontFamily={'Gordita-Regular'}
          textAlign={'center'}
          fontSize={fontSz(12)}
          text={
            isLockedSavings
              ? `${displayProgress}% elapsed`
              : `${displayProgress}% completed`
          }
        />
        <View
          style={[
            globalStyles.colStart,
            {alignItems: 'flex-end', rowGap: ms(5)},
          ]}>
          {isLockedSavings ? (
            // Show days remaining for locked savings
            <Text
              color={Colors.payLaterHeaderText}
              fontWeight="600"
              fontFamily={'Gordita-Medium'}
              textAlign={'center'}
              fontSize={fontSz(14)}
              text={getDaysRemaining() || ''}
            />
          ) : (
            // Show target for flexible savings
            <>
              <Text
                color={Colors.neutral100}
                fontWeight="500"
                fontFamily={'Gordita-Medium'}
                textAlign={'center'}
                fontSize={fontSz(10)}
                text={'Target'}
              />
              <Text
                color={Colors.payLaterHeaderText}
                fontWeight="600"
                fontFamily={'Gordita-Medium'}
                textAlign={'center'}
                fontSize={fontSz(14)}
                text={`${formatAsCurrency(Number(savingTarget))}`}
              />
            </>
          )}
        </View>
      </View>
      <View
        style={[
          styles.progressBarBackground,
          {backgroundColor: Colors.progressBg},
        ]}>
        <Animated.View
          style={[
            styles.progressBarFill,
            {
              width: widthInterpolated,
              //   width: `${progress}%`,
              backgroundColor: Colors.darkCornFlowerBlue90,
            },
          ]}
        />
      </View>
      {/* Show proposed amount tip only for flexible savings */}
      {/* {!isLockedSavings && proposedAmount && (
        <Info
          text={
            <BaseText
              style={{
                fontSize: fontSz(10),
                fontFamily: 'Gordita-Regular',
                fontWeight: '400',
                color: Colors.neutral30,
                width: '90%',
              }}>
              Increasing your deposit to
              <Text
                fontSize={fontSz(10)}
                fontFamily="Gordita-Regular"
                fontWeight="700"
                text={` ${formatAsCurrency(Number(proposedAmount ?? 0))} `}
                color={Colors.neutral30}
              />
              will increase your likelihood of meeting your target
            </BaseText>
          }
        />
      )} */}
    </View>
  );
};

const Plan = ({params, navigate, goBack, isInitialScreen}: Props) => {
  const [autoSave, setAutoSave] = useState<boolean>(false);
  const [showWithdraw, setShowWithdraw] = useState<boolean>(false);
  const [showSave, setShowSave] = useState<boolean>(false);
  const [showInterestCalculation, setShowInterestCalculation] =
    useState<boolean>(false);
  const [showInterestBreakdown, setShowInterestBreakdown] =
    useState<boolean>(false);
  const [showWithdrawalWarning, setShowWithdrawalWarning] =
    useState<boolean>(false);
  const [showEarlyWithdrawalWarning, setShowEarlyWithdrawalWarning] =
    useState<boolean>(false);
  const [screenData, setScreenData] = useState({
    data: {},
    isLoading: false,
    isError: false,
  });
  const listRef = useRef(null);
  const {apiKey, primaryColor} = useSDKConfig();

  // Query for savings details
  const {data, isLoading, isError, refetch} = useQuery({
    queryKey: ['savingsDetails', params?.planId, apiKey],
    queryFn: () => getSavingsDetailsBySavingsId(apiKey, params?.planId || ''),
    staleTime: 5 * 60 * 1000, // 5 minutes
    retry: 2,
    enabled: !!params?.planId, // Only run query if planId exists
  });

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

  // Get withdrawal limit for the current plan's category
  const getWithdrawalLimit = () => {
    if (!data?.categoryName || !Array.isArray(categoriesData)) {
      return null;
    }

    const matchingCategory = categoriesData.find(
      (category: any) =>
        category.name?.toLowerCase() === data.categoryName?.toLowerCase(),
    );

    return matchingCategory?.withdrawalLimit || null;
  };

  const withdrawalLimit = getWithdrawalLimit();
  const isLoadingData = isLoading || categoriesLoading;

  // Check if savings account is locked and has early withdrawal penalties
  const getSavingsCategory = () => {
    if (!data?.categoryName || !Array.isArray(categoriesData)) {
      return null;
    }

    const matchingCategory = categoriesData.find(
      (category: any) =>
        category.name?.toLowerCase() === data.categoryName?.toLowerCase(),
    );

    return matchingCategory || null;
  };

  const savingsCategory = getSavingsCategory();
  const isLockedSavings = data?.isLocked || false;
  const penaltyFeePercentage = savingsCategory?.lockedPenaltyFeePercentage || 0;

  // Check if withdrawal is before maturity date
  const isBeforeMaturity = () => {
    if (!data?.endDate || !isLockedSavings) {
      return false;
    }
    const endDate = new Date(data.endDate);
    const currentDate = new Date();
    return currentDate < endDate;
  };

  // Check if transactions exist (amount saved > 0 means transactions have been made)
  const hasTransactions = data?.amountSaved > 0;

  // Handle edit navigation
  const handleEditPress = () => {
    const savingsCategory = getSavingsCategory();
    if (savingsCategory) {
      navigate('savingsForm', {
        savingsOption: savingsCategory,
        editMode: true,
        existingSavingsData: data,
      });
    }
  };

  // Handle withdraw button press with limit check
  const handleWithdrawPress = () => {
    const currentWithdrawals = data?.noOfWithdrawals || 0;
    const limit = withdrawalLimit || 3;

    // Check for early withdrawal penalty first
    if (isLockedSavings && penaltyFeePercentage > 0 && isBeforeMaturity()) {
      setShowEarlyWithdrawalWarning(true);
      return;
    }

    // Show warning when user is at withdrawal limit and about to exceed it
    if (currentWithdrawals === limit) {
      setShowWithdrawalWarning(true);
    } else {
      setShowWithdraw(true);
    }
  };

  // Open withdrawal modal after user confirms they want to proceed despite warning
  const handleProceedWithWithdrawal = () => {
    setShowWithdrawalWarning(false);
    setShowWithdraw(true);
  };

  // Open withdrawal modal after user confirms early withdrawal penalty
  const handleProceedWithEarlyWithdrawal = () => {
    setShowEarlyWithdrawalWarning(false);

    // Still need to check withdrawal limit after penalty confirmation
    const currentWithdrawals = data?.noOfWithdrawals || 0;
    const limit = withdrawalLimit || 3;

    if (currentWithdrawals === limit) {
      setShowWithdrawalWarning(true);
    } else {
      setShowWithdraw(true);
    }
  };

  useEffect(() => {
    if (data) {
      setAutoSave(data?.autoSave);
    }
  }, [data]);

  console.log(params.planId, 'data', data);

  const getWalletBalanceLoader = () => {
    if (isLoadingData) {
      return <ActivityIndicator size={'small'} color={Colors.white} />;
    } else {
      return (
        <View style={globalStyles.rowCenter}>
          <Text
            color={Colors.payLaterHeaderText}
            fontWeight="700"
            fontFamily={'Gordita-Medium'}
            textAlign={'center'}
            fontSize={fontSz(20)}
            text={`${formatAsCurrency(Number(data?.accountBalance) ?? 0)}`}
          />
        </View>
      );
    }
  };

  const displayWalletCard = () => {
    const interestRange = data
      ? `${getInterestRange(data).min} - ${getInterestRange(data).max}`
      : '0 - 0';
    return (
      <View
        style={{
          width: '100%',
          alignItems: 'center',
          position: 'relative',
          marginBottom: ms(2.5),
          marginTop: ms(5),
          borderRadius: ms(10),
          ...(isTablet
            ? {
                minHeight: 220,
                backgroundColor: primaryColor,
              }
            : {}),
        }}>
        <SmartImage
          style={[styles.walletCardImage]}
          source={Images.savingsWalletCard}
        />
        <View style={styles.walletCardOverlay}>
          <View style={[globalStyles.rowEnd, {}]}>
            <CustomPressable
              onPress={() => {}}
              style={[
                {
                  flexDirection: 'row',
                  alignItems: 'center',
                  backgroundColor: Colors.savingsWalletCardBg,
                  borderRadius: ms(10),
                  paddingHorizontal: wp(7.5),
                  paddingVertical: wp(4),
                  columnGap: ms(4),
                },
              ]}>
              <Text
                style={{
                  color: Colors.payLaterHeaderText,
                }}
                fontFamily={'Gordita-Medium'}
                fontWeight="500"
                fontSize={fontSz(10)}
                text={`${data?.interestRate}% per annum`}
              />
            </CustomPressable>
          </View>
          <View
            style={[
              globalStyles.colCenter,
              {
                flex: 0.7,
                alignSelf: 'center',
                justifyContent: 'center',
                rowGap: ms(1.5),
              },
            ]}>
            <Text
              color={Colors.payLaterHeaderText}
              fontWeight="500"
              textAlign={'center'}
              fontSize={fontSz(14)}
              text={`${data?.accountName}`}
            />
            {getWalletBalanceLoader()}
          </View>
          <View
            style={[
              globalStyles.rowBetween,
              {
                paddingTop: hp(10),
              },
            ]}>
            <CustomPressable
              activeOpacity={Number(data?.interestEarned) > 0 ? 0.9 : 1}
              onPress={
                Number(data?.interestEarned) > 0
                  ? () => setShowInterestBreakdown(true)
                  : undefined
              }
              style={[globalStyles.colStart, styles.walletCardBg, {}]}>
              <Text
                color={Colors.payLaterHeaderText}
                fontFamily={'Gordita-Regular'}
                fontWeight="500"
                fontSize={fontSz(8)}
                lineHeight={fontSz(8 * 1.14)}
                text={'Interest Earned'}
              />
              <Text
                color={Colors.payLaterHeaderText}
                fontFamily={'Gordita-Medium'}
                fontWeight="900"
                fontSize={fontSz(12)}
                lineHeight={fontSz(12 * 1.14)}
                text={`${formatAsCurrency(Number(data?.interestEarned) ?? 0)}`}
              />
            </CustomPressable>

            {withdrawalLimit && (
              <CustomPressable
                activeOpacity={0.9}
                onPress={() => {}}
                style={[
                  globalStyles.colStart,
                  styles.walletCardBg,
                  {alignItems: 'flex-end'},
                ]}>
                <Text
                  color={Colors.payLaterHeaderText}
                  fontFamily={'Gordita-Regular'}
                  fontWeight="500"
                  fontSize={fontSz(8)}
                  lineHeight={fontSz(8 * 1.14)}
                  text={'Withdrawals'}
                />
                <BaseText
                  style={{
                    fontSize: fontSz(10),
                    fontFamily: 'Gordita-Regular',
                    fontWeight: '400',
                    color: Colors.payLaterHeaderText,
                  }}>
                  <Text
                    color={Colors.payLaterHeaderText}
                    fontFamily={'Gordita-Medium'}
                    fontWeight="900"
                    fontSize={fontSz(12)}
                    lineHeight={fontSz(12 * 1.14)}
                    text={`${data?.noOfWithdrawals || 0} `}
                  />
                  out of {withdrawalLimit} this month
                </BaseText>
              </CustomPressable>
            )}
          </View>
        </View>
      </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}} />}
        />
        <View
          style={{
            flex: 1,
            paddingHorizontal: wp(10),
            paddingTop: ms(14),
          }}>
          {/* <Text
            fontSize={fontSz(14)}
            lineHeight={fontSz(16)}
            fontFamily="Gordita-Regular"
            fontWeight="400"
            textAlign={'left'}
            text={'What do you want to save for?'}
            color={Colors.headerText}
            style={{
              paddingBottom: ms(15),
            }}
          /> */}
          <View style={[styles.content]}>
            {isLoadingData ? (
              <View
                style={{
                  flex: 1,
                  justifyContent: 'center',
                  alignItems: 'center',
                }}>
                <ActivityIndicator size="small" color={primaryColor} />
              </View>
            ) : (
              <>
                <ScrollView
                  nestedScrollEnabled
                  showsVerticalScrollIndicator={false}
                  keyboardShouldPersistTaps="handled">
                  {displayWalletCard()}
                  <PlanProgress
                    progress={
                      calculateSavingsProgress(
                        data?.savingTarget,
                        data?.amountSaved,
                      ) ?? 0
                    }
                    savingTarget={data?.savingTarget ?? 0}
                    accountBalance={data?.accountBalance ?? 0}
                    amountSaved={data?.amountSaved ?? 0}
                    proposedAmount={data?.proposedAmount}
                    isLockedSavings={isLockedSavings}
                    endDate={data?.endDate}
                    startDate={data?.startDate}
                  />
                  <PlanButtons
                    onPressWithdraw={handleWithdrawPress}
                    onPressEdit={handleEditPress}
                    onPressSave={() => setShowSave(true)}
                    isEditDisabled={false}
                    isLockedSavings={isLockedSavings}
                  />
                  <PlanDetailsCard
                    planType={data?.categoryName}
                    endDate={data?.endDate}
                    autoSave={autoSave}
                    setAutoSave={setAutoSave}
                    isLockedSavings={isLockedSavings}
                  />
                  {hasTransactions && (
                    <>
                      <View
                        style={[
                          globalStyles.rowBetween,
                          {
                            paddingTop: hp(22),
                            paddingBottom: hp(8),
                          },
                        ]}>
                        {/* <Text
                          color={Colors.accountTransactions}
                          fontWeight="500"
                          fontFamily={'Gordita-Medium'}
                          fontSize={fontSz(16)}
                          lineHeight={fontSz(16 * 1.5)}
                          text={'History'}
                        /> */}
                        {/* <CustomPressable
                          activeOpacity={0.9}
                          onPress={() => {
                            navigate('history', {
                              planId: params?.planId,
                              planName: params?.planName,
                            });
                          }}>
                          <Text
                            color={primaryColor}
                            fontWeight="500"
                            fontFamily={'Gordita-Medium'}
                            fontSize={fontSz(14)}
                            lineHeight={fontSz(14 * 1.33)}
                            text={`View More`}
                          />
                        </CustomPressable> */}
                      </View>
                      <TransactionsList
                        savingsId={params?.planId || ''}
                        recordsPerPage={3}
                        limit={3}
                        showScrollIndicator={false}
                        scrollEnabled={false}
                        showTabs={true}
                      />
                    </>
                  )}
                </ScrollView>
                {/* <View
                  style={{
                    alignSelf: 'center',
                    marginTop: ms(10),
                  }}>
                  <PoweredBy />
                </View> */}
              </>
            )}
          </View>
        </View>
      </SafeAreaView>
      <Withdraw
        visible={showWithdraw}
        onClose={() => setShowWithdraw(false)}
        onPressContinue={() => {}}
        resetPin={() => {}}
        plan={{
          ...data,
          noOfWithdrawals: data?.noOfWithdrawals ?? 0,
        }}
        withdrawalLimit={withdrawalLimit}
        isLockedSavings={isLockedSavings}
        penaltyFeePercentage={penaltyFeePercentage}
        isBeforeMaturity={isBeforeMaturity()}
      />
      <Modal
        visible={showInterestCalculation}
        title="Interest Calculation"
        onClose={() => setShowInterestCalculation(false)}>
        <InterestCalculation
          closeModal={() => setShowInterestCalculation(false)}
          onPressContinue={() => {}}
        />
      </Modal>
      <Save
        visible={showSave}
        closeModal={() => setShowSave(false)}
        savingsAccountName={data?.accountName}
        savingsId={params?.planId || ''}
      />
      <InterestBreakdown
        visible={showInterestBreakdown}
        onClose={() => setShowInterestBreakdown(false)}
        savingsId={params?.planId || ''}
      />

      {/* Withdrawal Warning Notification */}
      {showWithdrawalWarning && (
        <Notification
          title="Interest Earnings at Risk"
          description={`You'll forfeit this month's interest earnings if you proceed for the ${
            (withdrawalLimit || 3) + 1
          }${getOrdinalSuffix((withdrawalLimit || 3) + 1)} time.

Consider waiting until next month to avoid losing your interest.`}
          image={Images.warning}
          buttonText="Proceed"
          onButtonPress={handleProceedWithWithdrawal}
          onClose={() => setShowWithdrawalWarning(false)}
          minHeight={ms(420)}
        />
      )}

      {/* Early Withdrawal Warning Notification */}
      {showEarlyWithdrawalWarning && (
        <Notification
          title="Withdrawal Before Maturity"
          description={`You are about to withdraw from your locked savings account before the maturity date and will be charged a fee of ${penaltyFeePercentage}%`}
          image={Images.warning}
          buttonText="Proceed"
          onButtonPress={handleProceedWithEarlyWithdrawal}
          onClose={() => setShowEarlyWithdrawalWarning(false)}
          minHeight={ms(380)}
        />
      )}
    </>
  );
};

export default Plan;

const styles = StyleSheet.create({
  content: {
    flex: 1,
    height: '100%',
    paddingVertical: ms(12.5),
    paddingBottom: ms(10),
    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(12.5),
    position: 'absolute',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingTop: ms(75),
  },
  button: {
    width: '31%',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: ms(13.5),
    borderRadius: ms(8),
  },
  walletCardBg: {
    // width: '40%',
    rowGap: ms(5),
    borderRadius: ms(4),
    backgroundColor: 'rgba(255, 255, 255, 0.4)',
    paddingHorizontal: ms(10),
    paddingVertical: ms(4),
  },
  progressBarBackground: {
    height: 10,
    backgroundColor: '#eee',
    borderRadius: 5,
    overflow: 'hidden',
  },
  progressBarFill: {
    height: '100%',
    backgroundColor: '#4caf50',
    borderRadius: 5,
  },
});
