import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, ScrollView, TouchableOpacity, ActivityIndicator, Alert } from 'react-native';
import { ThemedView } from '@/components/themed-view';
import { ThemedText } from '@/components/themed-text';
import { carteService, Carte } from '@/services/api';

export default function CartesScreen() {
  const [cartes, setCartes] = useState<Carte[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    loadCartes();
  }, []);

  const loadCartes = async () => {
    try {
      setLoading(true);
      setError(null);
      const cartesData = await carteService.getAll();
      setCartes(cartesData);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Erreur lors du chargement des cartes');
    } finally {
      setLoading(false);
    }
  };

  const handleCartePress = (carte: Carte) => {
    Alert.alert(
      carte.titre,
      `${carte.description || 'Aucune description disponible'}\n\nÉchelle: ${carte.echelle || 'Non spécifiée'}\nAnnée: ${carte.annee || 'Non spécifiée'}`,
      [
        { text: 'Annuler', style: 'cancel' },
        { 
          text: 'Voir la carte', 
          onPress: () => {
            // Ici vous pouvez implémenter l'affichage de la carte PDF
            Alert.alert('Carte PDF', `URL: ${carte.url_image}\n\nNote: L'affichage des cartes PDF sera implémentée dans la version finale.`);
          }
        }
      ]
    );
  };

  const getTypeIcon = (type: string) => {
    switch (type) {
      case 'aerienne': return '✈️';
      case 'topographique': return '🏔️';
      case 'infrastructure': return '🏗️';
      case 'plan': return '📐';
      default: return '🗺️';
    }
  };

  const getTypeColor = (type: string) => {
    switch (type) {
      case 'aerienne': return '#3498db';
      case 'topographique': return '#27ae60';
      case 'infrastructure': return '#e67e22';
      case 'plan': return '#9b59b6';
      default: return '#95a5a6';
    }
  };

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

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

  return (
    <ScrollView style={styles.container}>
      <ThemedView style={styles.header}>
        <ThemedText style={styles.title}>Cartes Aéroportuaires</ThemedText>
        <ThemedText style={styles.subtitle}>
          {cartes.length} carte{cartes.length > 1 ? 's' : ''} disponible{cartes.length > 1 ? 's' : ''}
        </ThemedText>
      </ThemedView>

      {cartes.length === 0 ? (
        <View style={styles.emptyContainer}>
          <Text style={styles.emptyIcon}>🗺️</Text>
          <ThemedText style={styles.emptyText}>Aucune carte disponible</ThemedText>
        </View>
      ) : (
        <View style={styles.cartesList}>
          {cartes.map((carte) => (
            <TouchableOpacity
              key={carte.id}
              style={styles.carteCard}
              onPress={() => handleCartePress(carte)}
            >
              <View style={styles.carteHeader}>
                <Text style={styles.carteIcon}>
                  {getTypeIcon(carte.type_carte || 'autre')}
                </Text>
                <View style={styles.carteInfo}>
                  <ThemedText style={styles.carteTitle}>{carte.titre}</ThemedText>
                  <ThemedText style={styles.carteType}>
                    Type: {carte.type_carte || 'autre'}
                  </ThemedText>
                </View>
                <View style={[
                  styles.carteBadge,
                  { backgroundColor: getTypeColor(carte.type_carte || 'autre') }
                ]}>
                  <Text style={styles.badgeText}>
                    {carte.type_carte?.toUpperCase() || 'AUTRE'}
                  </Text>
                </View>
              </View>

              {carte.description && (
                <ThemedText style={styles.carteDescription} numberOfLines={2}>
                  {carte.description}
                </ThemedText>
              )}

              <View style={styles.carteDetails}>
                {carte.echelle && (
                  <View style={styles.detailItem}>
                    <Text style={styles.detailIcon}>📏</Text>
                    <ThemedText style={styles.detailValue}>
                      Échelle: {carte.echelle}
                    </ThemedText>
                  </View>
                )}
                {carte.annee && (
                  <View style={styles.detailItem}>
                    <Text style={styles.detailIcon}>📅</Text>
                    <ThemedText style={styles.detailValue}>
                      Année: {carte.annee}
                    </ThemedText>
                  </View>
                )}
              </View>

              <View style={styles.carteFooter}>
                <Text style={styles.pdfIndicator}>📄 Carte PDF</Text>
                <TouchableOpacity style={styles.viewButton}>
                  <Text style={styles.viewButtonText}>Voir la carte</Text>
                </TouchableOpacity>
              </View>
            </TouchableOpacity>
          ))}
        </View>
      )}
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  header: {
    padding: 20,
    backgroundColor: '#fff',
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 5,
  },
  subtitle: {
    fontSize: 16,
    color: '#666',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f5f5f5',
  },
  loadingText: {
    marginTop: 10,
    fontSize: 16,
    color: '#666',
  },
  errorContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f5f5f5',
    padding: 20,
  },
  errorText: {
    fontSize: 16,
    color: '#e74c3c',
    textAlign: 'center',
    marginBottom: 20,
  },
  retryButton: {
    backgroundColor: '#3498db',
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 5,
  },
  retryButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 40,
  },
  emptyIcon: {
    fontSize: 64,
    marginBottom: 20,
  },
  emptyText: {
    fontSize: 18,
    color: '#666',
    textAlign: 'center',
  },
  cartesList: {
    padding: 15,
  },
  carteCard: {
    backgroundColor: '#fff',
    borderRadius: 10,
    padding: 15,
    marginBottom: 15,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 3.84,
    elevation: 5,
  },
  carteHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10,
  },
  carteIcon: {
    fontSize: 24,
    marginRight: 12,
  },
  carteInfo: {
    flex: 1,
  },
  carteTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 4,
  },
  carteType: {
    fontSize: 14,
    color: '#666',
  },
  carteBadge: {
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 12,
  },
  badgeText: {
    color: '#fff',
    fontSize: 12,
    fontWeight: 'bold',
  },
  carteDescription: {
    fontSize: 14,
    color: '#666',
    marginBottom: 10,
    lineHeight: 20,
  },
  carteDetails: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 15,
    marginBottom: 10,
  },
  detailItem: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  detailIcon: {
    fontSize: 14,
    marginRight: 5,
  },
  detailValue: {
    fontSize: 12,
    color: '#333',
  },
  carteFooter: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingTop: 10,
    borderTopWidth: 1,
    borderTopColor: '#f0f0f0',
  },
  pdfIndicator: {
    fontSize: 12,
    color: '#e74c3c',
    fontWeight: 'bold',
  },
  viewButton: {
    backgroundColor: '#3498db',
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 15,
  },
  viewButtonText: {
    color: '#fff',
    fontSize: 12,
    fontWeight: 'bold',
  },
});
