import React from 'react';
import {StyleSheet, View, ActivityIndicator} from 'react-native';
import {CustomPressable} from '../Button';
import {Colors, fontSz, globalStyles, ms, naira, formatAsCurrency} from '../../utils';
import {Text} from '../Text';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {Info} from '../Common/info';
import {Modal} from '../Common/modal';
import {useSDKConfig} from '../../contexts/SDKConfigContext';
import {getInterestBreakdownBySavingsId} from '../../services/actions';
import {InterestBreakdownType} from '../../utils/types';
import {useQuery} from '@tanstack/react-query';

type BreakdownProps = {
  date: string;
  interest: string;
  balance: string;
  header?: boolean;
};

type InterestBreakdownProps = {
  visible: boolean;
  onClose: () => void;
  savingsId: string;
};

const Breakdown = (props: BreakdownProps) => {
  const {date, interest, balance, header} = props;
  return (
    <CustomPressable
      style={[
        globalStyles.rowBetween,
        {
          flex: 1,
          backgroundColor: Colors.tabBg,
          paddingHorizontal: ms(10),
          paddingVertical: ms(15),
          borderRadius: ms(8),
        },
      ]}>
      <Text
        fontSize={fontSz(14)}
        fontFamily={header ? 'Gordita-Medium' : 'Gordita-Regular'}
        fontWeight={header ? '500' : '400'}
        text={`${date}`}
        color={Colors.dark30}
        textAlign={'left'}
        style={{flex: 1, alignSelf: 'center'}}
      />
      <Text
        fontSize={fontSz(14)}
        fontFamily={header ? 'Gordita-Medium' : 'Gordita-Regular'}
        fontWeight={header ? '500' : '400'}
        text={`${interest}`}
        color={Colors.dark30}
        textAlign={'left'}
        style={{flex: 1, alignSelf: 'center'}}
      />
      <Text
        fontSize={fontSz(14)}
        fontFamily={header ? 'Gordita-Medium' : 'Gordita-Regular'}
        fontWeight={header ? '500' : '400'}
        text={`${balance}`}
        color={Colors.dark30}
        textAlign={'left'}
        style={{flex: 1, alignSelf: 'center'}}
      />
    </CustomPressable>
  );
};

const InterestBreakdown = (props: InterestBreakdownProps) => {
  const {visible, onClose, savingsId} = props;
  const {bottom} = useSafeAreaInsets();
  const {apiKey} = useSDKConfig();

  const {
    data: interestData,
    isLoading,
    error,
    refetch,
  } = useQuery<InterestBreakdownType[], Error>({
    queryKey: ['interestBreakdown', savingsId, apiKey],
    queryFn: async (): Promise<InterestBreakdownType[]> => {
      const result = await getInterestBreakdownBySavingsId(savingsId, apiKey);

      if (result.error) {
        throw new Error(result.message || 'Failed to load interest breakdown');
      }

      return result.data || [];
    },
    enabled: visible && !!savingsId && !!apiKey,
    staleTime: 5 * 60 * 1000, // 5 minutes
    gcTime: 10 * 60 * 1000, // 10 minutes (formerly cacheTime)
    retry: 2,
  });

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-GB', {
      day: '2-digit',
      month: '2-digit',
      year: '2-digit',
    });
  };

  const renderContent = () => (
    <View style={[styles.container, {paddingBottom: ms(bottom)}]}>
      <Info
        text={'Interest will be paid to your savings account at the end of the month'}
        containerStyle={{marginBottom: ms(20)}}
      />

      {isLoading ? (
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color={Colors.primary} />
          <Text
            fontSize={fontSz(14)}
            fontFamily="Gordita-Regular"
            text="Loading interest breakdown..."
            color={Colors.dark30}
            textAlign="center"
            style={{marginTop: ms(10)}}
          />
        </View>
      ) : error ? (
        <View style={styles.errorContainer}>
          <Text
            fontSize={fontSz(14)}
            fontFamily="Gordita-Regular"
            text={error instanceof Error ? error.message : 'An error occurred while loading interest breakdown'}
            color={Colors.error}
            textAlign="center"
          />
          <CustomPressable
            onPress={() => refetch()}
            style={styles.retryButton}>
            <Text
              fontSize={fontSz(14)}
              fontFamily="Gordita-Medium"
              text="Retry"
              color={Colors.primary}
              textAlign="center"
            />
          </CustomPressable>
        </View>
      ) : (
        <View style={{rowGap: ms(20)}}>
          <Breakdown
            date={'Date'}
            interest={'Interest'}
            balance={'Balance'}
            header
          />
          {interestData && interestData.length > 0 ? (
            interestData.map((item, index) => (
              <Breakdown
                key={index}
                date={formatDate(item.date)}
                interest={formatAsCurrency(item.interest)}
                balance={formatAsCurrency(item.balance)}
              />
            ))
          ) : (
            <View style={styles.emptyContainer}>
              <Text
                fontSize={fontSz(14)}
                fontFamily="Gordita-Regular"
                text="No pending interest found for this savings account"
                color={Colors.dark30}
                textAlign="center"
              />
            </View>
          )}
        </View>
      )}
    </View>
  );

  return (
    <Modal
      visible={visible}
      title="Interest Breakdown"
      onClose={onClose}>
      {renderContent()}
    </Modal>
  );
};

export default InterestBreakdown;

const styles = StyleSheet.create({
  container: {
    paddingHorizontal: ms(16),
    paddingTop: ms(0),
  },
  loadingContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: ms(40),
  },
  errorContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: ms(40),
  },
  retryButton: {
    marginTop: ms(15),
    paddingVertical: ms(10),
    paddingHorizontal: ms(20),
    borderRadius: ms(8),
    borderWidth: 1,
    borderColor: Colors.primary,
  },
  emptyContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: ms(30),
  },
});
