import React, {useEffect, useState, Fragment} from 'react';
import {
  Animated,
  StyleSheet,
  View,
  Text as BaseText,
} from 'react-native';
import {
  Colors,
  fontSz,
  formatAsCurrency,
  globalStyles,
  ms,
  SavingsAccountListType,
} from '../utils';
import {Text} from './Text';
import {CustomPressable} from './Button';
import {Info} from './Common/info';
import InterestBreakdown from './Modals/interestBreakdown';

type PlanCardProps = {
  progress: number;
  backgroundColor: string;
  data: SavingsAccountListType;
  onPress: () => void;
  isLockedSavings?: boolean;
  startDate?: string;
  endDate?: string;
};

const PlanCard = (props: PlanCardProps) => {
  const {progress, backgroundColor, data, onPress, isLockedSavings, startDate, endDate} = props;
  const [showInterestBreakdown, setShowInterestBreakdown] = useState<boolean>(false);

  // Calculate days remaining 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 (!isLockedSavings) {return progress;}

    // If we don't have start/end dates, show amount-based progress for now
    // This should be updated when the API includes these fields
    if (!endDate || !startDate) {
      return progress; // Fallback to amount-based 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 (
    <>
      <CustomPressable
        onPress={onPress}
        style={[
          globalStyles.colBetween,
          {
            rowGap: ms(15),
            backgroundColor: backgroundColor ?? Colors.cardBg,
            paddingHorizontal: ms(10),
            paddingVertical: ms(20),
            borderRadius: ms(8),
          },
        ]}>
        <View style={[globalStyles.rowBetween]}>
          <Text
            color={Colors.payLaterHeaderText}
            fontWeight="700"
            fontFamily={'Gordita-Regular'}
            textAlign={'center'}
            fontSize={fontSz(14)}
            text={data.accountName}
          />
          <CustomPressable
            activeOpacity={Number(data.interestEarned) > 0 ? 0.9 : 1}
            onPress={
              Number(data.interestEarned) > 0
                ? () => setShowInterestBreakdown(true)
                : undefined
            }
            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={'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>
        </View>
        <View style={[globalStyles.rowBetween]}>
          <Text
            color={Colors.payLaterHeaderText}
            fontWeight="400"
            fontFamily={'Gordita-Regular'}
            textAlign={'center'}
            fontSize={fontSz(12)}
            text={isLockedSavings ? `${Number(displayProgress).toFixed(0)}% elapsed` : `${Number(displayProgress).toFixed(0)}% 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.neutral90}
                  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(data?.savingTarget) ?? 0)}`}
                />
              </>
            )}
          </View>
        </View>
        <View
          style={[
            styles.progressBarBackground,
            {backgroundColor: Colors.progressBg},
          ]}>
          <Animated.View
            style={[
              styles.progressBarFill,
              {
                width: widthInterpolated,
                backgroundColor: Colors.darkCornFlowerBlue90,
              },
            ]}
          />
        </View>
        {/* {data?.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(data?.proposedAmount ?? 0),
                  )} `}
                  color={Colors.neutral30}
                />
                will increase your likelihood of meeting your target
              </BaseText>
            }
          />
        )} */}
      </CustomPressable>
      
      {/* Interest Breakdown Modal */}
      <InterestBreakdown
        visible={showInterestBreakdown}
        onClose={() => setShowInterestBreakdown(false)}
        savingsId={data.savingsId}
      />
    </>
  );
};

const styles = StyleSheet.create({
  progressBarBackground: {
    height: 10,
    backgroundColor: '#eee',
    borderRadius: 5,
    overflow: 'hidden',
  },
  progressBarFill: {
    height: '100%',
    backgroundColor: '#4caf50',
    borderRadius: 5,
  },
  walletCardBg: {
    rowGap: ms(5),
    borderRadius: ms(4),
    backgroundColor: 'rgba(255, 255, 255, 0.4)',
    paddingHorizontal: ms(10),
    paddingVertical: ms(5),
  },
});

export default PlanCard;
