import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import { COLORS, SHADOWS } from '../constants/theme';
import { useMobileSignal, MobileSignalInfo } from '../hooks/useMobileSignal';

interface MobileSignalIndicatorProps {
  showDetails?: boolean;
  onPress?: () => void;
  compact?: boolean;
}

export const MobileSignalIndicator: React.FC<MobileSignalIndicatorProps> = ({
  showDetails = false,
  onPress,
  compact = false,
}) => {
  const { signalInfo, checkConnection } = useMobileSignal();

  // Função para obter a cor de fundo baseada na força do sinal
  const getBackgroundColor = () => {
    if (signalInfo.signalStrength >= 70) return COLORS.success + '15';
    if (signalInfo.signalStrength >= 40) return COLORS.warning + '15';
    return COLORS.danger + '15';
  };

  // Função para obter a cor do gradiente baseada na força do sinal
  const getGradientColors = (): [string, string] => {
    if (signalInfo.signalStrength >= 70) return [COLORS.success, "#059669"];
    if (signalInfo.signalStrength >= 40) return [COLORS.warning, "#D97706"];
    return [COLORS.danger, "#DC2626"];
  };

  // Função para obter o texto de recomendação
  const getRecommendationText = () => {
    if (signalInfo.signalStrength >= 70) return 'Conexão excelente - Modo online';
    if (signalInfo.signalStrength >= 40) return 'Conexão boa - Modo online';
    if (signalInfo.signalStrength >= 30) return 'Conexão aceitável - Modo online';
    return 'Sinal fraco - Modo offline ativado';
  };

  // Função para obter o ícone baseado no tipo de conexão e força do sinal
  const getConnectionIcon = (info: MobileSignalInfo) => {
    if (!info.isConnected) {
      return { name: 'cloud-offline', color: COLORS.danger };
    }

    if (info.connectionType === 'wifi') {
      if (info.signalStrength >= 70) {
        return { name: 'wifi', color: COLORS.success };
      } else if (info.signalStrength >= 40) {
        return { name: 'wifi', color: COLORS.warning };
      } else {
        return { name: 'wifi', color: COLORS.danger };
      }
    }

    if (info.connectionType === 'cellular') {
      if (info.signalStrength >= 70) {
        return { name: 'cellular', color: COLORS.success };
      } else if (info.signalStrength >= 40) {
        return { name: 'cellular', color: COLORS.warning };
      } else {
        return { name: 'cellular', color: COLORS.danger };
      }
    }

    return { name: 'help-circle', color: COLORS.textLight };
  };

  // Função para obter a cor da barra de sinal
  const getSignalBarColor = (strength: number) => {
    if (strength >= 70) return COLORS.success;
    if (strength >= 40) return COLORS.warning;
    return COLORS.danger;
  };

  // Função para obter o texto de status
  const getStatusText = (info: MobileSignalInfo) => {
    if (!info.isConnected) return 'Sem conexão';
    
    if (info.connectionType === 'wifi') {
      return `WiFi ${info.signalStrength}%`;
    }
    
    if (info.connectionType === 'cellular') {
      const generation = info.details?.cellularGeneration?.toUpperCase() || '';
      return `${generation} ${info.signalStrength}%`;
    }
    
    return 'Conectado';
  };

  // Função para obter o texto de modo offline
  const getOfflineText = (info: MobileSignalInfo) => {
    if (info.shouldUseOffline) {
      return 'Modo Offline';
    }
    return 'Modo Online';
  };

  // Função para obter a cor do modo offline
  const getOfflineColor = (info: MobileSignalInfo) => {
    return info.shouldUseOffline ? COLORS.warning : COLORS.success;
  };

  const iconInfo = getConnectionIcon(signalInfo);
  const statusText = getStatusText(signalInfo);
  const offlineText = getOfflineText(signalInfo);
  const offlineColor = getOfflineColor(signalInfo);

  if (compact) {
    return (
      <TouchableOpacity
        style={styles.compactContainer}
        onPress={onPress || checkConnection}
        activeOpacity={0.7}
      >
        <Ionicons name={iconInfo.name as any} size={16} color={iconInfo.color} />
        <View style={[styles.signalBar, { backgroundColor: getSignalBarColor(signalInfo.signalStrength) }]} />
      </TouchableOpacity>
    );
  }

  return (
    <TouchableOpacity
      style={styles.container}
      onPress={onPress || checkConnection}
      activeOpacity={0.7}
    >
      {/* Header com gradiente */}
      <LinearGradient
        colors={getGradientColors()}
        style={styles.headerGradient}
        start={{ x: 0, y: 0 }}
        end={{ x: 1, y: 1 }}
      >
        <View style={styles.headerContent}>
          <View style={styles.iconContainer}>
            <Ionicons name={iconInfo.name as any} size={20} color="white" />
          </View>
          <Text style={styles.headerTitle}>{statusText}</Text>
          <TouchableOpacity style={styles.refreshButton} onPress={checkConnection}>
            <Ionicons name="refresh" size={16} color="white" />
          </TouchableOpacity>
        </View>
      </LinearGradient>

      {/* Conteúdo do card */}
      <View style={styles.cardContent}>
        {showDetails && (
          <>
            {/* Barra de sinal visual */}
            <View style={styles.signalContainer}>
              <View style={styles.signalBars}>
                {[1, 2, 3, 4].map((bar) => (
                  <View
                    key={bar}
                    style={[
                      styles.signalBar,
                      {
                        backgroundColor: bar <= Math.ceil(signalInfo.signalStrength / 25) 
                          ? getSignalBarColor(signalInfo.signalStrength)
                          : COLORS.textLight + '40',
                        height: bar * 3 + 2,
                      }
                    ]}
                  />
                ))}
              </View>
              <Text style={styles.signalPercentage}>{signalInfo.signalStrength}%</Text>
            </View>

            {/* Modo offline */}
            <View style={styles.offlineContainer}>
              <View style={[styles.offlineIndicator, { backgroundColor: offlineColor }]} />
              <Text style={[styles.offlineText, { color: offlineColor }]}>
                {offlineText}
              </Text>
            </View>

            {/* Recomendação de conexão */}
            <View style={styles.recommendationContainer}>
              <Text style={styles.recommendationText}>
                {getRecommendationText()}
              </Text>
            </View>

            {/* Detalhes adicionais */}
            {signalInfo.details?.cellularGeneration && (
              <Text style={styles.detailText}>
                Rede: {signalInfo.details.cellularGeneration.toUpperCase()}
              </Text>
            )}
            
            {signalInfo.details?.isConnectionExpensive && (
              <Text style={styles.detailText}>
                Conexão cara
              </Text>
            )}
          </>
        )}
      </View>
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: COLORS.card,
    borderRadius: 12,
    marginVertical: 8,
    overflow: 'hidden',
    ...SHADOWS.medium,
  },
  headerGradient: {
    paddingVertical: 12,
    paddingHorizontal: 16,
  },
  headerContent: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  headerTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: 'white',
    flex: 1,
    textAlign: 'center',
  },
  refreshButton: {
    width: 32,
    height: 32,
    borderRadius: 16,
    backgroundColor: 'rgba(255, 255, 255, 0.2)',
    alignItems: 'center',
    justifyContent: 'center',
  },
  cardContent: {
    padding: 16,
  },
  compactContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 8,
  },
  iconContainer: {
    marginRight: 12,
    alignItems: 'center',
    justifyContent: 'center',
    width: 32,
    height: 32,
  },
  infoContainer: {
    flex: 1,
  },
  statusText: {
    fontSize: 16,
    fontWeight: '600',
    color: COLORS.text,
    marginBottom: 4,
  },
  signalContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginVertical: 8,
  },
  signalBars: {
    flexDirection: 'row',
    alignItems: 'flex-end',
    marginRight: 8,
    height: 18,
  },
  signalBar: {
    width: 3,
    marginRight: 2,
    borderRadius: 1.5,
    backgroundColor: COLORS.textLight,
  },
  signalPercentage: {
    fontSize: 12,
    fontWeight: '500',
    color: COLORS.textLight,
  },
  offlineContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginVertical: 4,
  },
  offlineIndicator: {
    width: 8,
    height: 8,
    borderRadius: 4,
    marginRight: 6,
  },
  offlineText: {
    fontSize: 12,
    fontWeight: '500',
  },
  detailText: {
    fontSize: 11,
    color: COLORS.textLight,
    marginTop: 2,
  },
  recommendationContainer: {
    marginTop: 8,
    paddingHorizontal: 8,
    paddingVertical: 6,
    backgroundColor: 'rgba(255, 255, 255, 0.8)',
    borderRadius: 6,
    borderWidth: 1,
    borderColor: 'rgba(0, 0, 0, 0.1)',
  },
  recommendationText: {
    fontSize: 11,
    color: COLORS.text,
    fontWeight: '600',
    textAlign: 'center',
  },
  updateIndicator: {
    marginLeft: 8,
    padding: 4,
  },
}); 