import React, {useState} from 'react';
import {
  View,
  StyleSheet,
  Modal,
  ScrollView,
  TouchableOpacity,
  TouchableWithoutFeedback,
} from 'react-native';
import {Text} from '../Text';
import {Colors, fontSz, globalStyles, ms, formatAsCurrency} from '../../utils';
import {LockedSavingsInterestRateTierType} from '../../utils/types';
import {CustomPressable} from '../Button';
import CurrencyInput from '../Input/currency';
import Dropdown from '../Dropdown';

type Props = {
  tiers: LockedSavingsInterestRateTierType[];
  selectedDays: number;
  currentRate: number;
  onTierSelect: (
    tier: LockedSavingsInterestRateTierType,
    isManualSelection?: boolean,
  ) => void;
  onDaysChange?: (days: number) => void;
  primaryColor: string;
  isLoading?: boolean;
  minimumLockDurationDays: number;
  durationError?: string;
  tierSelectionError?: string;
  onSectionLayout?: (event: any) => void;
  lockAmount: number;
  isInterestDisabled?: boolean;
  selectedTier?: LockedSavingsInterestRateTierType | null;
};

const InterestRateTiers = ({
  tiers,
  selectedDays,
  currentRate,
  onTierSelect,
  onDaysChange = () => {},
  primaryColor,
  isLoading = false,
  minimumLockDurationDays,
  durationError = '',
  tierSelectionError = '',
  onSectionLayout,
  lockAmount,
  isInterestDisabled = false,
  selectedTier: parentSelectedTier = null,
}: Props) => {
  const [showTierModal, setShowTierModal] = useState(false);
  const [localSelectedTier, setLocalSelectedTier] =
    useState<LockedSavingsInterestRateTierType | null>(null);

  // Use parent's selectedTier if available, otherwise use local state
  const selectedTier = parentSelectedTier || localSelectedTier;

  // Find which tier contains the selected days
  const getCurrentTier = () => {
    return tiers.find(
      tier => selectedDays >= tier.minDays && selectedDays <= tier.maxDays,
    );
  };

  const formatDurationText = (minDays: number, maxDays: number) => {
    if (minDays === maxDays) {
      return `${minDays} days`;
    }
    return `${minDays}-${maxDays} days`;
  };

  const formatTierDisplayText = (tier: LockedSavingsInterestRateTierType) => {
    const rate = isInterestDisabled ? 0 : tier.interestRate;
    const duration = formatDurationText(tier.minDays, tier.maxDays);
    return `${duration} • ${rate}% per annum`;
  };

  // Calculate projected earnings based on amount, rate, and duration
  const calculateProjectedEarnings = () => {
    if (!lockAmount || !currentRate || !selectedDays || isInterestDisabled)
      return 0;

    const principal = lockAmount;
    const annualRate = currentRate / 100;
    const timeInYears = selectedDays / 365;

    return principal * annualRate * timeInYears;
  };

  const handleTierSelection = (
    tier: LockedSavingsInterestRateTierType,
    isManualSelection: boolean = true,
  ) => {
    setLocalSelectedTier(tier);
    if (isManualSelection) {
      setShowTierModal(false);
    }

    // Notify parent component about tier selection
    onTierSelect(tier, isManualSelection);

    // Reset days input only when manually selecting from dropdown
    if (isManualSelection && onDaysChange) {
      onDaysChange(0);
    }
  };

  const handleDaysChange = (days: number) => {
    if (onDaysChange) {
      onDaysChange(days);
    }

    // Auto-select the appropriate tier based on entered days
    if (days > 0) {
      const matchingTier = tiers.find(
        tier => days >= tier.minDays && days <= tier.maxDays,
      );

      if (matchingTier && matchingTier.id !== selectedTier?.id) {
        handleTierSelection(matchingTier, false); // false = auto-selection
      }
    }
  };

  if (isLoading) {
    return (
      <View style={styles.container}>
        <View style={styles.loadingContainer}>
          <Text
            fontSize={fontSz(14)}
            fontFamily="Gordita-Regular"
            fontWeight="400"
            text="Loading interest rates..."
            color={Colors.inputBackgroundLight}
            textAlign="center"
          />
        </View>
      </View>
    );
  }

  if (!tiers || tiers.length === 0) {
    return null;
  }

  const currentTier = getCurrentTier();
  const displayTier = selectedTier || currentTier;

  // Calculate maximum days from all tiers
  const maxDaysAvailable = Math.max(...tiers.map(tier => tier.maxDays));

  return (
    <View style={styles.container}>
      {/* Tier Selection Dropdown */}
      <Dropdown
        label="How long do you want to lock for?"
        placeHolder="Choose lock duration"
        value={displayTier ? formatTierDisplayText(displayTier) : ''}
        onPress={() => setShowTierModal(true)}
        showAsterisk={true}
        errorMsg={tierSelectionError}
        containerStyle={{marginBottom: ms(24)}}
      />

      {/* Days Input - Only show if a tier is selected */}
      {displayTier && (
        <View style={styles.durationInputContainer} onLayout={onSectionLayout}>
          <CurrencyInput
            value={selectedDays > 0 ? selectedDays.toString() : ''}
            onChangeValue={(value: any) => {
              const numericValue = Number(value);
              // Limit input to maximum available range
              if (numericValue <= maxDaysAvailable) {
                handleDaysChange(numericValue);
              }
            }}
            ignoreNegative={false}
            delimiter=""
            separator=""
            precision={0}
            containerStyle={{marginBottom: ms(0)}}
            returnKeyType="done"
            topComponent={<></>}
            walletAmount={0}
            paymentAmount={selectedDays}
            onPressUseAllBalance={() => {}}
            onEndEditing={() => {}}
            onFocus={() => {}}
            label={`Lock Duration (${formatDurationText(
              displayTier.minDays,
              displayTier.maxDays,
            )})`}
            showAsterisk={true}
            placeholder={`Enter days between ${displayTier.minDays} and ${displayTier.maxDays}`}
            balance={0}
            wrapperStyle={{
              borderColor: durationError ? Colors.error : '#F4F4F4',
            }}
            errorMsg={durationError}
            showUseAllBalance={false}
            showCurrency={false}
            hideBalance={true}
          />
        </View>
      )}

      {/* Enhanced Interest Rate & Earnings Display */}
      {/* {selectedDays > 0 && displayTier && (
        <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="Lock Duration"
                color={Colors.inputBackgroundLight}
                textAlign="left"
              />
              <Text
                fontSize={fontSz(14)}
                fontFamily="Gordita-Medium"
                fontWeight="500"
                text={`${selectedDays} days`}
                color={Colors.headerText}
                textAlign="right"
              />
            </View>

            {lockAmount > 0 && (
              <>
                <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(calculateProjectedEarnings())}
                    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(
                      lockAmount + calculateProjectedEarnings(),
                    )}
                    color={Colors.headerText}
                    textAlign="right"
                  />
                </View>
              </>
            )}
          </View>
        </View>
      )} */}

      {/* Tier Selection Modal */}
      <Modal
        visible={showTierModal}
        transparent
        animationType="none"
        onRequestClose={() => setShowTierModal(false)}>
        <TouchableWithoutFeedback onPress={() => setShowTierModal(false)}>
          <View style={styles.modalOverlay}>
            <TouchableWithoutFeedback onPress={() => {}}>
              <View style={styles.modalContent}>
                <View style={styles.modalHeader}>
                  <Text
                    fontSize={fontSz(18)}
                    fontFamily="Gordita-Medium"
                    fontWeight="500"
                    text="Choose Your Savings Duration"
                    color={Colors.headerText}
                  />
                </View>

                <ScrollView
                  style={styles.tiersList}
                  showsVerticalScrollIndicator={false}>
                  {tiers.map((tier) => (
                    <TouchableOpacity
                      key={tier.id}
                      style={[
                        styles.tierOption,
                        displayTier?.id === tier.id &&
                          styles.selectedTierOption,
                      ]}
                      onPress={() => handleTierSelection(tier, true)}>
                      <View style={styles.tierInfo}>
                        <Text
                          fontSize={fontSz(16)}
                          fontFamily="Gordita-Medium"
                          fontWeight="600"
                          text={`${
                            isInterestDisabled ? 0 : tier.interestRate
                          }% per annum`}
                          color={
                            displayTier?.id === tier.id
                              ? Colors.primary
                              : Colors.headerText
                          }
                        />
                        <Text
                          fontSize={fontSz(14)}
                          fontFamily="Gordita-Regular"
                          fontWeight="400"
                          text={formatDurationText(tier.minDays, tier.maxDays)}
                          color={Colors.inputBackgroundLight}
                          style={{marginTop: ms(4)}}
                        />
                      </View>
                      {displayTier?.id === tier.id && (
                        <View style={styles.checkIcon}>
                          <Text
                            fontSize={fontSz(16)}
                            fontFamily="Gordita-Medium"
                            fontWeight="600"
                            text="✓"
                            color={Colors.primary}
                          />
                        </View>
                      )}
                    </TouchableOpacity>
                  ))}
                </ScrollView>
              </View>
            </TouchableWithoutFeedback>
          </View>
        </TouchableWithoutFeedback>
      </Modal>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    marginTop: ms(16),
  },
  loadingContainer: {
    paddingVertical: ms(20),
    alignItems: 'center',
  },
  durationInputContainer: {
    marginBottom: ms(16),
  },
  earningsCard: {
    marginBottom: ms(24),
    backgroundColor: '#F8F9FA',
    borderRadius: ms(12),
    paddingHorizontal: ms(16),
    paddingVertical: ms(16),
    borderWidth: ms(1),
    borderColor: '#E9ECEF',
  },
  earningsHeader: {
    marginBottom: ms(12),
  },
  earningsContent: {
    gap: ms(8),
  },
  earningsRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: ms(4),
  },
  rateDisplay: {
    flexDirection: 'row',
    alignItems: 'baseline',
  },
  divider: {
    height: ms(1),
    backgroundColor: '#E9ECEF',
    marginVertical: ms(8),
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    justifyContent: 'flex-end',
  },
  modalContent: {
    backgroundColor: Colors.white,
    borderTopLeftRadius: ms(20),
    borderTopRightRadius: ms(20),
    width: '100%',
    maxHeight: '70%',
    paddingBottom: ms(20),
    shadowColor: Colors.shadowColor,
    shadowOffset: {width: 0, height: -4},
    shadowOpacity: 0.25,
    shadowRadius: 8,
    elevation: 8,
  },
  modalHeader: {
    paddingHorizontal: ms(20),
    paddingTop: ms(20),
    paddingBottom: ms(16),
    borderBottomWidth: 1,
    borderBottomColor: '#E9ECEF',
  },
  tiersList: {
    paddingHorizontal: ms(20),
    paddingTop: ms(20),
    maxHeight: ms(400),
  },
  tierOption: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: ms(16),
    paddingHorizontal: ms(16),
    borderRadius: ms(8),
    marginBottom: ms(8),
    backgroundColor: '#F8F9FA',
    borderWidth: ms(1),
    borderColor: '#E9ECEF',
  },
  selectedTierOption: {
    backgroundColor: '#F0F8FF',
    borderColor: Colors.primary,
  },
  tierInfo: {
    flex: 1,
  },
  checkIcon: {
    marginLeft: ms(12),
  },
});

export default InterestRateTiers;
