import { scrollViewWebProps } from '@/lib/ui/scroll-props';
import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  TextInput,
  Alert,
  ActivityIndicator,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Stack, useRouter } from 'expo-router';
import { ArrowLeft, ArrowRightLeft, Wallet, History, ChevronDown } from 'lucide-react-native';
import { trpc } from '@/lib/trpc';

const CURRENCIES = [
  { code: 'USD', name: 'US Dollar', symbol: '$' },
  { code: 'EUR', name: 'Euro', symbol: '€' },
  { code: 'GBP', name: 'British Pound', symbol: '£' },
  { code: 'JPY', name: 'Japanese Yen', symbol: '¥' },
  { code: 'CAD', name: 'Canadian Dollar', symbol: 'C$' },
  { code: 'AUD', name: 'Australian Dollar', symbol: 'A$' },
  { code: 'CHF', name: 'Swiss Franc', symbol: 'Fr' },
  { code: 'CNY', name: 'Chinese Yuan', symbol: '¥' },
  { code: 'INR', name: 'Indian Rupee', symbol: '₹' },
  { code: 'MXN', name: 'Mexican Peso', symbol: '$' },
];

export default function CurrencyScreen() {
  const router = useRouter();
  const [activeTab, setActiveTab] = useState<'exchange' | 'wallets' | 'history'>('exchange');
  const [fromCurrency, setFromCurrency] = useState('USD');
  const [toCurrency, setToCurrency] = useState('EUR');
  const [amount, setAmount] = useState('');
  const [showFromPicker, setShowFromPicker] = useState(false);
  const [showToPicker, setShowToPicker] = useState(false);
  const parsedAmount = Number.parseFloat(amount);
  const hasValidAmount = Number.isFinite(parsedAmount) && parsedAmount > 0;

  const { data: walletsData, refetch: refetchWallets } = trpc.currency.getWallets.useQuery();
  trpc.currency.getRates.useQuery();
  const { data: historyData, refetch: refetchHistory } = trpc.currency.getHistory.useQuery();
  const { data: quoteData } = trpc.currency.getQuote.useQuery(
    { fromCurrency: fromCurrency as any, toCurrency: toCurrency as any, amount: hasValidAmount ? parsedAmount : 1 },
    { enabled: hasValidAmount }
  );

  const exchangeMutation = trpc.currency.exchange.useMutation();
  const createWalletMutation = trpc.currency.createWallet.useMutation();

  const handleExchange = async () => {
    if (!hasValidAmount) {
      Alert.alert('Invalid Amount', 'Please enter a valid amount');
      return;
    }

    try {
      await exchangeMutation.mutateAsync({
        fromCurrency: fromCurrency as any,
        toCurrency: toCurrency as any,
        amount: parsedAmount,
      });

      Alert.alert('Success', 'Currency exchange completed!');
      setAmount('');
      refetchWallets();
      refetchHistory();
    } catch {
      Alert.alert('Error', 'Exchange failed');
    }
  };

  const handleCreateWallet = async (currency: string) => {
    try {
      await createWalletMutation.mutateAsync({ currency: currency as any });
      Alert.alert('Success', `${currency} wallet created!`);
      refetchWallets();
    } catch {
      Alert.alert('Error', 'Failed to create wallet');
    }
  };

  const swapCurrencies = () => {
    const temp = fromCurrency;
    setFromCurrency(toCurrency);
    setToCurrency(temp);
  };

  const formatCurrency = (value: number, currency: string) => {
    return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(value);
  };

  const renderExchange = () => (
    <View>
      <View style={styles.exchangeCard}>
        <Text style={styles.exchangeLabel}>From</Text>
        <TouchableOpacity
          style={styles.currencySelector}
          onPress={() => setShowFromPicker(!showFromPicker)}
        >
          <Text style={styles.currencyCode}>{fromCurrency}</Text>
          <ChevronDown size={20} color="#94A3B8" />
        </TouchableOpacity>
        {showFromPicker && (
          <View style={styles.pickerContainer}>
            {CURRENCIES.map((c) => (
              <TouchableOpacity
                key={c.code}
                style={styles.pickerItem}
                onPress={() => {
                  setFromCurrency(c.code);
                  setShowFromPicker(false);
                }}
              >
                <Text style={styles.pickerItemText}>{c.code} - {c.name}</Text>
              </TouchableOpacity>
            ))}
          </View>
        )}
        <TextInput
          style={styles.amountInput}
          value={amount}
          onChangeText={setAmount}
          keyboardType="decimal-pad"
          placeholder="0.00"
          placeholderTextColor="#6B7280"
        />
      </View>

      <TouchableOpacity style={styles.swapButton} onPress={swapCurrencies}>
        <ArrowRightLeft size={24} color="#10B981" />
      </TouchableOpacity>

      <View style={styles.exchangeCard}>
        <Text style={styles.exchangeLabel}>To</Text>
        <TouchableOpacity
          style={styles.currencySelector}
          onPress={() => setShowToPicker(!showToPicker)}
        >
          <Text style={styles.currencyCode}>{toCurrency}</Text>
          <ChevronDown size={20} color="#94A3B8" />
        </TouchableOpacity>
        {showToPicker && (
          <View style={styles.pickerContainer}>
            {CURRENCIES.map((c) => (
              <TouchableOpacity
                key={c.code}
                style={styles.pickerItem}
                onPress={() => {
                  setToCurrency(c.code);
                  setShowToPicker(false);
                }}
              >
                <Text style={styles.pickerItemText}>{c.code} - {c.name}</Text>
              </TouchableOpacity>
            ))}
          </View>
        )}
        <Text style={styles.convertedAmount}>
          {quoteData ? formatCurrency(quoteData.toAmount, toCurrency) : '0.00'}
        </Text>
      </View>

      {quoteData && hasValidAmount && (
        <View style={styles.rateInfo}>
          <Text style={styles.rateText}>
            1 {fromCurrency} = {quoteData.exchangeRate.toFixed(4)} {toCurrency}
          </Text>
          <Text style={styles.feeText}>
            Fee: {formatCurrency(quoteData.fee, fromCurrency)}
          </Text>
        </View>
      )}

      <TouchableOpacity
        style={[styles.exchangeButton, exchangeMutation.isPending && styles.buttonDisabled]}
        onPress={handleExchange}
        disabled={exchangeMutation.isPending}
      >
        {exchangeMutation.isPending ? (
          <ActivityIndicator color="#FFFFFF" />
        ) : (
          <Text style={styles.exchangeButtonText}>Exchange</Text>
        )}
      </TouchableOpacity>
    </View>
  );

  const renderWallets = () => (
    <View>
      {walletsData?.wallets?.length ? (
        walletsData.wallets.map((wallet: any) => (
          <View key={wallet.id} style={styles.walletCard}>
            <View style={styles.walletIcon}>
              <Wallet size={24} color="#10B981" />
            </View>
            <View style={styles.walletInfo}>
              <Text style={styles.walletCurrency}>{wallet.currency}</Text>
              <Text style={styles.walletBalance}>
                {formatCurrency(wallet.balance, wallet.currency)}
              </Text>
            </View>
            {wallet.isPrimary && (
              <View style={styles.primaryBadge}>
                <Text style={styles.primaryText}>Primary</Text>
              </View>
            )}
          </View>
        ))
      ) : (
        <View style={styles.emptyState}>
          <Wallet size={48} color="#6B7280" />
          <Text style={styles.emptyStateText}>No wallets yet</Text>
        </View>
      )}

      <Text style={styles.sectionTitle}>Add New Wallet</Text>
      <View style={styles.currencyGrid}>
        {CURRENCIES.filter(c => !walletsData?.wallets?.find((w: any) => w.currency === c.code)).map((c) => (
          <TouchableOpacity
            key={c.code}
            style={styles.addWalletCard}
            onPress={() => handleCreateWallet(c.code)}
          >
            <Text style={styles.addWalletCode}>{c.code}</Text>
            <Text style={styles.addWalletName}>{c.name}</Text>
          </TouchableOpacity>
        ))}
      </View>
    </View>
  );

  const renderHistory = () => (
    <View>
      {historyData?.exchanges?.length ? (
        historyData.exchanges.map((exchange: any) => (
          <View key={exchange.id} style={styles.historyCard}>
            <View style={styles.historyHeader}>
              <Text style={styles.historyPair}>
                {exchange.fromCurrency} → {exchange.toCurrency}
              </Text>
              <Text style={[
                styles.historyStatus,
                { color: exchange.status === 'completed' ? '#10B981' : '#F59E0B' }
              ]}>
                {exchange.status.toUpperCase()}
              </Text>
            </View>
            <View style={styles.historyDetails}>
              <Text style={styles.historyAmount}>
                -{formatCurrency(exchange.fromAmount, exchange.fromCurrency)}
              </Text>
              <Text style={styles.historyReceived}>
                +{formatCurrency(exchange.toAmount, exchange.toCurrency)}
              </Text>
            </View>
            <Text style={styles.historyRate}>
              Rate: {exchange.exchangeRate.toFixed(4)} • Fee: {formatCurrency(exchange.fee, exchange.fromCurrency)}
            </Text>
          </View>
        ))
      ) : (
        <View style={styles.emptyState}>
          <History size={48} color="#6B7280" />
          <Text style={styles.emptyStateText}>No exchange history</Text>
        </View>
      )}
    </View>
  );

  return (
    <SafeAreaView style={styles.container} edges={['top']}>
      <Stack.Screen options={{ headerShown: false }} />
      
      <View style={styles.header}>
        <TouchableOpacity onPress={() => router.back()} style={styles.backButton}>
          <ArrowLeft size={24} color="#FFFFFF" />
        </TouchableOpacity>
        <Text style={styles.title}>Multi-Currency</Text>
      </View>

      <View style={styles.tabContainer}>
        <TouchableOpacity
          style={[styles.tab, activeTab === 'exchange' && styles.activeTab]}
          onPress={() => setActiveTab('exchange')}
        >
          <Text style={[styles.tabText, activeTab === 'exchange' && styles.activeTabText]}>Exchange</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={[styles.tab, activeTab === 'wallets' && styles.activeTab]}
          onPress={() => setActiveTab('wallets')}
        >
          <Text style={[styles.tabText, activeTab === 'wallets' && styles.activeTabText]}>Wallets</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={[styles.tab, activeTab === 'history' && styles.activeTab]}
          onPress={() => setActiveTab('history')}
        >
          <Text style={[styles.tabText, activeTab === 'history' && styles.activeTabText]}>History</Text>
        </TouchableOpacity>
      </View>

      <ScrollView style={styles.content} showsVerticalScrollIndicator={scrollViewWebProps.showsVerticalScrollIndicator}>
        {activeTab === 'exchange' && renderExchange()}
        {activeTab === 'wallets' && renderWallets()}
        {activeTab === 'history' && renderHistory()}
        <View style={{ height: 40 }} />
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#0F172A',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 20,
    paddingVertical: 16,
  },
  backButton: {
    marginRight: 16,
  },
  title: {
    fontSize: 24,
    fontWeight: '700' as const,
    color: '#FFFFFF',
  },
  tabContainer: {
    flexDirection: 'row',
    marginHorizontal: 20,
    backgroundColor: '#1E293B',
    borderRadius: 12,
    padding: 4,
    marginBottom: 20,
  },
  tab: {
    flex: 1,
    paddingVertical: 10,
    alignItems: 'center',
    borderRadius: 8,
  },
  activeTab: {
    backgroundColor: '#10B981',
  },
  tabText: {
    fontSize: 14,
    fontWeight: '600' as const,
    color: '#94A3B8',
  },
  activeTabText: {
    color: '#FFFFFF',
  },
  content: {
    flex: 1,
    paddingHorizontal: 20,
  },
  exchangeCard: {
    backgroundColor: '#1E293B',
    borderRadius: 16,
    padding: 20,
  },
  exchangeLabel: {
    fontSize: 14,
    color: '#94A3B8',
    marginBottom: 12,
  },
  currencySelector: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    backgroundColor: '#0F172A',
    borderRadius: 12,
    padding: 16,
    marginBottom: 16,
  },
  currencyCode: {
    fontSize: 18,
    fontWeight: '600' as const,
    color: '#FFFFFF',
  },
  pickerContainer: {
    backgroundColor: '#0F172A',
    borderRadius: 12,
    marginBottom: 16,
    maxHeight: 200,
  },
  pickerItem: {
    padding: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#1E293B',
  },
  pickerItemText: {
    fontSize: 16,
    color: '#FFFFFF',
  },
  amountInput: {
    fontSize: 32,
    fontWeight: '700' as const,
    color: '#FFFFFF',
    textAlign: 'center',
  },
  convertedAmount: {
    fontSize: 32,
    fontWeight: '700' as const,
    color: '#10B981',
    textAlign: 'center',
  },
  swapButton: {
    alignSelf: 'center',
    backgroundColor: '#1E293B',
    padding: 12,
    borderRadius: 24,
    marginVertical: 16,
  },
  rateInfo: {
    backgroundColor: '#1E293B',
    borderRadius: 12,
    padding: 16,
    marginTop: 20,
    alignItems: 'center',
  },
  rateText: {
    fontSize: 16,
    color: '#FFFFFF',
    fontWeight: '500' as const,
  },
  feeText: {
    fontSize: 14,
    color: '#94A3B8',
    marginTop: 4,
  },
  exchangeButton: {
    backgroundColor: '#10B981',
    borderRadius: 12,
    paddingVertical: 16,
    alignItems: 'center',
    marginTop: 20,
  },
  buttonDisabled: {
    opacity: 0.6,
  },
  exchangeButtonText: {
    fontSize: 18,
    fontWeight: '600' as const,
    color: '#FFFFFF',
  },
  walletCard: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#1E293B',
    borderRadius: 16,
    padding: 20,
    marginBottom: 12,
  },
  walletIcon: {
    width: 48,
    height: 48,
    borderRadius: 24,
    backgroundColor: '#064E3B',
    justifyContent: 'center',
    alignItems: 'center',
  },
  walletInfo: {
    flex: 1,
    marginLeft: 16,
  },
  walletCurrency: {
    fontSize: 18,
    fontWeight: '600' as const,
    color: '#FFFFFF',
  },
  walletBalance: {
    fontSize: 16,
    color: '#94A3B8',
    marginTop: 2,
  },
  primaryBadge: {
    backgroundColor: '#10B981',
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 6,
  },
  primaryText: {
    fontSize: 12,
    fontWeight: '600' as const,
    color: '#FFFFFF',
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: '600' as const,
    color: '#FFFFFF',
    marginTop: 24,
    marginBottom: 16,
  },
  currencyGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
  },
  addWalletCard: {
    width: '48%',
    backgroundColor: '#1E293B',
    borderRadius: 12,
    padding: 16,
    marginBottom: 12,
    alignItems: 'center',
  },
  addWalletCode: {
    fontSize: 18,
    fontWeight: '700' as const,
    color: '#10B981',
  },
  addWalletName: {
    fontSize: 12,
    color: '#94A3B8',
    marginTop: 4,
  },
  historyCard: {
    backgroundColor: '#1E293B',
    borderRadius: 16,
    padding: 16,
    marginBottom: 12,
  },
  historyHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 12,
  },
  historyPair: {
    fontSize: 16,
    fontWeight: '600' as const,
    color: '#FFFFFF',
  },
  historyStatus: {
    fontSize: 12,
    fontWeight: '600' as const,
  },
  historyDetails: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 8,
  },
  historyAmount: {
    fontSize: 16,
    color: '#EF4444',
  },
  historyReceived: {
    fontSize: 16,
    color: '#10B981',
  },
  historyRate: {
    fontSize: 12,
    color: '#94A3B8',
  },
  emptyState: {
    alignItems: 'center',
    paddingTop: 60,
  },
  emptyStateText: {
    fontSize: 18,
    fontWeight: '600' as const,
    color: '#FFFFFF',
    marginTop: 16,
  },
});
