import React, { useState, useEffect, useRef } from 'react';
import { StyleSheet, View, Text, TouchableOpacity, Animated, Alert, Platform, Vibration } from 'react-native';
import { colors } from '@/constants/colors';
import useTradeStore from '@/store/useTradeStore';
import { useTheme } from '@/context/ThemeContext';
import { useToast } from '@/context/ToastContext';

export default function AccountTypeSwitch() {
  const { isDemoAccount, switchAccountMode, activeTrades } = useTradeStore();
  const { theme, colors } = useTheme();
  const { showToast } = useToast();
  
  // Animation values
  const translateX = useRef(new Animated.Value(isDemoAccount ? 0 : 1)).current;
  const scaleAnim = useRef(new Animated.Value(1)).current;
  
  // Update animation when account mode changes
  useEffect(() => {
    Animated.spring(translateX, {
      toValue: isDemoAccount ? 0 : 1,
      friction: 8,
      tension: 50,
      useNativeDriver: true,
    }).start();
  }, [isDemoAccount]);
  
  const handleSwitch = () => {
    // Check if there are active trades
    if (activeTrades.length > 0) {
      Alert.alert(
        "Active Trades",
        "You cannot switch account mode while you have active trades. Please wait for your trades to complete.",
        [{ text: "OK" }]
      );
      
      // Animate button shake to indicate error
      Animated.sequence([
        Animated.timing(scaleAnim, {
          toValue: 0.95,
          duration: 100,
          useNativeDriver: true,
        }),
        Animated.timing(scaleAnim, {
          toValue: 1.05,
          duration: 100,
          useNativeDriver: true,
        }),
        Animated.timing(scaleAnim, {
          toValue: 1,
          duration: 100,
          useNativeDriver: true,
        }),
      ]).start();
      
      return;
    }
    
    // Provide haptic feedback on native platforms
    if (Platform.OS !== 'web') {
      try {
        Vibration.vibrate(20);
      } catch (error) {
        console.error("Vibration error:", error);
      }
    }
    
    // Switch account mode
    switchAccountMode();
    
    // Show toast notification
    showToast(
      `Switched to ${isDemoAccount ? 'Real' : 'Demo'} Account mode`,
      'info'
    );
  };
  
  // Interpolate translateX for the switch thumb
  const thumbTranslateX = translateX.interpolate({
    inputRange: [0, 1],
    outputRange: [2, 78], // Adjust based on your design
  });
  
  return (
    <Animated.View 
      style={[
        styles.container,
        { 
          backgroundColor: theme === 'dark' ? 'rgba(17, 17, 17, 0.8)' : colors.backgroundSecondary,
          transform: [{ scale: scaleAnim }]
        }
      ]}
    >
      <TouchableOpacity 
        style={styles.switchContainer}
        onPress={handleSwitch}
        activeOpacity={0.8}
      >
        <Animated.View 
          style={[
            styles.switchThumb,
            { 
              backgroundColor: isDemoAccount ? colors.accent : colors.primary,
              transform: [{ translateX: thumbTranslateX }]
            }
          ]}
        />
        
        <View style={styles.labelContainer}>
          <Text 
            style={[
              styles.label, 
              { 
                color: isDemoAccount ? colors.textWhite : colors.textSecondary,
                fontWeight: isDemoAccount ? 'bold' : 'normal'
              }
            ]}
          >
            Demo
          </Text>
          
          <Text 
            style={[
              styles.label, 
              { 
                color: !isDemoAccount ? colors.textWhite : colors.textSecondary,
                fontWeight: !isDemoAccount ? 'bold' : 'normal'
              }
            ]}
          >
            Real
          </Text>
        </View>
      </TouchableOpacity>
    </Animated.View>
  );
}

const styles = StyleSheet.create({
  container: {
    borderRadius: 30,
    padding: 2,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 2,
  },
  switchContainer: {
    width: 150,
    height: 36,
    borderRadius: 30,
    position: 'relative',
  },
  switchThumb: {
    position: 'absolute',
    width: 70,
    height: 32,
    borderRadius: 16,
    top: 2,
    left: 0,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,
    shadowRadius: 2,
    elevation: 4,
  },
  labelContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 20,
    height: '100%',
  },
  label: {
    fontSize: 14,
    zIndex: 1,
  },
});