import React, { useEffect, useState } from 'react';
import { View, FlatList, StyleSheet, TouchableOpacity, ActivityIndicator, ImageBackground } from 'react-native';
import { Text, useTheme, Surface } from 'react-native-paper';
import { API_BASE_URL } from '../../config';
import { useNavigation } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import { SelectionStackParamList } from '../../types/Navigation';
import ScreenTitle from '../../components/ScreenTitle';

const RAYON_IMAGES: Record<string, string> = {
    'Alcools': 'https://images.unsplash.com/photo-1608270586620-248524c67de9?q=80&w=500&auto=format&fit=crop',
    'Asiatique': 'https://images.unsplash.com/photo-1496116218417-1a781b1c416c?q=80&w=500&auto=format&fit=crop',
    'Féculents': 'https://images.unsplash.com/photo-1518977676601-b53f82aba655?q=80&w=500&auto=format&fit=crop',
    'Fromage': 'https://images.unsplash.com/photo-1627935722051-395636b0d8a5?q=80&w=1473&auto=format&fit=crop',
    'Fruit à coques': 'https://plus.unsplash.com/premium_photo-1726768984120-f476b15835f2?q=80&w=500&auto=format&fit=crop',
    'Huiles': 'https://plus.unsplash.com/premium_photo-1692825694870-10196b7640f9?q=80&w=500&auto=format&fit=crop',
    'Oeufs': 'https://images.unsplash.com/photo-1506976785307-8732e854ad03?q=80&w=500&auto=format&fit=crop',
    'Petit Déjeuner': 'https://images.unsplash.com/photo-1620146344904-097a0002d797?w=500&auto=format&fit=crop',
    'Poissonnerie': 'https://images.unsplash.com/photo-1576330383200-2bf325cfec52?q=80&w=500&auto=format&fit=crop',
    'Sirops': 'https://images.unsplash.com/photo-1536852386-74fd4d6daf8b?q=80&w=500&auto=format&fit=crop',
    'Crèmerie': 'https://plus.unsplash.com/premium_photo-1723759365132-af57124362b0?q=80&w=500&auto=format&fit=crop',
    'Conserves': 'https://images.unsplash.com/photo-1738618140037-09e11c8e644a?q=80&w=1470&auto=format&fit=crop',
    'Apéritif': 'https://images.unsplash.com/photo-1692071097980-2d78ced0cf75?q=80&w=500&auto=format&fit=crop',
    'Vins': 'https://images.unsplash.com/photo-1510812431401-41d2bd2722f3?q=80&w=500&auto=format&fit=crop',
    'Sodas': 'https://images.unsplash.com/photo-1622483767028-3f66f32aef97?q=80&w=500&auto=format&fit=crop',
    'Eau': 'https://images.unsplash.com/photo-1548839140-29a749e1cf4d?q=80&w=500&auto=format&fit=crop',
    'Jus de fruit': 'https://images.unsplash.com/photo-1613478223719-2ab802602423?q=80&w=500&auto=format&fit=crop',
    'Boissons chaudes': 'https://images.unsplash.com/photo-1517256064527-09c73fc73e38?q=80&w=500&auto=format&fit=crop',
    'Fruits et Légumes': 'https://images.unsplash.com/photo-1610832958506-aa56368176cf?q=80&w=500&auto=format&fit=crop',
    'Viandes': 'https://images.unsplash.com/photo-1607623814075-e51df1bdc82f?q=80&w=500&auto=format&fit=crop',
    'Volailles': 'https://images.unsplash.com/photo-1587593810167-a84920ea0781?q=80&w=500&auto=format&fit=crop',
    'Traiteur': 'https://images.unsplash.com/photo-1555939594-58d7cb561ad1?q=80&w=500&auto=format&fit=crop',
    'Produit Laitier': 'https://images.unsplash.com/photo-1563636619-e9143da7973b?q=80&w=500&auto=format&fit=crop',
    'Pain': 'https://images.unsplash.com/photo-1549931319-a545dcf3bc73?q=80&w=500&auto=format&fit=crop',
    'Pâtisserie': 'https://images.unsplash.com/photo-1578985545062-69928b1d9587?q=80&w=500&auto=format&fit=crop',
    'Céréales': 'https://images.unsplash.com/photo-1536153635972-1fc2e818f642?q=80&w=500&auto=format&fit=crop',
    'Condiments': 'https://images.unsplash.com/photo-1596040033229-a9821ebd058d?q=80&w=500&auto=format&fit=crop',
    'Sucreries': 'https://images.unsplash.com/photo-1581798459219-318e76aecc7b?q=80&w=500&auto=format&fit=crop',
    'Gâteaux secs': 'https://images.unsplash.com/photo-1558961363-fa8fdf82db35?q=80&w=500&auto=format&fit=crop',
    'Desserts': 'https://images.unsplash.com/photo-1563729784474-d77dbb933a9e?q=80&w=500&auto=format&fit=crop',
    'Italien': 'https://images.unsplash.com/photo-1673442635965-34f1b36d8944?w=500&auto=format&fit=crop',
    'Mexicain': 'https://images.unsplash.com/photo-1565299585323-38d6b0865b47?q=80&w=500&auto=format&fit=crop',
    'Autre': 'https://images.unsplash.com/photo-1578916171728-46686eac8d58?q=80&w=500&auto=format&fit=crop',
};

const getImageForRayon = (rayonName: string) => {
    const exactMatch = RAYON_IMAGES[rayonName];
    if (exactMatch) return exactMatch;
    const normalized = rayonName.trim();
    return RAYON_IMAGES[normalized] || RAYON_IMAGES['Autre'];
};

export default function RayonListScreen() {
    const [rayons, setRayons] = useState<string[]>([]);
    const [loading, setLoading] = useState(true);
    const theme = useTheme();
    const navigation = useNavigation<StackNavigationProp<SelectionStackParamList>>();

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

    const fetchRayons = async () => {
        try {
            const response = await fetch(`${API_BASE_URL}/items/options/rayons`);
            if (response.ok) {
                const data: string[] = await response.json();
                const sortedData = data.sort((a, b) => a.localeCompare(b));
                setRayons(sortedData);
            }
        } catch (error) {
            console.error("Erreur chargement rayons", error);
        } finally {
            setLoading(false);
        }
    };

    const renderItem = ({ item }: { item: string }) => {
        const imageUri = getImageForRayon(item);

        return (
            <TouchableOpacity
                style={styles.gridItem}
                onPress={() => navigation.navigate('ItemsByRayon', { rayon: item })}
                activeOpacity={0.8}
            >
                <Surface style={[styles.cardSurface, { backgroundColor: theme.colors.surfaceVariant }]} elevation={2}>
                    <ImageBackground
                        source={{ uri: imageUri }}
                        style={styles.imageBackground}
                        imageStyle={{ borderRadius: 12 }}
                    >
                        <View style={styles.overlay}>
                            <Text
                                variant="titleMedium"
                                style={styles.rayonTitle}
                                numberOfLines={2}
                            >
                                {item}
                            </Text>
                        </View>
                    </ImageBackground>
                </Surface>
            </TouchableOpacity>
        );
    };

    if (loading) {
        return (
            <View style={[styles.center, { backgroundColor: theme.colors.background }]}>
                <ActivityIndicator size="large" color={theme.colors.primary} />
            </View>
        );
    }

    return (
        <View style={[styles.container, { backgroundColor: theme.colors.background }]}>
            <ScreenTitle title="Rayons" />
            <FlatList
                key={2}
                data={rayons}
                keyExtractor={(item) => item}
                renderItem={renderItem}
                numColumns={2}
                contentContainerStyle={styles.list}
                columnWrapperStyle={styles.columnWrapper}
                showsVerticalScrollIndicator={false}
            />
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1
    },
    center: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
    },
    headerContainer: {
        padding: 20,
        paddingTop: 60,
        borderBottomWidth: 1,
    },
    headerTitle: {
        fontSize: 28,
        fontWeight: '800',
    },
    list: {
        padding: 12,
        paddingTop: 20,
    },
    columnWrapper: {
        justifyContent: 'space-between',
    },
    gridItem: {
        width: '48%',
        aspectRatio: 1,
        marginBottom: 16,
    },
    cardSurface: {
        flex: 1,
        borderRadius: 12,
        overflow: 'hidden',
    },
    imageBackground: {
        flex: 1,
        justifyContent: 'flex-end',
    },
    overlay: {
        backgroundColor: 'rgba(0,0,0,0.5)',
        padding: 10,
        paddingTop: 15,
        width: '100%',
    },
    rayonTitle: {
        color: '#ffffff',
        fontWeight: 'bold',
        textAlign: 'center',
        textShadowColor: 'rgba(0, 0, 0, 0.75)',
        textShadowOffset: { width: 0, height: 1 },
        textShadowRadius: 3,
    }
});