import React, { useEffect, useRef, useState } from 'react';
import { StyleSheet, View, Text, Modal, TouchableOpacity, FlatList, Animated, Platform } from 'react-native';
import { X, Check, Search, Globe } from 'lucide-react-native';
import { colors } from '@/constants/colors';
import { useTheme } from '@/context/ThemeContext';
import { LinearGradient } from 'expo-linear-gradient';
import { useToast } from '@/context/ToastContext';

interface CountrySelectorProps {
  visible: boolean;
  onClose: () => void;
  onSelect: (country: string) => void;
  selectedCountry: string;
}

// List of countries with their codes
const countries = [
  { code: 'NG', name: 'Nigeria', currency: 'NGN' },
  { code: 'US', name: 'United States', currency: 'USDT' },
  { code: 'GB', name: 'United Kingdom', currency: 'USDT' },
  { code: 'CA', name: 'Canada', currency: 'USDT' },
  { code: 'AU', name: 'Australia', currency: 'USDT' },
  { code: 'IN', name: 'India', currency: 'USDT' },
  { code: 'ZA', name: 'South Africa', currency: 'USDT' },
  { code: 'GH', name: 'Ghana', currency: 'USDT' },
  { code: 'KE', name: 'Kenya', currency: 'USDT' },
  { code: 'UG', name: 'Uganda', currency: 'USDT' },
  { code: 'TZ', name: 'Tanzania', currency: 'USDT' },
  { code: 'RW', name: 'Rwanda', currency: 'USDT' },
  { code: 'AE', name: 'United Arab Emirates', currency: 'USDT' },
  { code: 'SA', name: 'Saudi Arabia', currency: 'USDT' },
  { code: 'QA', name: 'Qatar', currency: 'USDT' },
  { code: 'SG', name: 'Singapore', currency: 'USDT' },
  { code: 'MY', name: 'Malaysia', currency: 'USDT' },
  { code: 'ID', name: 'Indonesia', currency: 'USDT' },
  { code: 'PH', name: 'Philippines', currency: 'USDT' },
  { code: 'TH', name: 'Thailand', currency: 'USDT' },
];

export default function CountrySelector({ visible, onClose, onSelect, selectedCountry }: CountrySelectorProps) {
  const { theme, colors } = useTheme();
  const { showToast } = useToast();
  
  // Animation values
  const slideAnim = useRef(new Animated.Value(Platform.OS === 'web' ? 0 : 100)).current;
  const opacityAnim = useRef(new Animated.Value(0)).current;
  
  // State
  const [searchQuery, setSearchQuery] = useState('');
  const [filteredCountries, setFilteredCountries] = useState(countries);
  
  // Filter countries based on search query
  useEffect(() => {
    if (searchQuery) {
      const filtered = countries.filter(country => 
        country.name.toLowerCase().includes(searchQuery.toLowerCase())
      );
      setFilteredCountries(filtered);
    } else {
      setFilteredCountries(countries);
    }
  }, [searchQuery]);
  
  // Animate modal when visibility changes
  useEffect(() => {
    if (visible) {
      // Slide up animation when modal becomes visible
      Animated.parallel([
        Animated.timing(slideAnim, {
          toValue: 0,
          duration: 300,
          useNativeDriver: Platform.OS !== 'web',
        }),
        Animated.timing(opacityAnim, {
          toValue: 1,
          duration: 300,
          useNativeDriver: Platform.OS !== 'web',
        })
      ]).start();
    } else {
      // Reset animation value when modal is hidden
      if (Platform.OS === 'web') {
        slideAnim.setValue(0);
      } else {
        slideAnim.setValue(100);
      }
      opacityAnim.setValue(0);
    }
  }, [visible]);
  
  const handleSelect = (countryCode: string) => {
    onSelect(countryCode);
  };
  
  const renderCountryItem = ({ item }: { item: typeof countries[0] }) => {
    const isSelected = selectedCountry === item.code;
    
    return (
      <TouchableOpacity
        style={[
          styles.countryItem,
          isSelected && styles.selectedCountryItem
        ]}
        onPress={() => handleSelect(item.code)}
        activeOpacity={0.7}
      >
        <View style={styles.countryInfo}>
          <Text style={[styles.countryName, { color: colors.text }]}>{item.name}</Text>
          <Text style={[styles.countryCurrency, { color: colors.textSecondary }]}>
            Currency: {item.currency}
          </Text>
        </View>
        {isSelected && (
          <View style={[styles.checkContainer, { backgroundColor: colors.primary }]}>
            <Check size={16} color={colors.textWhite} />
          </View>
        )}
      </TouchableOpacity>
    );
  };
  
  return (
    <Modal
      visible={visible}
      transparent={true}
      animationType="none"
      onRequestClose={onClose}
    >
      <View style={styles.modalContainer}>
        <Animated.View 
          style={[
            styles.modalContent,
            { backgroundColor: theme === 'dark' ? colors.bgBlack : colors.background },
            Platform.OS === 'web' 
              ? { 
                  opacity: opacityAnim,
                  bottom: 0,
                } 
              : { 
                  transform: [{ translateY: slideAnim }],
                  opacity: opacityAnim
                }
          ]}
        >
          {theme === 'dark' && (
            <LinearGradient
              colors={['rgba(30, 39, 46, 0.8)', 'rgba(0, 0, 0, 1)']}
              style={styles.backgroundGradient}
            />
          )}
          
          <View style={styles.header}>
            <Text style={[styles.headerTitle, { color: colors.text }]}>Select Region</Text>
            <TouchableOpacity 
              style={[styles.closeButton, { backgroundColor: theme === 'dark' ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.1)' }]}
              onPress={onClose}
              activeOpacity={0.7}
            >
              <X size={20} color={colors.text} />
            </TouchableOpacity>
          </View>
          
          <View style={styles.infoContainer}>
            <Globe size={20} color={colors.primary} style={styles.infoIcon} />
            <Text style={[styles.infoText, { color: colors.textSecondary }]}>
              Your region determines the currency used for transactions.
            </Text>
          </View>
          
          <FlatList
            data={filteredCountries}
            renderItem={renderCountryItem}
            keyExtractor={(item) => item.code}
            contentContainerStyle={[styles.countriesList, { backgroundColor: theme === 'dark' ? colors.bgDark : colors.backgroundSecondary }]}
            showsVerticalScrollIndicator={false}
          />
          
          <View style={styles.footer}>
            <TouchableOpacity 
              style={[styles.cancelButton, { borderColor: colors.border }]}
              onPress={onClose}
              activeOpacity={0.7}
            >
              <Text style={[styles.cancelButtonText, { color: colors.text }]}>Cancel</Text>
            </TouchableOpacity>
          </View>
        </Animated.View>
      </View>
    </Modal>
  );
}

const styles = StyleSheet.create({
  modalContainer: {
    flex: 1,
    justifyContent: 'flex-end',
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
  },
  modalContent: {
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    maxHeight: '80%',
    position: 'relative',
  },
  backgroundGradient: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 16,
    borderBottomWidth: 1,
    borderBottomColor: 'rgba(74, 101, 114, 0.2)',
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: 'bold',
  },
  closeButton: {
    padding: 8,
    borderRadius: 20,
  },
  infoContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 16,
    backgroundColor: 'rgba(41, 171, 226, 0.1)',
  },
  infoIcon: {
    marginRight: 12,
  },
  infoText: {
    flex: 1,
    fontSize: 14,
  },
  searchContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 12,
    borderBottomWidth: 1,
    borderBottomColor: 'rgba(74, 101, 114, 0.2)',
  },
  searchIcon: {
    marginRight: 8,
  },
  searchInput: {
    flex: 1,
    height: 40,
    padding: 8,
    fontSize: 16,
  },
  countriesList: {
    padding: 16,
    maxHeight: 400,
  },
  countryItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 12,
    paddingHorizontal: 16,
    borderBottomWidth: 1,
    borderBottomColor: 'rgba(74, 101, 114, 0.1)',
  },
  selectedCountryItem: {
    backgroundColor: 'rgba(41, 171, 226, 0.1)',
  },
  countryInfo: {
    flex: 1,
  },
  countryName: {
    fontSize: 16,
    fontWeight: '500',
    marginBottom: 4,
  },
  countryCurrency: {
    fontSize: 14,
  },
  checkContainer: {
    width: 24,
    height: 24,
    borderRadius: 12,
    justifyContent: 'center',
    alignItems: 'center',
  },
  footer: {
    padding: 16,
    borderTopWidth: 1,
    borderTopColor: 'rgba(74, 101, 114, 0.2)',
  },
  cancelButton: {
    paddingVertical: 12,
    borderRadius: 8,
    alignItems: 'center',
    borderWidth: 1,
  },
  cancelButtonText: {
    fontSize: 16,
    fontWeight: '500',
  },
});