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';

export default function Explore() {
  const navigation = useNavigation<NativeStackNavigationProp<RootStackParamList>>();
  const { shops, shopsReady, user } = 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);
      })
      .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]);

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled">
        {/* Header */}
        <View style={styles.header}>
          <View>
            <Text style={styles.greeting}>
              {user ? `Olá, ${user.name.split(' ')[0]}` : 'Descobre'}
            </Text>
            <Text style={styles.headline}>Barbearias</Text>
          </View>
          <View style={styles.brandPill}>
            <Text style={styles.brandText}>SA</Text>
          </View>
        </View>

        {/* Search */}
        <View style={styles.searchBox}>
          <Text style={styles.searchIcon}>⌕</Text>
          <TextInput
            value={query}
            onChangeText={setQuery}
            placeholder="Pesquisar nome ou endereço..."
            placeholderTextColor="#475569"
            style={styles.searchInput}
          />
        </View>

        {/* Filters */}
        <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={styles.filters}>
          {[
            ['todas', 'Melhor avaliação'],
            ['top', 'Top avaliadas'],
            ['servicos', 'Mais serviços'],
          ].map(([id, label]) => (
            <TouchableOpacity
              key={id}
              onPress={() => setFilter(id as typeof filter)}
              style={[styles.chip, filter === id && styles.chipActive]}
            >
              <Text style={[styles.chipText, filter === id && styles.chipTextActive]}>{label}</Text>
            </TouchableOpacity>
          ))}
        </ScrollView>

        {/* Results */}
        {!shopsReady ? (
          <View style={styles.emptyState}>
            <Text style={styles.emptyIcon}>⏳</Text>
            <Text style={styles.emptyTitle}>A carregar espaços...</Text>
          </View>
        ) : filtered.length === 0 ? (
          <View style={styles.emptyState}>
            <Text style={styles.emptyIcon}>🔍</Text>
            <Text style={styles.emptyTitle}>Nenhuma barbearia encontrada</Text>
            <Text style={styles.emptyText}>Tente ajustar a pesquisa ou filtros.</Text>
            <Button variant="outline" onPress={() => { setQuery(''); setFilter('todas'); }}>
              Limpar Tudo
            </Button>
          </View>
        ) : (
          <View style={styles.list}>
            <Text style={styles.count}>{filtered.length} espaços disponíveis</Text>
            {filtered.map((shop) => (
              <TouchableOpacity
                key={shop.id}
                style={styles.shopCard}
                activeOpacity={0.85}
                onPress={() => navigation.navigate('ShopDetails', { shopId: shop.id })}
              >
                {shop.imageUrl ? (
                  <Image source={{ uri: shop.imageUrl }} style={styles.shopImage} />
                ) : (
                  <View style={styles.shopImageFallback}>
                    <Text style={styles.shopFallbackText}>{shop.name.charAt(0)}</Text>
                  </View>
                )}
                <View style={styles.shopOverlay} />
                <View style={styles.shopBody}>
                  <View style={styles.shopRow}>
                    <Text style={styles.shopName} numberOfLines={1}>{shop.name}</Text>
                    <View style={styles.ratingPill}>
                      <Text style={styles.ratingText}>★ {(shop.rating || 0).toFixed(1)}</Text>
                    </View>
                  </View>
                  <Text style={styles.address} numberOfLines={1}>{shop.address || 'Endereço indisponível'}</Text>
                  <View style={styles.metaRow}>
                    <View style={styles.metaPill}>
                      <Text style={styles.metaText}>{(shop.services || []).length} serviços</Text>
                    </View>
                    <View style={styles.metaPill}>
                      <Text style={styles.metaText}>{(shop.barbers || []).length} barbeiros</Text>
                    </View>
                  </View>
                </View>
              </TouchableOpacity>
            ))}
          </View>
        )}
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#0a0a0f',
  },
  content: {
    padding: 20,
    gap: 20,
    paddingBottom: 32,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
  },
  greeting: {
    color: '#64748b',
    fontSize: 15,
    fontWeight: '600',
    marginBottom: 2,
  },
  headline: {
    color: '#f8fafc',
    fontSize: 32,
    fontWeight: '900',
  },
  brandPill: {
    width: 44,
    height: 44,
    borderRadius: 14,
    backgroundColor: '#141420',
    borderWidth: 1,
    borderColor: 'rgba(99,102,241,0.25)',
    alignItems: 'center',
    justifyContent: 'center',
  },
  brandText: {
    color: '#818cf8',
    fontSize: 14,
    fontWeight: '900',
  },
  searchBox: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#141420',
    borderRadius: 16,
    borderWidth: 1,
    borderColor: 'rgba(255,255,255,0.06)',
    paddingHorizontal: 16,
    gap: 10,
  },
  searchIcon: {
    color: '#475569',
    fontSize: 20,
  },
  searchInput: {
    flex: 1,
    height: 52,
    color: '#f8fafc',
    fontSize: 15,
    fontWeight: '500',
  },
  filters: {
    gap: 8,
  },
  chip: {
    borderRadius: 12,
    backgroundColor: '#141420',
    paddingHorizontal: 16,
    paddingVertical: 10,
    borderWidth: 1,
    borderColor: 'rgba(255,255,255,0.04)',
  },
  chipActive: {
    backgroundColor: '#6366f1',
    borderColor: '#6366f1',
  },
  chipText: {
    color: '#94a3b8',
    fontSize: 13,
    fontWeight: '700',
  },
  chipTextActive: {
    color: '#fff',
  },
  list: {
    gap: 16,
  },
  count: {
    color: '#475569',
    fontSize: 12,
    fontWeight: '700',
    textTransform: 'uppercase',
    letterSpacing: 0.5,
  },
  shopCard: {
    borderRadius: 22,
    overflow: 'hidden',
    backgroundColor: '#141420',
    borderWidth: 1,
    borderColor: 'rgba(255,255,255,0.04)',
  },
  shopImage: {
    width: '100%',
    height: 160,
  },
  shopImageFallback: {
    width: '100%',
    height: 160,
    backgroundColor: '#1c1c2e',
    alignItems: 'center',
    justifyContent: 'center',
  },
  shopFallbackText: {
    color: '#6366f1',
    fontSize: 42,
    fontWeight: '900',
    opacity: 0.5,
  },
  shopOverlay: {},
  shopBody: {
    padding: 18,
    gap: 10,
  },
  shopRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    gap: 10,
  },
  shopName: {
    flex: 1,
    fontSize: 18,
    fontWeight: '800',
    color: '#f8fafc',
  },
  ratingPill: {
    backgroundColor: 'rgba(99,102,241,0.15)',
    borderRadius: 10,
    paddingHorizontal: 10,
    paddingVertical: 5,
  },
  ratingText: {
    color: '#a5b4fc',
    fontSize: 12,
    fontWeight: '800',
  },
  address: {
    color: '#64748b',
    fontWeight: '500',
    fontSize: 14,
  },
  metaRow: {
    flexDirection: 'row',
    gap: 8,
  },
  metaPill: {
    backgroundColor: 'rgba(255,255,255,0.04)',
    borderRadius: 8,
    paddingHorizontal: 10,
    paddingVertical: 5,
  },
  metaText: {
    color: '#475569',
    fontSize: 11,
    fontWeight: '700',
    textTransform: 'uppercase',
  },
  emptyState: {
    alignItems: 'center',
    padding: 40,
    gap: 12,
  },
  emptyIcon: {
    fontSize: 48,
    marginBottom: 8,
  },
  emptyTitle: {
    color: '#f8fafc',
    fontSize: 18,
    fontWeight: '800',
    textAlign: 'center',
  },
  emptyText: {
    color: '#64748b',
    textAlign: 'center',
    fontWeight: '500',
  },
});
