import React, { useEffect, useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  ActivityIndicator,
  SafeAreaView,
  TouchableOpacity,
  ListRenderItem,
  Platform,
  StatusBar,
} from 'react-native';
import { useNavigation } from 'expo-router';

interface Transaction {
  txHash: string;
  buyer: string;
  amount: string;
  receiver: string;
  mark_price: number;
}

const TransactionsList: React.FC = () => {
  const [transactions, setTransactions] = useState<Transaction[]>([]);
  const [loading, setLoading] = useState(true);
  const navigation = useNavigation();

  useEffect(() => {
    const fetchTransactions = async () => {
      try {
        const response = await fetch(
          'http://vps.playpoolstudios.com:28329/getTransactions/0x4586F1Dd2DeD0045923c9519BBf3b87B599480C2'
        );
        const data = await response.json();
        setTransactions(data.transactions || []);
      } catch (error) {
        console.error('Error fetching transactions:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchTransactions();
  }, []);

  const renderTransaction: ListRenderItem<Transaction> = ({ item }) => {
    // Calculate the amount in million WEI and convert it to Thai Baht
    const amountInMillion = parseFloat(item.amount) / 1_000_000_000_000_000_000;
    // Display mark_price as conversion rate in USD
    const conversionRate = (item.mark_price/ 1_000_000_00).toFixed(2) ;

    return (
      <View style={styles.card}>
        <Text style={styles.label}>Transaction Hash:</Text>
        <Text style={styles.value}>{item.txHash}</Text>
        <Text style={styles.label}>Amount:</Text>
        <Text style={styles.value}>
          { (parseFloat(conversionRate)*amountInMillion).toFixed(2)} THB  ~{amountInMillion.toLocaleString()} USD
        </Text>
        <Text style={styles.label}>Receiver:</Text>
        <Text style={styles.value}>{item.receiver}</Text>
        <Text style={styles.label}>Conversion Rate:</Text>
        <Text style={styles.value}>${conversionRate}</Text>
      </View>
    );
  };

  const handleBackPress = () => {
    navigation.goBack();
  };

  return (
    <SafeAreaView style={styles.container}>
      <StatusBar
        barStyle={Platform.OS === 'android' ? 'light-content' : 'dark-content'}
        backgroundColor="#1e1e1e"
      />
      <View style={styles.header}>
        <TouchableOpacity style={styles.backButton} onPress={handleBackPress}>
          <Text style={styles.backButtonText}>←</Text>
        </TouchableOpacity>
        <Text style={styles.title}>Transaction History</Text>
      </View>

      {loading ? (
        <ActivityIndicator size="large" color="#bb86fc" style={styles.loader} />
      ) : transactions.length > 0 ? (
        <FlatList
          data={transactions}
          renderItem={renderTransaction}
          keyExtractor={(item) => item.txHash}
          contentContainerStyle={styles.listContent}
        />
      ) : (
        <Text style={styles.noDataText}>No transactions found.</Text>
      )}
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: 15,
    flex: 1,
    backgroundColor: '#121212', // Dark background
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 16,
    paddingHorizontal: 16,
    backgroundColor: '#1e1e1e',
    elevation: 4,
    zIndex: 1,
  },
  backButton: {
    marginRight: 16,
  },
  backButtonText: {
    fontSize: 24,
    color: '#bb86fc', // Highlight color for back button
  },
  title: {
    fontSize: 20,
    color: '#ffffff', // White text for title
    fontWeight: 'bold',
  },
  listContent: {
    padding: 16,
  },
  card: {
    backgroundColor: '#1e1e1e', // Darker card background
    borderRadius: 8,
    padding: 16,
    marginBottom: 16,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,
    shadowRadius: 4,
    elevation: 4,
  },
  label: {
    fontSize: 14,
    color: '#bb86fc', // Highlight color for labels
    fontWeight: 'bold',
    marginBottom: 4,
  },
  value: {
    fontSize: 16,
    color: '#e0e0e0', // Light text for values
    marginBottom: 12,
  },
  loader: {
    marginTop: 50,
  },
  noDataText: {
    fontSize: 18,
    color: '#888888', // Slightly muted text color for "No data" message
    textAlign: 'center',
    marginTop: 20,
  },
});

export default TransactionsList;
