import React, { useState } from 'react';
import { View, TouchableOpacity, Text, StyleSheet, Alert, ActivityIndicator, ViewStyle, Dimensions } from 'react-native';
import { fetchPaymentIntent } from './api';
import { useStripe } from '@stripe/stripe-react-native';

interface PayButtonProps {
  offerId: string;
  apiKey: string;
  buttonColor?: string;
  textColor?: string;
  borderRadius?: number;
  buttonWidth?: string | number;
  buttonHeight?: string | number;
  fontWeight?: 'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900';
  onPaymentSucceeded?: (transactionId: string) => void;
  onPaymentFailed?: () => void;
  buttonTitle?: string;
}

const PayButton: React.FC<PayButtonProps> = ({
  offerId,
  apiKey,
  buttonColor = '#61D37A',
  textColor = 'black',
  borderRadius = 12,
  buttonWidth = '80%',
  buttonHeight = 50,
  fontWeight = '400',
  onPaymentSucceeded,
  onPaymentFailed,
  buttonTitle = 'Pay Now', 
}) => {
  const { initPaymentSheet, presentPaymentSheet } = useStripe();
  const [loading, setLoading] = useState(false);

  const handlePayment = async () => {
    setLoading(true);
    try {
      const response = await fetchPaymentIntent(offerId, apiKey);
      const secretKey = response.secretKey;

      const { error: initError } = await initPaymentSheet({
        paymentIntentClientSecret: secretKey,
        merchantDisplayName: 'Your Merchant Name',
      });

      if (initError) {
        Alert.alert(`Error code: ${initError.code}`, initError.message);
        setLoading(false);
        onPaymentFailed?.();
        return;
      }

      const { error: presentError } = await presentPaymentSheet();

      if (presentError) {
        onPaymentFailed?.();
      } else {
        if (onPaymentSucceeded && response.transactionId) {
          onPaymentSucceeded(response.transactionId);
        }
      }
    } catch (error) {
      onPaymentFailed?.();
    } finally {
      setLoading(false);
    }
  };

  const buttonStyles: ViewStyle = {
    backgroundColor: buttonColor,
    borderRadius: borderRadius,
    width: typeof buttonWidth === 'string' ? Dimensions.get('window').width * (parseFloat(buttonWidth) / 100) : buttonWidth,
    height: typeof buttonHeight === 'string' ? Dimensions.get('window').height * (parseFloat(buttonHeight) / 100) : buttonHeight,
  };

  return (
    <View style={styles.container}>
      {loading ? (
        <ActivityIndicator size="large" color="#0000ff" />
      ) : (
        <TouchableOpacity style={[styles.button, buttonStyles]} onPress={handlePayment}>
          <Text style={[styles.buttonText, { color: textColor, fontWeight: fontWeight }]}>
            {buttonTitle}
          </Text>
        </TouchableOpacity>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
  },
  button: {
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 15,
    paddingHorizontal: 30,
  },
  buttonText: {
    fontSize: 18,
  },
});

export default PayButton;