import { useState, useEffect } from 'react';
import { View, Text, TouchableOpacity, ActivityIndicator, ScrollView<% if (styling !== 'nativewind') { %>, StyleSheet<% } %> } from 'react-native';
import { useWallet } from '@lazorkit/wallet-mobile-adapter';
import { Connection, PublicKey } from '@solana/web3.js';
import * as Linking from 'expo-linking';
<% if (styling !== 'nativewind') { %>
const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: '#fff', padding: 24, paddingTop: 60 },
  card: { backgroundColor: '#0a0a0a', borderRadius: 16, padding: 20 },
  header: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 },
  title: { fontSize: 18, fontWeight: '600', color: '#fafafa' },
  back: { fontSize: 13, color: '#737373' },
  list: { gap: 8 },
  item: { borderWidth: 1, borderColor: '#262626', borderRadius: 12, padding: 12, backgroundColor: '#171717' },
  row: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' },
  sig: { fontFamily: 'monospace', fontSize: 13, color: '#fafafa' },
  time: { fontSize: 12, color: '#737373', marginTop: 4 },
  status: { fontSize: 11, paddingHorizontal: 6, paddingVertical: 2, borderRadius: 4, overflow: 'hidden' },
  success: { backgroundColor: '#14532d', color: '#4ade80' },
  failed: { backgroundColor: '#7f1d1d', color: '#f87171' },
  empty: { textAlign: 'center', paddingVertical: 32, color: '#737373', fontSize: 14 },
});
<% } %>
interface Props {
  onBack: () => void;
}

interface TxInfo {
  signature: string;
  slot: number;
  blockTime: number | null | undefined;
  err: any;
}

export function History({ onBack }: Props) {
  const { wallet } = useWallet();
  const [txs, setTxs] = useState<TxInfo[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!wallet?.smartWallet) return;
    const rpc = process.env.EXPO_PUBLIC_SOLANA_RPC || 'https://api.devnet.solana.com';
    const conn = new Connection(rpc);
    conn.getSignaturesForAddress(new PublicKey(wallet.smartWallet), { limit: 10 })
      .then((sigs) => setTxs(sigs.map((s) => ({ signature: s.signature, slot: s.slot, blockTime: s.blockTime, err: s.err }))))
      .catch(console.error)
      .finally(() => setLoading(false));
  }, [wallet?.smartWallet]);

  const formatTime = (ts: number | null) => {
    if (!ts) return '—';
    return new Date(ts * 1000).toLocaleDateString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
  };

  const openTx = (sig: string) => {
    const cluster = (process.env.EXPO_PUBLIC_SOLANA_RPC || '').includes('mainnet') ? '' : '?cluster=devnet';
    Linking.openURL(`https://solscan.io/tx/${sig}${cluster}`);
  };

  return (
<% if (styling === 'nativewind') { %>
    <View className="flex-1 bg-white p-6 pt-16">
      <View className="bg-neutral-900 rounded-2xl p-5">
        <View className="flex-row items-center justify-between mb-4">
          <Text className="text-lg font-semibold text-white">History</Text>
          <TouchableOpacity onPress={onBack}><Text className="text-sm text-neutral-500">← Back</Text></TouchableOpacity>
        </View>
        {loading ? (
          <View className="py-8 items-center"><ActivityIndicator color="#737373" /></View>
        ) : txs.length === 0 ? (
          <Text className="text-center py-8 text-neutral-500">No transactions yet</Text>
        ) : (
          <ScrollView className="gap-2" showsVerticalScrollIndicator={false}>
            {txs.map((tx) => (
              <TouchableOpacity key={tx.signature} onPress={() => openTx(tx.signature)} className="border border-neutral-700 rounded-xl p-3 mb-2 bg-neutral-800">
                <View className="flex-row justify-between items-center">
                  <Text className="font-mono text-sm text-white">{tx.signature.slice(0, 8)}...{tx.signature.slice(-8)}</Text>
                  <Text className={`text-xs px-2 py-0.5 rounded ${tx.err ? 'bg-red-900 text-red-400' : 'bg-green-900 text-green-400'}`}>
                    {tx.err ? 'Failed' : 'Success'}
                  </Text>
                </View>
                <Text className="text-xs text-neutral-500 mt-1">{formatTime(tx.blockTime)}</Text>
              </TouchableOpacity>
            ))}
          </ScrollView>
        )}
      </View>
    </View>
<% } else { %>
    <View style={styles.container}>
      <View style={styles.card}>
        <View style={styles.header}>
          <Text style={styles.title}>History</Text>
          <TouchableOpacity onPress={onBack}><Text style={styles.back}>← Back</Text></TouchableOpacity>
        </View>
        {loading ? (
          <View style={{ paddingVertical: 32, alignItems: 'center' }}><ActivityIndicator color="#737373" /></View>
        ) : txs.length === 0 ? (
          <Text style={styles.empty}>No transactions yet</Text>
        ) : (
          <ScrollView style={styles.list} showsVerticalScrollIndicator={false}>
            {txs.map((tx) => (
              <TouchableOpacity key={tx.signature} onPress={() => openTx(tx.signature)} style={[styles.item, { marginBottom: 8 }]}>
                <View style={styles.row}>
                  <Text style={styles.sig}>{tx.signature.slice(0, 8)}...{tx.signature.slice(-8)}</Text>
                  <Text style={[styles.status, tx.err ? styles.failed : styles.success]}>
                    {tx.err ? 'Failed' : 'Success'}
                  </Text>
                </View>
                <Text style={styles.time}>{formatTime(tx.blockTime)}</Text>
              </TouchableOpacity>
            ))}
          </ScrollView>
        )}
      </View>
    </View>
<% } %>
  );
}
