import React, { useMemo, useState } from 'react';
import { Image, ScrollView, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { useApp } from '../context/AppContext';
import { Card } from '../components/ui/Card';
import { Button } from '../components/ui/Button';
import { RootStackParamList } from '../navigation/types';
import { colors, radius, shadows } from '../lib/theme';
import { Ionicons } from '@expo/vector-icons';

export default function Explore() {
  const navigation = useNavigation<NativeStackNavigationProp<RootStackParamList>>();
  const { shops, shopsReady, user, toggleFavorite, isFavorite } = useApp();
  const [query, setQuery] = useState('');
  const [filter, setFilter] = useState<'todas' | 'top' | 'servicos'>('todas');

  const filtered = useMemo(() => {
    const normalized = query.trim().toLowerCase();
    return [...shops]
      .filter((shop) => {
        if (!normalized) return true;
        return (
          shop.name.toLowerCase().includes(normalized) ||
          (shop.address || '').toLowerCase().includes(normalized) ||
          (shop.services || []).some(s => s.name.toLowerCase().includes(normalized))
        );
      })
      .filter((shop) => (filter === 'top' ? (shop.rating || 0) >= 4.7 : true))
      .sort((a, b) => {
        if (filter === 'servicos') return (b.services || []).length - (a.services || []).length;
        return (b.rating || 0) - (a.rating || 0);
      });
  }, [shops, query, filter]);

  const featuredShops = filtered.slice(0, 3);

  const goToProfile = () => {
    if (!user) {
      navigation.navigate('Login');
      return;
    }
    navigation.getParent()?.navigate('ProfileTab' as never);
  };

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled" showsVerticalScrollIndicator={false}>
        
        {/* Modern Header Section */}
        <View style={styles.header}>
          <View style={styles.headerCopy}>
            <Text style={styles.greeting}>
              {user ? `Olá, ${user.name.split(' ')[0]} 👋` : 'Bem-vindo 👋'}
            </Text>
            <Text style={styles.headline}>Encontra um espaço</Text>
          </View>
          <TouchableOpacity 
            style={styles.avatarButton} 
            activeOpacity={0.85}
            onPress={goToProfile}
          >
            <View style={styles.avatarGradient}>
              <Text style={styles.avatarText}>
                {user ? user.name.charAt(0).toUpperCase() : 'S'}
              </Text>
            </View>
          </TouchableOpacity>
        </View>

        {/* Clean Integrated Search Box */}
        <View style={styles.searchSection}>
          <View style={styles.searchBox}>
            <Ionicons name="search-outline" size={20} color={colors.placeholder} />
            <TextInput
              value={query}
              onChangeText={setQuery}
              placeholder="Pesquisar nome, endereço ou serviço..."
              placeholderTextColor={colors.placeholder}
              style={styles.searchInput}
            />
            {query.length > 0 && (
              <TouchableOpacity onPress={() => setQuery('')}>
                <Ionicons name="close-circle" size={18} color={colors.textMuted} />
              </TouchableOpacity>
            )}
          </View>

          {/* Quick Filters Scroll */}
          <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={styles.filtersScroll}>
            {[
              ['todas', 'Melhor avaliação'],
              ['top', 'Top avaliadas (4.7+)'],
              ['servicos', 'Mais serviços'],
            ].map(([id, label]) => (
              <TouchableOpacity
                key={id}
                onPress={() => setFilter(id as typeof filter)}
                style={[styles.filterChip, filter === id && styles.filterChipActive]}
                activeOpacity={0.8}
              >
                <Text style={[styles.filterChipText, filter === id && styles.filterChipTextActive]}>{label}</Text>
              </TouchableOpacity>
            ))}
          </ScrollView>
        </View>

        {!shopsReady ? (
          <View style={styles.emptyState}>
            <Ionicons name="sync-outline" size={44} color={colors.primary} style={styles.loadingSpinner} />
            <Text style={styles.emptyTitle}>A carregar espaços...</Text>
          </View>
        ) : filtered.length === 0 ? (
          <View style={styles.emptyState}>
            <Ionicons name="search-outline" size={48} color={colors.textMuted} />
            <Text style={styles.emptyTitle}>Nenhum espaço encontrado</Text>
            <Text style={styles.emptyText}>Tenta ajustar a pesquisa ou filtros.</Text>
            <Button variant="outline" onPress={() => { setQuery(''); setFilter('todas'); }}>
              Limpar Tudo
            </Button>
          </View>
        ) : (
          <>
            {/* Featured Section */}
            {featuredShops.length > 0 && (
              <View style={styles.featuredSection}>
                <View style={styles.sectionHeaderRow}>
                  <Text style={styles.sectionTitle}>Em destaque</Text>
                  <Text style={styles.countBadge}>{filtered.length} espaços</Text>
                </View>
                <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={styles.featuredList}>
                  {featuredShops.map((shop) => {
                    const isFav = isFavorite(shop.id);
                    return (
                      <TouchableOpacity
                        key={shop.id}
                        style={styles.featuredCard}
                        activeOpacity={0.9}
                        onPress={() => navigation.navigate('ShopDetails', { shopId: shop.id })}
                      >
                        <View style={styles.featuredImageWrapper}>
                          {shop.imageUrl ? (
                            <Image source={{ uri: shop.imageUrl }} style={styles.featuredImage} />
                          ) : (
                            <View style={styles.featuredFallback}>
                              <Ionicons name="storefront-outline" size={40} color={colors.primary} style={{ opacity: 0.6 }} />
                            </View>
                          )}
                          
                          {/* Rating Badge Overlay */}
                          <View style={styles.ratingBadgeOverlay}>
                            <Ionicons name="star" size={12} color={colors.star} />
                            <Text style={styles.ratingBadgeText}>{(shop.rating || 0).toFixed(1)}</Text>
                          </View>
                          
                          {/* Floating Favorite Heart Button */}
                          <TouchableOpacity 
                            style={styles.favoriteBtnFloating}
                            activeOpacity={0.7}
                            onPress={(e) => {
                              e.stopPropagation();
                              toggleFavorite(shop.id);
                            }}
                          >
                            <Ionicons 
                              name={isFav ? "heart" : "heart-outline"} 
                              size={18} 
                              color={isFav ? colors.danger : colors.textInverse} 
                            />
                          </TouchableOpacity>
                        </View>
                        <View style={styles.featuredCardBody}>
                          <Text style={styles.featuredShopName} numberOfLines={1}>{shop.name}</Text>
                          <View style={styles.infoRowInline}>
                            <Ionicons name="location-outline" size={13} color={colors.textMuted} />
                            <Text style={styles.addressText} numberOfLines={1}>
                              {shop.address && shop.address !== 'Endereço a definir' ? shop.address : 'Morada por definir'}
                            </Text>
                          </View>
                          <View style={styles.cardFooterRow}>
                            <Text style={styles.featuredStatsText}>{(shop.services || []).length} serv. • {(shop.barbers || []).length} barb.</Text>
                            <View style={styles.goBtn}>
                              <Ionicons name="arrow-forward" size={14} color={colors.textInverse} />
                            </View>
                          </View>
                        </View>
                      </TouchableOpacity>
                    );
                  })}
                </ScrollView>
              </View>
            )}

            {/* All Spaces Section */}
            <View style={styles.allSpacesSection}>
              <View style={styles.sectionHeaderRow}>
                <Text style={styles.sectionTitle}>Todos os espaços</Text>
                <Text style={styles.countBadge}>{filtered.length}</Text>
              </View>
              <View style={styles.allSpacesList}>
                {filtered.map((shop) => {
                  const isFav = isFavorite(shop.id);
                  return (
                    <TouchableOpacity
                      key={shop.id}
                      style={styles.shopCard}
                      activeOpacity={0.9}
                      onPress={() => navigation.navigate('ShopDetails', { shopId: shop.id })}
                    >
                      <View style={styles.shopImageWrapper}>
                        {shop.imageUrl ? (
                          <Image source={{ uri: shop.imageUrl }} style={styles.shopImage} />
                        ) : (
                          <View style={styles.shopImageFallback}>
                            <Ionicons name="storefront-outline" size={24} color={colors.primary} style={{ opacity: 0.5 }} />
                          </View>
                        )}
                        {/* Floating Favorite Button on list image */}
                        <TouchableOpacity 
                          style={styles.favoriteBtnListFloating}
                          activeOpacity={0.7}
                          onPress={(e) => {
                            e.stopPropagation();
                            toggleFavorite(shop.id);
                          }}
                        >
                          <Ionicons 
                            name={isFav ? "heart" : "heart-outline"} 
                            size={14} 
                            color={isFav ? colors.danger : colors.textInverse} 
                          />
                        </TouchableOpacity>
                      </View>

                      <View style={styles.shopBody}>
                        <View style={styles.shopNameRow}>
                          <Text style={styles.shopName} numberOfLines={1}>{shop.name}</Text>
                          <View style={styles.ratingBadgeSmall}>
                            <Ionicons name="star" size={11} color={colors.star} />
                            <Text style={styles.ratingTextSmall}>{(shop.rating || 0).toFixed(1)}</Text>
                          </View>
                        </View>
                        
                        <View style={styles.infoRowInline}>
                          <Ionicons name="location-outline" size={13} color={colors.textMuted} />
                          <Text style={styles.addressText} numberOfLines={1}>
                            {shop.address && shop.address !== 'Endereço a definir' ? shop.address : 'Morada por definir'}
                          </Text>
                        </View>

                        <View style={styles.shopStatsRow}>
                          <View style={styles.statTag}>
                            <Ionicons name="cut-outline" size={10} color={colors.primary} />
                            <Text style={styles.statTagText}>{(shop.services || []).length} serv.</Text>
                          </View>
                          <View style={styles.statTag}>
                            <Ionicons name="people-outline" size={10} color={colors.primary} />
                            <Text style={styles.statTagText}>{(shop.barbers || []).length} barb.</Text>
                          </View>
                        </View>
                      </View>

                      <View style={styles.chevronIconContainer}>
                        <Ionicons name="chevron-forward" size={18} color={colors.primary} />
                      </View>
                    </TouchableOpacity>
                  );
                })}
              </View>
            </View>
          </>
        )}
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  content: {
    padding: 20,
    gap: 22,
    paddingBottom: 40,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginTop: 8,
  },
  headerCopy: {
    flex: 1,
  },
  greeting: {
    color: colors.textMuted,
    fontSize: 14,
    fontWeight: '600',
    marginBottom: 4,
    letterSpacing: 0.3,
  },
  headline: {
    color: colors.text,
    fontSize: 28,
    fontWeight: '900',
    letterSpacing: -0.5,
  },
  avatarButton: {
    shadowColor: colors.primary,
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.15,
    shadowRadius: 8,
    elevation: 4,
  },
  avatarGradient: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: colors.primary,
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 2,
    borderColor: colors.surface,
  },
  avatarText: {
    color: colors.textInverse,
    fontSize: 18,
    fontWeight: '800',
  },
  searchSection: {
    gap: 12,
  },
  searchBox: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.surface,
    borderRadius: radius.md,
    borderWidth: 1,
    borderColor: 'rgba(15,118,110,0.1)',
    paddingHorizontal: 16,
    gap: 10,
    height: 54,
    shadowColor: '#102018',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.04,
    shadowRadius: 8,
    elevation: 2,
  },
  searchInput: {
    flex: 1,
    height: '100%',
    color: colors.text,
    fontSize: 15,
    fontWeight: '500',
  },
  filtersScroll: {
    gap: 8,
    paddingVertical: 2,
  },
  filterChip: {
    borderRadius: radius.pill,
    backgroundColor: colors.surface,
    paddingHorizontal: 16,
    paddingVertical: 10,
    borderWidth: 1,
    borderColor: 'rgba(15,118,110,0.08)',
    shadowColor: '#102018',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.02,
    shadowRadius: 4,
    elevation: 1,
  },
  filterChipActive: {
    backgroundColor: colors.primary,
    borderColor: colors.primary,
  },
  filterChipText: {
    color: colors.textMuted,
    fontSize: 13,
    fontWeight: '700',
  },
  filterChipTextActive: {
    color: colors.textInverse,
  },
  categoriesSection: {
    gap: 12,
    marginTop: 4,
  },
  categoriesScroll: {
    gap: 14,
    paddingRight: 10,
    paddingVertical: 4,
  },
  categoryItem: {
    alignItems: 'center',
    gap: 8,
    width: 72,
  },
  categoryIconBg: {
    width: 58,
    height: 58,
    borderRadius: 29,
    backgroundColor: colors.surface,
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 1,
    borderColor: 'rgba(15,118,110,0.08)',
    shadowColor: '#102018',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.05,
    shadowRadius: 8,
    elevation: 2,
  },
  categoryIconBgActive: {
    backgroundColor: colors.primary,
    borderColor: colors.primary,
  },
  categoryLabel: {
    fontSize: 12,
    fontWeight: '600',
    color: colors.textMuted,
    textAlign: 'center',
  },
  categoryLabelActive: {
    color: colors.primary,
    fontWeight: '800',
  },
  promoBanner: {
    flexDirection: 'row',
    backgroundColor: colors.surfaceDark,
    borderRadius: radius.lg,
    overflow: 'hidden',
    shadowColor: colors.primaryDark,
    shadowOffset: { width: 0, height: 6 },
    shadowOpacity: 0.12,
    shadowRadius: 12,
    elevation: 5,
    marginTop: 6,
    borderWidth: 1,
    borderColor: 'rgba(255,255,255,0.04)',
  },
  promoContent: {
    flex: 1.2,
    padding: 20,
    gap: 8,
  },
  promoBadge: {
    alignSelf: 'flex-start',
    backgroundColor: 'rgba(255,255,255,0.12)',
    paddingHorizontal: 8,
    paddingVertical: 3,
    borderRadius: radius.xs,
  },
  promoBadgeText: {
    color: '#e2f4f1',
    fontSize: 10,
    fontWeight: '800',
    letterSpacing: 1,
  },
  promoTitle: {
    color: colors.textInverse,
    fontSize: 18,
    fontWeight: '900',
    lineHeight: 22,
  },
  promoSubtitle: {
    color: 'rgba(248,251,248,0.72)',
    fontSize: 12,
    lineHeight: 16,
    fontWeight: '500',
  },
  promoButton: {
    alignSelf: 'flex-start',
    backgroundColor: colors.surface,
    paddingHorizontal: 14,
    paddingVertical: 8,
    borderRadius: radius.sm,
    marginTop: 6,
  },
  promoButtonText: {
    color: colors.surfaceDark,
    fontSize: 12,
    fontWeight: '800',
  },
  promoVisual: {
    flex: 0.8,
    alignItems: 'center',
    justifyContent: 'center',
    position: 'relative',
  },
  promoBackgroundIcon: {
    position: 'absolute',
    right: -10,
    bottom: -10,
  },
  sectionHeaderRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginBottom: 12,
  },
  sectionTitle: {
    color: colors.text,
    fontSize: 18,
    fontWeight: '900',
    letterSpacing: -0.3,
  },
  countBadge: {
    color: colors.primary,
    backgroundColor: colors.primarySoft,
    fontSize: 11,
    fontWeight: '800',
    paddingHorizontal: 10,
    paddingVertical: 4,
    borderRadius: radius.pill,
    textTransform: 'uppercase',
  },
  featuredSection: {
    marginTop: 4,
  },
  featuredList: {
    gap: 16,
    paddingRight: 10,
    paddingVertical: 4,
  },
  featuredCard: {
    width: 250,
    backgroundColor: colors.surface,
    borderRadius: radius.lg,
    borderWidth: 1,
    borderColor: 'rgba(15,118,110,0.06)',
    overflow: 'hidden',
    shadowColor: '#102018',
    shadowOffset: { width: 0, height: 6 },
    shadowOpacity: 0.05,
    shadowRadius: 10,
    elevation: 3,
  },
  featuredImageWrapper: {
    position: 'relative',
    width: '100%',
    height: 130,
  },
  featuredImage: {
    width: '100%',
    height: '100%',
  },
  featuredFallback: {
    width: '100%',
    height: '100%',
    backgroundColor: colors.primarySoft,
    alignItems: 'center',
    justifyContent: 'center',
  },
  ratingBadgeOverlay: {
    position: 'absolute',
    bottom: 10,
    left: 10,
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'rgba(12,20,17,0.7)',
    borderRadius: radius.pill,
    paddingHorizontal: 8,
    paddingVertical: 3.5,
    gap: 4,
    borderWidth: 0.5,
    borderColor: 'rgba(255,255,255,0.15)',
  },
  ratingBadgeText: {
    color: colors.textInverse,
    fontSize: 11,
    fontWeight: '800',
  },
  favoriteBtnFloating: {
    position: 'absolute',
    top: 10,
    right: 10,
    width: 32,
    height: 32,
    borderRadius: 16,
    backgroundColor: 'rgba(12,20,17,0.5)',
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 0.5,
    borderColor: 'rgba(255,255,255,0.15)',
  },
  featuredCardBody: {
    padding: 14,
    gap: 6,
  },
  featuredShopName: {
    fontSize: 16,
    fontWeight: '800',
    color: colors.text,
  },
  infoRowInline: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 5,
  },
  addressText: {
    flex: 1,
    color: colors.textMuted,
    fontWeight: '500',
    fontSize: 13,
  },
  cardFooterRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginTop: 4,
    borderTopWidth: 1,
    borderTopColor: 'rgba(15,118,110,0.05)',
    paddingTop: 8,
  },
  featuredStatsText: {
    color: colors.textSubtle,
    fontSize: 12,
    fontWeight: '600',
  },
  goBtn: {
    width: 22,
    height: 22,
    borderRadius: 11,
    backgroundColor: colors.primary,
    alignItems: 'center',
    justifyContent: 'center',
  },
  allSpacesSection: {
    marginTop: 4,
  },
  allSpacesList: {
    gap: 12,
  },
  shopCard: {
    flexDirection: 'row',
    alignItems: 'center',
    borderRadius: radius.lg,
    backgroundColor: colors.surface,
    borderWidth: 1,
    borderColor: 'rgba(15,118,110,0.06)',
    padding: 10,
    gap: 12,
    shadowColor: '#102018',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.03,
    shadowRadius: 8,
    elevation: 2,
  },
  shopImageWrapper: {
    position: 'relative',
    width: 82,
    height: 82,
    borderRadius: radius.md,
    overflow: 'hidden',
  },
  shopImage: {
    width: '100%',
    height: '100%',
  },
  shopImageFallback: {
    width: '100%',
    height: '100%',
    backgroundColor: colors.primarySoft,
    alignItems: 'center',
    justifyContent: 'center',
  },
  favoriteBtnListFloating: {
    position: 'absolute',
    top: 4,
    right: 4,
    width: 24,
    height: 24,
    borderRadius: 12,
    backgroundColor: 'rgba(12,20,17,0.5)',
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 0.5,
    borderColor: 'rgba(255,255,255,0.15)',
  },
  shopBody: {
    flex: 1,
    gap: 4,
  },
  shopNameRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    gap: 8,
  },
  shopName: {
    flex: 1,
    fontSize: 16,
    fontWeight: '800',
    color: colors.text,
  },
  ratingBadgeSmall: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.accentSoft,
    borderRadius: radius.pill,
    paddingHorizontal: 7,
    paddingVertical: 2,
    gap: 3,
  },
  ratingTextSmall: {
    color: '#7a4310',
    fontSize: 10,
    fontWeight: '800',
  },
  shopStatsRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
    marginTop: 2,
  },
  statTag: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 3,
    backgroundColor: 'rgba(15,118,110,0.05)',
    borderRadius: radius.xs,
    paddingHorizontal: 6,
    paddingVertical: 2,
  },
  statTagText: {
    color: colors.primary,
    fontSize: 10,
    fontWeight: '700',
  },
  chevronIconContainer: {
    width: 26,
    height: 26,
    borderRadius: 13,
    backgroundColor: 'rgba(15,118,110,0.05)',
    alignItems: 'center',
    justifyContent: 'center',
  },
  emptyState: {
    alignItems: 'center',
    paddingVertical: 60,
    paddingHorizontal: 20,
    gap: 14,
  },
  emptyTitle: {
    color: colors.text,
    fontSize: 17,
    fontWeight: '800',
    textAlign: 'center',
  },
  emptyText: {
    color: colors.textMuted,
    textAlign: 'center',
    fontWeight: '500',
    fontSize: 14,
    marginBottom: 6,
  },
  loadingSpinner: {
    marginBottom: 8,
  },
});
