import React, { useMemo, useState } from 'react';
import { 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 { ShopCard } from '../components/ShopCard';
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, 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]);

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled" showsVerticalScrollIndicator={false}>
        <View style={styles.hero}>
          <View style={styles.kicker}>
            <Ionicons name="star" size={10} color={colors.primaryDark} />
            <Text style={styles.kickerText}>As Nossas Barbearias</Text>
          </View>
          <Text style={styles.title}>
            Ver <Text style={styles.titleAccent}>Barbearias</Text>
          </Text>
          <Text style={styles.subtitle}>
            Descubra barbearias exclusivas e reserve o seu próximo corte em segundos.
          </Text>
          <Text style={styles.countLabel}>
            <Text style={styles.countValue}>{filtered.length}</Text> Espaços Disponíveis
          </Text>
        </View>

        <Card style={styles.searchCard}>
          <View style={styles.searchRow}>
            <Ionicons name="search-outline" size={20} color={colors.textSubtle} />
            <TextInput
              value={query}
              onChangeText={setQuery}
              placeholder="Pesquisar por nome ou endereço..."
              placeholderTextColor={colors.placeholder}
              style={styles.searchInput}
            />
            {query.length > 0 && (
              <TouchableOpacity onPress={() => setQuery('')}>
                <Ionicons name="close-circle" size={18} color={colors.textMuted} />
              </TouchableOpacity>
            )}
          </View>

          <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>
        </Card>

        {!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>
        ) : (
          <View style={styles.grid}>
            {filtered.map((shop) => (
              <ShopCard
                key={shop.id}
                shop={shop}
                isFavorite={isFavorite(shop.id)}
                onToggleFavorite={() => toggleFavorite(shop.id)}
                onPress={() => navigation.navigate('ShopDetails', { shopId: shop.id })}
              />
            ))}
          </View>
        )}
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  content: {
    padding: 20,
    gap: 20,
    paddingBottom: 40,
  },
  hero: {
    gap: 8,
  },
  kicker: {
    alignSelf: 'flex-start',
    flexDirection: 'row',
    alignItems: 'center',
    gap: 6,
    backgroundColor: colors.primarySoft,
    paddingHorizontal: 12,
    paddingVertical: 5,
    borderRadius: radius.pill,
  },
  kickerText: {
    color: colors.primaryDark,
    fontSize: 10,
    fontWeight: '900',
    textTransform: 'uppercase',
    letterSpacing: 1.2,
  },
  title: {
    color: colors.text,
    fontSize: 32,
    fontWeight: '900',
    letterSpacing: -0.8,
    textTransform: 'uppercase',
  },
  titleAccent: {
    color: colors.primary,
  },
  subtitle: {
    color: colors.textMuted,
    fontSize: 14,
    fontWeight: '500',
    lineHeight: 20,
    maxWidth: 340,
  },
  countLabel: {
    marginTop: 4,
    color: colors.textSubtle,
    fontSize: 12,
    fontWeight: '800',
    textTransform: 'uppercase',
    letterSpacing: 0.8,
  },
  countValue: {
    color: colors.text,
  },
  searchCard: {
    padding: 8,
    borderRadius: radius.xl,
    borderWidth: 0,
    ...shadows.card,
  },
  searchRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 10,
    paddingHorizontal: 12,
    paddingVertical: 4,
  },
  searchInput: {
    flex: 1,
    height: 48,
    color: colors.text,
    fontSize: 16,
    fontWeight: '500',
  },
  filtersScroll: {
    gap: 8,
    paddingHorizontal: 8,
    paddingBottom: 8,
    paddingTop: 4,
  },
  filterChip: {
    borderRadius: radius.pill,
    backgroundColor: colors.backgroundAlt,
    paddingHorizontal: 14,
    paddingVertical: 9,
    borderWidth: 1,
    borderColor: colors.border,
  },
  filterChipActive: {
    backgroundColor: colors.surfaceDark,
    borderColor: colors.surfaceDark,
  },
  filterChipText: {
    color: colors.textMuted,
    fontSize: 12,
    fontWeight: '700',
  },
  filterChipTextActive: {
    color: colors.brandAccent,
  },
  grid: {
    gap: 16,
  },
  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,
  },
});
