import React from 'react';
import {View, StyleSheet, TouchableOpacity} from 'react-native';
import {Text} from '../Text';
import {
  Colors,
  fontSz,
  ms,
  formatAsCurrency,
  FrequencyType,
  getFrequencyEnum,
} from '../../utils';
import {
  calculateFinalBalanceWithCompoundInterest as calculateFinalBalance,
  calculateProjectedInterestEarnings,
  calculateRequiredPeriodicAmountWithInterest,
} from '../../utils/savingsCalculations';

type Props = {
  currentRate: number;
  savingsTarget: number;
  periodicSavingsAmount: number;
  selectedFrequency: FrequencyType;
  startDate: Date | null;
  endDate: Date | null;
  isInterestDisabled?: boolean;
  onSectionLayout?: (event: any) => void;
  onAutoCalculate?: (calculatedAmount: number) => void;
};

const FlexibleInterestDisplay = ({
  currentRate,
  savingsTarget,
  periodicSavingsAmount,
  selectedFrequency,
  startDate,
  endDate,
  isInterestDisabled = false,
  onSectionLayout,
  onAutoCalculate,
}: Props) => {
  // Helper function to get days per frequency
  const getFrequencyDays = (frequency: FrequencyType): number => {
    const frequencyEnum = getFrequencyEnum(frequency);
    switch (frequencyEnum) {
      case 1:
        return 1; // Daily
      case 2:
        return 7; // Weekly
      case 3:
        return 30; // Monthly
      case 4:
        return 1; // On inflow (treat as daily for calculation)
      default:
        return 1;
    }
  };

  // Calculate total savings period in days
  const getSavingsPeriodDays = (): number => {
    if (!startDate || !endDate) return 0;
    const timeDiff = endDate.getTime() - startDate.getTime();
    return Math.ceil(timeDiff / (1000 * 3600 * 24));
  };

  // Calculate total amount that will be saved over the period
  const calculateTotalSavingsAmount = (): number => {
    if (!periodicSavingsAmount || !selectedFrequency || !startDate || !endDate)
      return 0;

    const periodDays = getSavingsPeriodDays();
    const frequencyDays = getFrequencyDays(selectedFrequency);
    const numberOfPeriods = Math.floor(periodDays / frequencyDays);

    return periodicSavingsAmount * numberOfPeriods;
  };

  // Calculate projected earnings with compound interest (daily accrual, monthly compounding)
  const calculateProjectedEarnings = () => {
    if (
      !periodicSavingsAmount ||
      !currentRate ||
      isInterestDisabled ||
      !startDate ||
      !endDate
    )
      return 0;

    return calculateProjectedInterestEarnings({
      periodicAmount: periodicSavingsAmount,
      selectedFrequency,
      startDate,
      endDate,
      annualInterestRate: currentRate,
      isInterestDisabled,
    });
  };

  // Auto-calculate required periodic amount to reach target with interest
  const calculateRequiredPeriodicAmount = (): number => {
    if (!savingsTarget || !selectedFrequency || !startDate || !endDate)
      return 0;

    return calculateRequiredPeriodicAmountWithInterest({
      savingsTarget,
      selectedFrequency,
      startDate,
      endDate,
      annualInterestRate: currentRate,
      isInterestDisabled,
    });
  };

  // Calculate final balance including compound interest
  const calculateFinalBalanceWithCompoundInterest = () => {
    if (!periodicSavingsAmount || !selectedFrequency || !startDate || !endDate)
      return 0;

    return calculateFinalBalance({
      periodicAmount: periodicSavingsAmount,
      selectedFrequency,
      startDate,
      endDate,
      annualInterestRate: currentRate,
      isInterestDisabled,
    });
  };

  // Check if we have enough data to show calculations
  const hasCalculationData =
    periodicSavingsAmount > 0 && selectedFrequency && startDate && endDate;
  const hasAutoCalculationData =
    savingsTarget > 0 &&
    selectedFrequency &&
    startDate &&
    endDate &&
    periodicSavingsAmount === 0;

  const totalSavingsAmount = calculateTotalSavingsAmount();
  const projectedEarnings = calculateProjectedEarnings();
  const finalBalanceWithInterest = calculateFinalBalanceWithCompoundInterest();
  const requiredPeriodicAmount = calculateRequiredPeriodicAmount();
  const periodDays = getSavingsPeriodDays();

  // Don't render if no relevant data
  if (!hasCalculationData && !hasAutoCalculationData) {
    return null;
  }

  return (
    <View style={styles.container} onLayout={onSectionLayout}>
      {/* Auto-calculation Section - Show first if applicable */}
      {hasAutoCalculationData && (
        <View style={styles.autoCalculateSection}>
          <Text
            fontSize={fontSz(12)}
            fontFamily="Gordita-Regular"
            fontWeight="400"
            text={`To reach your target of ${formatAsCurrency(
              savingsTarget,
            )}, you need to save:`}
            color={Colors.inputBackgroundLight}
            textAlign="center"
            style={{marginBottom: ms(12)}}
          />
          <View style={styles.autoCalculateResult}>
            <Text
              fontSize={fontSz(18)}
              fontFamily="Gordita-Bold"
              fontWeight="700"
              text={formatAsCurrency(requiredPeriodicAmount)}
              color={Colors.headerText}
              textAlign="center"
            />
            <Text
              fontSize={fontSz(12)}
              fontFamily="Gordita-Regular"
              fontWeight="400"
              text={selectedFrequency.toLowerCase()}
              color={Colors.inputBackgroundLight}
              textAlign="center"
              style={{marginTop: ms(4)}}
            />
          </View>
          {onAutoCalculate && (
            <TouchableOpacity
              style={styles.autoCalculateButton}
              onPress={() => onAutoCalculate(requiredPeriodicAmount)}>
              <Text
                fontSize={fontSz(14)}
                fontFamily="Gordita-Medium"
                fontWeight="500"
                text="Use This Amount"
                color={Colors.primary}
                textAlign="center"
              />
            </TouchableOpacity>
          )}
        </View>
      )}

      {/* Earnings Summary - Show when we have calculation data */}
      {/* {hasCalculationData && periodDays > 0 && (
        <View style={styles.earningsCard}>
          <View style={styles.earningsHeader}>
            <Text
              fontSize={fontSz(14)}
              fontFamily="Gordita-Medium"
              fontWeight="500"
              text="Your Earnings Summary"
              color={Colors.headerText}
              textAlign="left"
            />
          </View>
          
          <View style={styles.earningsContent}>
            <View style={styles.earningsRow}>
              <Text
                fontSize={fontSz(12)}
                fontFamily="Gordita-Regular"
                fontWeight="400"
                text="Interest Rate"
                color={Colors.inputBackgroundLight}
                textAlign="left"
              />
              <View style={styles.rateDisplay}>
                <Text
                  fontSize={fontSz(16)}
                  fontFamily="Gordita-Medium"
                  fontWeight="600"
                  text={`${isInterestDisabled ? 0 : currentRate}%`}
                  color={Colors.headerText}
                  textAlign="right"
                />
                <Text
                  fontSize={fontSz(10)}
                  fontFamily="Gordita-Regular"
                  fontWeight="400"
                  text=" per annum"
                  color={Colors.inputBackgroundLight}
                  textAlign="right"
                  style={{marginLeft: ms(2)}}
                />
              </View>
            </View>

            <View style={styles.earningsRow}>
              <Text
                fontSize={fontSz(12)}
                fontFamily="Gordita-Regular"
                fontWeight="400"
                text="Savings Duration"
                color={Colors.inputBackgroundLight}
                textAlign="left"
              />
              <Text
                fontSize={fontSz(14)}
                fontFamily="Gordita-Medium"
                fontWeight="500"
                text={`${periodDays} days`}
                color={Colors.headerText}
                textAlign="right"
              />
            </View>

            <View style={styles.divider} />
          
            <View style={styles.earningsRow}>
              <Text
                fontSize={fontSz(12)}
                fontFamily="Gordita-Regular"
                fontWeight="400"
                text="Earnings"
                color={Colors.inputBackgroundLight}
                textAlign="left"
              />
              <Text
                fontSize={fontSz(16)}
                fontFamily="Gordita-Medium"
                fontWeight="600"
                text={formatAsCurrency(projectedEarnings)}
                color="#4CAF50"
                textAlign="right"
              />
            </View>
            
            <View style={styles.earningsRow}>
              <Text
                fontSize={fontSz(12)}
                fontFamily="Gordita-Regular"
                fontWeight="400"
                text="Total at Maturity"
                color={Colors.inputBackgroundLight}
                textAlign="left"
              />
              <Text
                fontSize={fontSz(16)}
                fontFamily="Gordita-Bold"
                fontWeight="700"
                text={formatAsCurrency(finalBalanceWithInterest)}
                color={Colors.headerText}
                textAlign="right"
              />
            </View>
          </View>
        </View>
      )} */}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    marginTop: ms(0),
    marginBottom: ms(8),
  },
  earningsCard: {
    backgroundColor: Colors.white,
    borderRadius: ms(8),
    borderWidth: 1,
    borderColor: Colors.gray200,
    shadowColor: Colors.shadowColor,
    shadowOffset: {width: 0, height: 2},
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 2,
    marginTop: ms(4),
  },
  earningsHeader: {
    paddingHorizontal: ms(16),
    paddingTop: ms(16),
    paddingBottom: ms(8),
  },
  earningsContent: {
    paddingHorizontal: ms(16),
    paddingBottom: ms(16),
  },
  earningsRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: ms(8),
  },
  rateDisplay: {
    flexDirection: 'row',
    alignItems: 'baseline',
  },
  divider: {
    height: 1,
    backgroundColor: Colors.gray200,
    marginVertical: ms(4),
  },
  autoCalculateSection: {
    alignItems: 'center',
    paddingVertical: ms(16),
    paddingHorizontal: ms(16),
    backgroundColor: Colors.white,
    borderRadius: ms(8),
    borderWidth: 1,
    borderColor: Colors.gray200,
    shadowColor: Colors.shadowColor,
    shadowOffset: {width: 0, height: 2},
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 2,
  },
  autoCalculateResult: {
    alignItems: 'center',
    marginBottom: ms(16),
  },
  autoCalculateButton: {
    backgroundColor: Colors.lightPrimary,
    paddingVertical: ms(10),
    paddingHorizontal: ms(20),
    borderRadius: ms(6),
    borderWidth: 1,
    borderColor: Colors.primary,
  },
});

export default FlexibleInterestDisplay;
