import React from 'react';
import { View, Text, StyleSheet, ScrollView, TouchableOpacity, ActivityIndicator, Alert } from 'react-native';
import { useAuth } from '@/contexts/AuthContext';
import { useAeroports } from '@/hooks/useAeroports';
import { ThemedView } from '@/components/themed-view';
import { ThemedText } from '@/components/themed-text';

export default function AeroportsScreen() {
  const { user } = useAuth();
  const { aeroports, loading, error, refreshAeroports } = useAeroports();

  const getAirportTypeInfo = (type: string) => {
    switch (type) {
      case 'international':
        return { icon: '🌍', label: 'International', color: '#e74c3c' };
      case 'regional':
        return { icon: '✈️', label: 'Régional', color: '#3498db' };
      case 'national':
        return { icon: '🛫', label: 'National', color: '#27ae60' };
      default:
        return { icon: '🏢', label: 'Aérodrome', color: '#95a5a6' };
    }
  };

  const getStatusInfo = (statut: string) => {
    switch (statut) {
      case 'actif':
        return { icon: '✅', label: 'Actif', color: '#27ae60' };
      case 'inactif':
        return { icon: '❌', label: 'Inactif', color: '#e74c3c' };
      case 'maintenance':
        return { icon: '🔧', label: 'Maintenance', color: '#f39c12' };
      default:
        return { icon: '❓', label: 'Inconnu', color: '#95a5a6' };
    }
  };

  const handleAeroportPress = (aeroport: any) => {
    Alert.alert(
      aeroport.nom,
      `📍 ${aeroport.ville} - ${aeroport.region}\n\n✈️ Codes:\n• IATA: ${aeroport.code_iata || 'N/A'}\n• OACI: ${aeroport.code_oaci || 'N/A'}\n\n📏 Informations:\n• Type: ${aeroport.type}\n• Statut: ${aeroport.statut}\n• Altitude: ${aeroport.altitude || 'N/A'}m\n\n📝 Description:\n${aeroport.description || 'Aéroport régional du Sénégal'}`,
      [
        { text: 'Fermer', style: 'cancel' },
        { 
          text: 'Voir Documents', 
          onPress: () => {
            // Navigation vers les documents de cet aéroport
            Alert.alert('Documents', `Documents et cartes pour ${aeroport.nom} seront disponibles prochainement.`);
          }
        }
      ]
    );
  };

  if (loading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#3498db" />
        <ThemedText style={styles.loadingText}>Chargement des aéroports...</ThemedText>
      </View>
    );
  }

  if (error) {
    return (
      <View style={styles.errorContainer}>
        <ThemedText style={styles.errorText}>Erreur: {error}</ThemedText>
        <TouchableOpacity style={styles.retryButton} onPress={refreshAeroports}>
          <Text style={styles.retryButtonText}>Réessayer</Text>
        </TouchableOpacity>
      </View>
    );
  }

  return (
    <ScrollView style={styles.container}>
      <ThemedView style={styles.content}>
        <View style={styles.header}>
          <ThemedText style={styles.title}>Aéroports Régionaux du Sénégal</ThemedText>
          <ThemedText style={styles.subtitle}>
            {aeroports.length} aéroport{aeroports.length > 1 ? 's' : ''} régional{aeroports.length > 1 ? 'aux' : ''} - Direction Générale de l'Aviation Civile
          </ThemedText>
        </View>

        {aeroports.length === 0 ? (
          <View style={styles.emptyContainer}>
            <Text style={styles.emptyIcon}>✈️</Text>
            <ThemedText style={styles.emptyTitle}>Aucun aéroport trouvé</ThemedText>
            <ThemedText style={styles.emptyText}>
              Les aéroports seront affichés ici une fois qu'ils seront ajoutés à la base de données.
            </ThemedText>
            {user?.role === 'admin' && (
              <TouchableOpacity style={styles.addButton}>
                <Text style={styles.addButtonText}>Ajouter un aéroport</Text>
              </TouchableOpacity>
            )}
          </View>
        ) : (
          <View style={styles.aeroportsList}>
            <ThemedText style={styles.listTitle}>
              {aeroports.length} aéroport{aeroports.length > 1 ? 's' : ''} disponible{aeroports.length > 1 ? 's' : ''}
            </ThemedText>
            
            {aeroports.map((aeroport) => {
              const typeInfo = getAirportTypeInfo(aeroport.type);
              const statusInfo = getStatusInfo(aeroport.statut);
              
              return (
                <TouchableOpacity
                  key={aeroport.id}
                  style={styles.aeroportCard}
                  onPress={() => handleAeroportPress(aeroport)}
                >
                  <View style={styles.aeroportHeader}>
                    <View style={[styles.aeroportIconContainer, { backgroundColor: typeInfo.color }]}>
                      <Text style={styles.aeroportIcon}>{typeInfo.icon}</Text>
                    </View>
                    <View style={styles.aeroportInfo}>
                      <ThemedText style={styles.aeroportName}>{aeroport.nom}</ThemedText>
                      <ThemedText style={styles.aeroportLocation}>
                        📍 {aeroport.ville} - {aeroport.region}
                      </ThemedText>
                    </View>
                    <View style={[styles.statusBadge, { backgroundColor: statusInfo.color }]}>
                      <Text style={styles.statusBadgeText}>
                        {statusInfo.icon} {statusInfo.label}
                      </Text>
                    </View>
                  </View>
                  
                  <View style={styles.aeroportDetails}>
                    <View style={styles.detailRow}>
                      <View style={styles.detailItem}>
                        <Text style={styles.detailIcon}>🆔</Text>
                        <ThemedText style={styles.detailLabel}>IATA:</ThemedText>
                        <ThemedText style={styles.detailValue}>
                          {aeroport.code_iata || 'N/A'}
                        </ThemedText>
                      </View>
                      <View style={styles.detailItem}>
                        <Text style={styles.detailIcon}>🌐</Text>
                        <ThemedText style={styles.detailLabel}>OACI:</ThemedText>
                        <ThemedText style={styles.detailValue}>
                          {aeroport.code_oaci || 'N/A'}
                        </ThemedText>
                      </View>
                    </View>
                    <View style={styles.detailRow}>
                      <View style={styles.detailItem}>
                        <Text style={styles.detailIcon}>🏷️</Text>
                        <ThemedText style={styles.detailLabel}>Type:</ThemedText>
                        <ThemedText style={styles.detailValue}>{typeInfo.label}</ThemedText>
                      </View>
                      {aeroport.altitude && (
                        <View style={styles.detailItem}>
                          <Text style={styles.detailIcon}>⛰️</Text>
                          <ThemedText style={styles.detailLabel}>Altitude:</ThemedText>
                          <ThemedText style={styles.detailValue}>{aeroport.altitude}m</ThemedText>
                        </View>
                      )}
                    </View>
                  </View>
                  
                  <View style={styles.aeroportFooter}>
                    <Text style={styles.dgacIndicator}>🏛️ DGAC Sénégal</Text>
                    <View style={styles.viewButton}>
                      <Text style={styles.viewButtonText}>Détails</Text>
                    </View>
                  </View>
                </TouchableOpacity>
              );
            })}
          </View>
        )}

        <TouchableOpacity style={styles.refreshButton} onPress={refreshAeroports}>
          <Text style={styles.refreshButtonText}>🔄 Actualiser</Text>
        </TouchableOpacity>
      </ThemedView>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  content: {
    flex: 1,
    padding: 20,
  },
  header: {
    marginBottom: 30,
  },
  title: {
    fontSize: 28,
    fontWeight: 'bold',
    color: '#2c3e50',
    marginBottom: 8,
  },
  subtitle: {
    fontSize: 16,
    color: '#7f8c8d',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  loadingText: {
    marginTop: 16,
    fontSize: 16,
    color: '#7f8c8d',
  },
  errorContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  errorText: {
    fontSize: 16,
    color: '#e74c3c',
    textAlign: 'center',
    marginBottom: 20,
  },
  retryButton: {
    backgroundColor: '#3498db',
    paddingHorizontal: 20,
    paddingVertical: 12,
    borderRadius: 8,
  },
  retryButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '500',
  },
  emptyContainer: {
    alignItems: 'center',
    padding: 40,
  },
  emptyIcon: {
    fontSize: 64,
    marginBottom: 16,
  },
  emptyTitle: {
    fontSize: 20,
    fontWeight: '600',
    color: '#2c3e50',
    marginBottom: 8,
  },
  emptyText: {
    fontSize: 16,
    color: '#7f8c8d',
    textAlign: 'center',
    lineHeight: 24,
    marginBottom: 24,
  },
  addButton: {
    backgroundColor: '#27ae60',
    paddingHorizontal: 20,
    paddingVertical: 12,
    borderRadius: 8,
  },
  addButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '500',
  },
  aeroportsList: {
    marginBottom: 20,
  },
  listTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: '#2c3e50',
    marginBottom: 16,
  },
  aeroportCard: {
    backgroundColor: '#fff',
    padding: 16,
    borderRadius: 12,
    marginBottom: 12,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 3.84,
    elevation: 5,
  },
  aeroportHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 12,
  },
  aeroportIcon: {
    fontSize: 24,
    marginRight: 12,
  },
  aeroportIconContainer: {
    width: 50,
    height: 50,
    borderRadius: 25,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 15,
  },
  aeroportInfo: {
    flex: 1,
  },
  statusBadge: {
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 12,
  },
  statusBadgeText: {
    color: 'white',
    fontSize: 12,
    fontWeight: '600',
  },
  aeroportName: {
    fontSize: 18,
    fontWeight: '600',
    color: '#2c3e50',
    marginBottom: 2,
  },
  aeroportLocation: {
    fontSize: 14,
    color: '#7f8c8d',
  },
  aeroportBadge: {
    backgroundColor: '#ecf0f1',
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 12,
  },
  badgeText: {
    fontSize: 12,
    color: '#2c3e50',
    textTransform: 'capitalize',
  },
  aeroportDetails: {
    flexDirection: 'row',
    marginBottom: 8,
  },
  detailItem: {
    flexDirection: 'row',
    marginRight: 20,
  },
  detailLabel: {
    fontSize: 14,
    fontWeight: '500',
    color: '#7f8c8d',
    marginRight: 4,
  },
  detailValue: {
    fontSize: 14,
    color: '#2c3e50',
  },
  statusActive: {
    color: '#27ae60',
    fontWeight: '500',
  },
  statusInactive: {
    color: '#e74c3c',
    fontWeight: '500',
  },
  aeroportDescription: {
    fontSize: 14,
    color: '#7f8c8d',
    lineHeight: 20,
  },
  refreshButton: {
    backgroundColor: '#3498db',
    padding: 16,
    borderRadius: 8,
    alignItems: 'center',
    marginTop: 20,
  },
  refreshButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '500',
  },
  detailRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 8,
  },
  detailIcon: {
    fontSize: 14,
    marginRight: 6,
  },
  aeroportFooter: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginTop: 12,
    paddingTop: 12,
    borderTopWidth: 1,
    borderTopColor: '#ecf0f1',
  },
  dgacIndicator: {
    fontSize: 12,
    color: '#7f8c8d',
    fontStyle: 'italic',
  },
  viewButton: {
    backgroundColor: '#3498db',
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 15,
  },
  viewButtonText: {
    color: 'white',
    fontSize: 12,
    fontWeight: '600',
  },
});
