import React, {Fragment, useState} from 'react';
import {
  StyleSheet,
  Text as BaseText,
  GestureResponderEvent,
  View,
  StyleProp,
  ViewStyle,
} from 'react-native';
import {SmartImage} from '../Images/SmartImage';
import {Colors, fontSz, formatAsCurrency, Images, ms, wp, globalStyles} from '../../utils';
import {Button, CustomPressable} from '../Button';
import OtpInput from '../Input/otp';
import CurrencyInput from '../Input/currency';
import {Text} from '../Text';
import useHandleChange from '../../hooks/useHandleChangeNotrim';
import {Info} from '../Common/info';
import CheckBox from '../RadioButton/checkBox';
import {useSDKConfig} from '../../contexts/SDKConfigContext';
import {Modal} from '../Common/modal';
import {useMutation, useQueryClient} from '@tanstack/react-query';
import {withdrawFromSavingsAccount} from '../../services/actions';
import Notification from '../Feedback/Notification';

type Props = {
  visible: boolean;
  onClose: () => void;
  onPressContinue: (transactionId: string) => void;
  resetPin: () => void;
  plan: any;
  withdrawalLimit?: number | null;
  isLockedSavings?: boolean;
  penaltyFeePercentage?: number;
  isBeforeMaturity?: boolean;
};

type WithdrawalDurationProps = {
  numberOfTimes: string;
  withdrawalLimit?: number | null;
  containerStyle?: StyleProp<ViewStyle>;
};

const WithdrawalDuration = (props: WithdrawalDurationProps) => {
  const {numberOfTimes, withdrawalLimit, containerStyle} = props;
  return (
    <View
      style={[
        {
          paddingVertical: ms(10),
          paddingHorizontal: ms(10),
          rowGap: ms(7.5),
          borderRadius: ms(4),
          backgroundColor: Colors.neutral0X,
        },
        containerStyle,
      ]}>
      <Text
        fontSize={fontSz(12)}
        lineHeight={fontSz(12 * 1.2)}
        fontFamily={'Gordita-Regular'}
        fontWeight="400"
        text={`${'Withdrawal this month'}`}
        color={Colors.payLaterHeaderText}
        textAlign={'center'}
      />
      <Text
        fontSize={fontSz(12)}
        lineHeight={fontSz(12 * 1.2)}
        fontFamily={'Gordita-Medium'}
        fontWeight="900"
        text={`${numberOfTimes} out of ${withdrawalLimit || 3} times`}
        color={Colors.payLaterHeaderText}
        textAlign={'center'}
      />
    </View>
  );
};

const Withdraw = (props: Props) => {
  const {visible, onClose, onPressContinue, resetPin, plan, withdrawalLimit, isLockedSavings, penaltyFeePercentage, isBeforeMaturity} = props;
  const [agreement, setAgreement] = useState<boolean>(false);
  const [showSuccessNotification, setShowSuccessNotification] = useState(false);
  const {primaryColor, apiKey} = useSDKConfig();
  const queryClient = useQueryClient();
  const [errors, setErrors] = useHandleChange({
    code: '',
    amount: '',
  });

  const [details, setDetails] = useHandleChange({
    code: '',
    amount: '',
  });

  const {code, amount} = details;

  const useableSavingsBalance = Number(plan?.accountBalance ?? 0);
  const withdrawalAmount = Number(amount);

  // Calculate penalty fee for early withdrawal from locked savings
  const penaltyFee = (isLockedSavings && isBeforeMaturity && penaltyFeePercentage)
    ? (withdrawalAmount * penaltyFeePercentage) / 100
    : 0;

  const totalDeduction = withdrawalAmount + penaltyFee;
  const netAmountReceived = withdrawalAmount - penaltyFee;

  // Mutation for withdrawing from savings account
  const {
    mutate: withdrawSavings,
    isPending: isWithdrawPending,
  } = useMutation({
    mutationFn: (params: {savingsId: string; amount: number}) =>
      withdrawFromSavingsAccount(apiKey, params),
    onSuccess: (response) => {
      if (response?.success) {
        queryClient.invalidateQueries({
          queryKey: ['savingsDetails', plan?.savingsId, apiKey],
        });
        queryClient.invalidateQueries({
          queryKey: ['walletBalance', apiKey],
        });
        queryClient.invalidateQueries({
          queryKey: ['savingsListByCustomerId', apiKey],
        });
        queryClient.invalidateQueries({
          queryKey: ['totalAccountTransactionsByCustomerId', apiKey],
        });

        setShowSuccessNotification(true);
      }
    },
    onError: (error) => {
      console.error('Withdraw from savings account error:', error);
    },
  });

  function updateAmount(value: string) {
    setDetails('amount', value);
    const withdrawAmount = Number(value);
    const penalty = (isLockedSavings && isBeforeMaturity && penaltyFeePercentage)
      ? (withdrawAmount * penaltyFeePercentage) / 100
      : 0;
    const total = withdrawAmount + penalty;

    if (total > useableSavingsBalance) {
      setErrors(
        'amount',
        `Total deduction (₦${formatAsCurrency(total)}) exceeds your balance of ${formatAsCurrency(useableSavingsBalance)}`,
      );
    } else {
      setErrors('amount', '');
    }
  }
  function updateCode(value: string) {
    setDetails('code', value);
    setErrors('code', '');
  }
  function updateAgreement() {
    setAgreement(!agreement);
  }

  const handleWithdraw = () => {
    if (!amount || Number(amount) <= 0) {
      return;
    }

    // Convert amount to kobo (multiply by 100)
    const amountInKobo = Math.round(Number(amount) * 100);

    withdrawSavings({
      savingsId: plan?.savingsId,
      amount: amountInKobo,
    });
  };

  const handleSuccessNotificationClose = () => {
    setShowSuccessNotification(false);
    onClose();
  };

  // Calculate if user is about to cross the withdrawal limit (show warning only when crossing over)
  const isAboutToCrossLimit = Number(plan?.noOfWithdrawals) === (withdrawalLimit || 3);

  // Determine if withdrawal button should be disabled
  const isWithdrawDisabled = () => {
    // Basic validation
    if (!amount || Number(amount) <= 0 || errors.amount.length > 0) {
      return true;
    }

    // Check if user is about to cross withdrawal limit and needs to agree
    if (isAboutToCrossLimit && !agreement) {
      return true;
    }

    return false;
  };

  return (
    <>
      <Modal
        visible={visible && !showSuccessNotification}
        title="Withdraw"
        onClose={onClose}
        footer={
          <Button
            title={
              !amount || Number(amount) <= 0
                ? 'Withdraw'
                : `Withdraw ${formatAsCurrency(Number(amount))}`
            }
            onPress={handleWithdraw}
            disabled={isWithdrawDisabled()}
            isLoading={isWithdrawPending}
            // disabled={pin.length !== 4}
          />
        }>
        <View
          style={{
            paddingHorizontal: wp(15),
            minHeight: isAboutToCrossLimit  || isLockedSavings ? ms(450) : ms(350),
            // alignItems: 'center',
          }}>
          <SmartImage
            source={Images.completeTransaction}
            style={{
              width: ms(48),
              height: ms(48),
              alignSelf: 'center',
            }}
          />
          {!isLockedSavings && (
            <WithdrawalDuration
              numberOfTimes={String(plan?.noOfWithdrawals || 0)}
              containerStyle={{marginTop: ms(10), alignSelf: 'center'}}
              withdrawalLimit={withdrawalLimit}
            />
          )}
          <Text
            fontSize={fontSz(14)}
            lineHeight={fontSz(15.11)}
            fontWeight="400"
            text={`Withdraw from your ${plan?.accountName} Savings Account`}
            color={Colors.completeTransactionTitle}
            textAlign={'center'}
            style={{
              paddingTop: ms(30),
              paddingBottom: ms(20),
            }}
          />
          <CurrencyInput
            value={amount}
            key={useableSavingsBalance.toString()}
            onChangeValue={(value: any) => {
              updateAmount(value);
            }}
            ignoreNegative={false}
            delimiter=","
            separator="."
            precision={2}
            returnKeyType="done"
            topComponent={<></>}
            walletAmount={useableSavingsBalance}
            paymentAmount={withdrawalAmount}
            onPressUseAllBalance={() => {
              setDetails('amount', String(useableSavingsBalance));
              setErrors('amount', '');
            }}
            onEndEditing={() => {}}
            onFocus={() => {}}
            label={'Amount'}
            showAsterisk={false}
            placeholder={''}
            balance={useableSavingsBalance}
            errorMsg={errors.amount || ''}
            showUseAllBalance={useableSavingsBalance > 0}
            showCurrency
          />

          {/* Show fee breakdown for early withdrawal from locked savings */}
          {isLockedSavings && isBeforeMaturity && penaltyFeePercentage && penaltyFeePercentage > 0 && withdrawalAmount > 0 && (
            <View style={{
              backgroundColor: Colors.neutral0X,
              borderRadius: ms(8),
              padding: ms(16),
              marginTop: ms(32),
              marginBottom: ms(8),
            }}>
              <Text
                fontSize={fontSz(13)}
                fontFamily="Gordita-Medium"
                fontWeight="500"
                text="Fee Breakdown"
                color={Colors.completeTransactionTitle}
                style={{marginBottom: ms(12)}}
              />

              <View style={{rowGap: ms(8)}}>
                <View style={globalStyles.rowBetween}>
                  <Text
                    fontSize={fontSz(12)}
                    fontFamily="Gordita-Regular"
                    fontWeight="400"
                    text="Withdrawal Amount"
                    color={Colors.payLaterHeaderText}
                  />
                  <Text
                    fontSize={fontSz(12)}
                    fontFamily="Gordita-Medium"
                    fontWeight="500"
                    text={formatAsCurrency(withdrawalAmount)}
                    color={Colors.completeTransactionTitle}
                  />
                </View>

                <View style={globalStyles.rowBetween}>
                  <Text
                    fontSize={fontSz(12)}
                    fontFamily="Gordita-Regular"
                    fontWeight="400"
                    text={`Early Withdrawal Fee (${penaltyFeePercentage}%)`}
                    color={Colors.payLaterHeaderText}
                  />
                  <Text
                    fontSize={fontSz(12)}
                    fontFamily="Gordita-Medium"
                    fontWeight="500"
                    text={`-${formatAsCurrency(penaltyFee)}`}
                    color={Colors.debitRed}
                  />
                </View>

                <View style={{
                  height: 1,
                  backgroundColor: Colors.neutral20,
                  marginVertical: ms(4),
                }} />

                <View style={globalStyles.rowBetween}>
                  <Text
                    fontSize={fontSz(13)}
                    fontFamily="Gordita-Medium"
                    fontWeight="600"
                    text="You'll Receive"
                    color={Colors.completeTransactionTitle}
                  />
                  <Text
                    fontSize={fontSz(14)}
                    fontFamily="Gordita-Medium"
                    fontWeight="600"
                    text={formatAsCurrency(netAmountReceived)}
                    color={Colors.creditGreen}
                  />
                </View>
              </View>
            </View>
          )}

          {/* Show warning when user is about to cross withdrawal limit */}
          {isAboutToCrossLimit && (
            <Info
              text={'Withdrawal Limit Reached, Interest at stake'}
              containerStyle={{marginBottom: ms(16), marginTop: ms(32)}}
            />
          )}

          {isAboutToCrossLimit && (
            <CheckBox
              containerStyle={{marginBottom: ms(20), marginTop: ms(15)}}
              label={'I agree to lose my interest on my next withdrawal.'}
              selected={agreement}
              onPress={() => updateAgreement()}
            />
          )}
        </View>
      </Modal>

      {showSuccessNotification && (
        <Notification
          title="Withdrawal Successful"
          description={`Your main account balance has been credited with ${formatAsCurrency(Number(netAmountReceived))}`}
          image={Images.credited}
          buttonText="Close"
          onButtonPress={handleSuccessNotificationClose}
        />
      )}
    </>
  );
};

export default Withdraw;

const styles = StyleSheet.create({
  textFoot: {
    fontFamily: 'Gordita-Regular',
    fontSize: fontSz(16),
    color: Colors.gray500,
    fontWeight: '400',
  },
  resetPin: {
    fontFamily: 'Gordita-Medium',
    fontSize: fontSz(16),
    fontWeight: '500',
  },
});
