import React, { useState, useEffect, useCallback } from 'react';
import {
  View, Text, StyleSheet, FlatList, Image, TouchableOpacity,
  Alert, Modal, Pressable, Dimensions, Platform, ActivityIndicator,
} from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import * as FileSystem from 'expo-file-system';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { AntDesign, Feather } from '@expo/vector-icons';
import { useFocusEffect } from 'expo-router';
import { useUsers } from '@/contexts/UserContext';
import { useAppData } from '@/contexts/AppDataContext';


const SCREEN_WIDTH = Dimensions.get('window').width;
const THUMB_SIZE = (SCREEN_WIDTH - 48) / 3;
const GALLERY_DIR = FileSystem.documentDirectory + 'gallery/';

type GalleryItem = {
  id: string;
  filename: string;
  uri: string;
  date: string;
  owner: string;      // username ou '__public__'
  isPublic: boolean;
};

// ── Clés AsyncStorage
const PRIVATE_KEY = (username: string) => `gallery_private_${username}`;
const PUBLIC_KEY = 'gallery_public';

// ── Assure l'existence du répertoire
const ensureDir = async () => {
  const info = await FileSystem.getInfoAsync(GALLERY_DIR);
  if (!info.exists) await FileSystem.makeDirectoryAsync(GALLERY_DIR, { intermediates: true });
};

export default function GaleriePage() {
  const { fichier4a: fichier_4a, fichier8a: fichier_8a } = useAppData();
  const { currentUser } = useUsers();
  const [items, setItems] = useState<GalleryItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedItem, setSelectedItem] = useState<GalleryItem | null>(null);
  const [showImportModal, setShowImportModal] = useState(false);

  // ── Chargement des images (privées + publiques)
  const loadImages = useCallback(async () => {
    if (!currentUser?.username) return;
    setLoading(true);
    try {
      // Images privées de l'utilisateur courant
      const privateRaw = await AsyncStorage.getItem(PRIVATE_KEY(currentUser.username));
      const privateItems: GalleryItem[] = privateRaw ? JSON.parse(privateRaw) : [];

      // Images publiques
      const publicRaw = await AsyncStorage.getItem(PUBLIC_KEY);
      const publicItems: GalleryItem[] = publicRaw ? JSON.parse(publicRaw) : [];

      // Fusion, triée par date décroissante
      const all = [...privateItems, ...publicItems].sort(
        (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()
      );
      setItems(all);
    } catch (e) {
      console.error('loadImages error:', e);
    }
    setLoading(false);
  }, [currentUser?.username]);

  useFocusEffect(useCallback(() => { loadImages(); }, [loadImages]));

  // ── Import depuis la galerie
  const handleImport = async (isPublic: boolean) => {
    setShowImportModal(false);
    if (!currentUser?.username) return;

    const perm = await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (!perm.granted) {
      Alert.alert('Permission refusée', 'L\'accès à la galerie est nécessaire.');
      return;
    }

    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsMultipleSelection: true,
      quality: 0.85,
    });

    if (result.canceled) return;

    setLoading(true);
    await ensureDir();

    const newItems: GalleryItem[] = [];

    for (const asset of result.assets) {
      const id = `${Date.now()}_${Math.random().toString(36).slice(2)}`;
      const ext = asset.uri.split('.').pop() ?? 'jpg';
      const filename = `${id}.${ext}`;
      const dest = GALLERY_DIR + filename;

      await FileSystem.copyAsync({ from: asset.uri, to: dest });

      newItems.push({
        id,
        filename,
        uri: dest,
        date: new Date().toISOString(),
        owner: isPublic ? '__public__' : currentUser.username,
        isPublic,
      });
    }

    if (isPublic) {
      const existing = await AsyncStorage.getItem(PUBLIC_KEY);
      const parsed: GalleryItem[] = existing ? JSON.parse(existing) : [];
      await AsyncStorage.setItem(PUBLIC_KEY, JSON.stringify([...parsed, ...newItems]));
    } else {
      const key = PRIVATE_KEY(currentUser.username);
      const existing = await AsyncStorage.getItem(key);
      const parsed: GalleryItem[] = existing ? JSON.parse(existing) : [];
      await AsyncStorage.setItem(key, JSON.stringify([...parsed, ...newItems]));
    }

    await loadImages();
  };

  // ── Suppression
  const handleDelete = async (item: GalleryItem) => {
    Alert.alert(
      'Supprimer',
      'Supprimer cette photo ?',
      [
        { text: 'Annuler', style: 'cancel' },
        {
          text: 'Supprimer',
          style: 'destructive',
          onPress: async () => {
            try {
              await FileSystem.deleteAsync(item.uri, { idempotent: true });

              if (item.isPublic) {
                const raw = await AsyncStorage.getItem(PUBLIC_KEY);
                const parsed: GalleryItem[] = raw ? JSON.parse(raw) : [];
                await AsyncStorage.setItem(PUBLIC_KEY, JSON.stringify(parsed.filter(i => i.id !== item.id)));
              } else {
                const key = PRIVATE_KEY(currentUser!.username);
                const raw = await AsyncStorage.getItem(key);
                const parsed: GalleryItem[] = raw ? JSON.parse(raw) : [];
                await AsyncStorage.setItem(key, JSON.stringify(parsed.filter(i => i.id !== item.id)));
              }

              setSelectedItem(null);
              await loadImages();
            } catch (e) {
              console.error('Delete error:', e);
            }
          },
        },
      ]
    );
  };

  const formatDate = (iso: string) => {
    const d = new Date(iso);
    return `${String(d.getDate()).padStart(2,'0')}/${String(d.getMonth()+1).padStart(2,'0')}/${d.getFullYear()}`;
  };

  // ── Rendu d'une vignette
  const renderItem = ({ item }: { item: GalleryItem }) => (
    <TouchableOpacity
      style={styles.thumb}
      onPress={() => setSelectedItem(item)}
      activeOpacity={0.85}
    >
      <Image source={{ uri: item.uri }} style={styles.thumbImage} />
      {item.isPublic && (
        <View style={styles.publicBadge}>
          <Feather name="globe" size={10} color="white" />
        </View>
      )}
    </TouchableOpacity>
  );

  return (
    <View style={styles.container}>

      {/* Header */}
      <View style={styles.header}>
        <Text style={styles.headerTitle}>Galerie</Text>
        <Text style={styles.headerSub}>{items.length} photo{items.length !== 1 ? 's' : ''}</Text>
        <TouchableOpacity style={styles.addButton} onPress={() => setShowImportModal(true)}>
          <AntDesign name="plus" size={22} color="white" />
        </TouchableOpacity>
      </View>

      {/* Grille */}
      {loading ? (
        <ActivityIndicator style={{ marginTop: 60 }} size="large" color="#E8437B" />
      ) : items.length === 0 ? (
        <View style={styles.empty}>
          <Feather name="image" size={48} color="#ccc" />
          <Text style={styles.emptyText}>Aucune photo</Text>
          <Text style={styles.emptySubText}>Appuyez sur + pour importer</Text>
        </View>
      ) : (
        <FlatList
          data={items}
          renderItem={renderItem}
          keyExtractor={item => item.id}
          numColumns={3}
          contentContainerStyle={styles.grid}
          showsVerticalScrollIndicator={false}
        />
      )}

      {/* Modal choix import */}
      <Modal visible={showImportModal} transparent animationType="fade" onRequestClose={() => setShowImportModal(false)}>
        <Pressable style={styles.modalBackdrop} onPress={() => setShowImportModal(false)}>
          <View style={styles.importModal}>
            <Text style={styles.importTitle}>Importer des photos</Text>

            <TouchableOpacity
              style={[styles.importOption, styles.importPrivate]}
              onPress={() => handleImport(false)}
            >
              <AntDesign name="lock" size={20} color="#333" style={{ marginRight: 10 }} />
              <View>
                <Text style={styles.importOptionTitle}>Import privé</Text>
                <Text style={styles.importOptionSub}>Visible uniquement par {currentUser?.username}</Text>
              </View>
            </TouchableOpacity>

            <TouchableOpacity
              style={[styles.importOption, styles.importPublic]}
              onPress={() => handleImport(true)}
            >
              <Feather name="globe" size={20} color="white" style={{ marginRight: 10 }} />
              <View>
                <Text style={[styles.importOptionTitle, { color: 'white' }]}>Import public</Text>
                <Text style={[styles.importOptionSub, { color: 'rgba(255,255,255,0.8)' }]}>Visible par tous les utilisateurs</Text>
              </View>
            </TouchableOpacity>

            <TouchableOpacity onPress={() => setShowImportModal(false)} style={styles.cancelButton}>
              <Text style={styles.cancelText}>Annuler</Text>
            </TouchableOpacity>
          </View>
        </Pressable>
      </Modal>

      {/* Modal plein écran */}
      {selectedItem && (
        <Modal visible animationType="fade" onRequestClose={() => setSelectedItem(null)}>
          <View style={styles.fullscreenModal}>
            <Image
              source={{ uri: selectedItem.uri }}
              style={styles.fullscreenImage}
              resizeMode="contain"
            />

            {/* Infos */}
            <View style={styles.fullscreenInfo}>
              <View style={styles.fullscreenBadge}>
                {selectedItem.isPublic
                  ? <><Feather name="globe" size={13} color="white" /><Text style={styles.badgeText}> Public</Text></>
                  : <><AntDesign name="lock" size={13} color="white" /><Text style={styles.badgeText}> Privé</Text></>
                }
              </View>
              <Text style={styles.fullscreenDate}>{formatDate(selectedItem.date)}</Text>
            </View>

            {/* Actions */}
            <View style={styles.fullscreenActions}>
              <TouchableOpacity
                style={styles.fullscreenClose}
                onPress={() => setSelectedItem(null)}
              >
                <AntDesign name="close" size={24} color="white" />
              </TouchableOpacity>

              {/* Supprimer uniquement si propriétaire */}
              {(selectedItem.owner === currentUser?.username || selectedItem.isPublic) && (
                <TouchableOpacity
                  style={styles.fullscreenDelete}
                  onPress={() => handleDelete(selectedItem)}
                >
                  <AntDesign name="delete" size={22} color="white" />
                </TouchableOpacity>
              )}
            </View>
          </View>
        </Modal>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f8f8f8',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingTop: Platform.OS === 'ios' ? 16 : 12,
    paddingBottom: 12,
    backgroundColor: 'white',
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  headerTitle: {
    fontSize: 20,
    fontWeight: '700',
    color: '#1a1a1a',
    flex: 1,
  },
  headerSub: {
    fontSize: 13,
    color: '#999',
    marginRight: 12,
  },
  addButton: {
    width: 38,
    height: 38,
    borderRadius: 19,
    backgroundColor: '#E8437B',
    alignItems: 'center',
    justifyContent: 'center',
  },
  grid: {
    padding: 12,
    gap: 6,
  },
  thumb: {
    width: THUMB_SIZE,
    height: THUMB_SIZE,
    margin: 3,
    borderRadius: 6,
    overflow: 'hidden',
    backgroundColor: '#e0e0e0',
  },
  thumbImage: {
    width: '100%',
    height: '100%',
  },
  publicBadge: {
    position: 'absolute',
    bottom: 5,
    right: 5,
    backgroundColor: '#E8437B',
    borderRadius: 8,
    padding: 3,
  },
  empty: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    gap: 8,
  },
  emptyText: {
    fontSize: 17,
    fontWeight: '600',
    color: '#aaa',
    marginTop: 8,
  },
  emptySubText: {
    fontSize: 14,
    color: '#ccc',
  },
  // Modal import
  modalBackdrop: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.5)',
    justifyContent: 'flex-end',
  },
  importModal: {
    backgroundColor: 'white',
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    padding: 24,
    paddingBottom: Platform.OS === 'ios' ? 40 : 24,
    gap: 12,
  },
  importTitle: {
    fontSize: 18,
    fontWeight: '700',
    color: '#1a1a1a',
    marginBottom: 8,
    textAlign: 'center',
  },
  importOption: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 16,
    borderRadius: 12,
  },
  importPrivate: {
    backgroundColor: '#f4f4f4',
  },
  importPublic: {
    backgroundColor: '#E8437B',
  },
  importOptionTitle: {
    fontSize: 15,
    fontWeight: '600',
    color: '#1a1a1a',
  },
  importOptionSub: {
    fontSize: 12,
    color: '#777',
    marginTop: 2,
  },
  cancelButton: {
    alignItems: 'center',
    paddingVertical: 14,
  },
  cancelText: {
    fontSize: 15,
    color: '#999',
  },
  // Fullscreen
  fullscreenModal: {
    flex: 1,
    backgroundColor: 'black',
    justifyContent: 'center',
  },
  fullscreenImage: {
    width: '100%',
    height: '100%',
  },
  fullscreenActions: {
    position: 'absolute',
    top: Platform.OS === 'ios' ? 56 : 16,
    left: 0,
    right: 0,
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingHorizontal: 20,
  },
  fullscreenClose: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: 'rgba(0,0,0,0.5)',
    alignItems: 'center',
    justifyContent: 'center',
  },
  fullscreenDelete: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: 'rgba(220,50,50,0.7)',
    alignItems: 'center',
    justifyContent: 'center',
  },
  fullscreenInfo: {
    position: 'absolute',
    bottom: Platform.OS === 'ios' ? 50 : 24,
    left: 20,
    right: 20,
    flexDirection: 'row',
    alignItems: 'center',
    gap: 10,
  },
  fullscreenBadge: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'rgba(0,0,0,0.6)',
    borderRadius: 12,
    paddingHorizontal: 10,
    paddingVertical: 5,
  },
  badgeText: {
    color: 'white',
    fontSize: 12,
    fontWeight: '600',
  },
  fullscreenDate: {
    color: 'rgba(255,255,255,0.7)',
    fontSize: 13,
  },
});