import { Link, useLocalSearchParams } from 'expo-router';
import { useEffect, useMemo, useState } from 'react';
import { Image, SafeAreaView, ScrollView, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native';
import { CustomerBottomNav } from '../components/customer-bottom-nav';
import { CustomerPageHeader } from '../components/customer-page-header';
import { formatCurrency, useCustomerOrder } from '../src/store/order';
import { getCustomerTheme, useCustomerTheme } from '../src/store/theme';

export default function CustomerSearchScreen() {
  const params = useLocalSearchParams<{ category?: string; q?: string }>();
  const initialCategory = typeof params.category === 'string' ? params.category : '';
  const initialQuery = typeof params.q === 'string' ? params.q : '';
  const { stores, loading, error, clearError, loadStores } = useCustomerOrder();
  const { mode } = useCustomerTheme();
  const theme = getCustomerTheme(mode);
  const [query, setQuery] = useState(initialQuery);
  const [selectedCategory, setSelectedCategory] = useState(initialCategory);

  useEffect(() => {
    setSelectedCategory(initialCategory);
    setQuery(initialQuery);
  }, [initialCategory, initialQuery]);

  useEffect(() => {
    const timeout = setTimeout(() => {
      void loadStores({ search: query, category: selectedCategory });
    }, 180);

    return () => clearTimeout(timeout);
  }, [loadStores, query, selectedCategory]);

  const categories = useMemo(
    () =>
      Array.from(new Set(stores.flatMap((store) => store.categories ?? []).filter((entry) => entry && entry.trim().length > 0))),
    [stores],
  );

  return (
    <SafeAreaView style={[styles.safeArea, { backgroundColor: theme.background }]}>
      <View style={[styles.screen, { backgroundColor: theme.background }]}>
        <ScrollView contentContainerStyle={styles.content}>
          <CustomerPageHeader title="Buscar lojas" subtitle="Filtre por prato, loja ou categoria real do catalogo." backHref="/" backLabel="Inicio" />

          <TextInput
            value={query}
            onChangeText={setQuery}
            placeholder="Buscar prato, loja ou categoria"
            placeholderTextColor={theme.textSoft}
            style={[styles.searchInput, { backgroundColor: theme.surface, borderColor: theme.cardBorder, color: theme.text }]}
          />

          {categories.length ? (
            <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={styles.categoryRow}>
              <TouchableOpacity
                onPress={() => setSelectedCategory('')}
                style={[styles.categoryChip, { backgroundColor: selectedCategory ? theme.surface : theme.accent }]}
              >
                <Text style={[styles.categoryChipText, { color: selectedCategory ? theme.text : theme.accentText }]}>Todas</Text>
              </TouchableOpacity>
              {categories.map((category) => {
                const active = selectedCategory === category;
                return (
                  <TouchableOpacity
                    key={category}
                    onPress={() => setSelectedCategory(category)}
                    style={[styles.categoryChip, { backgroundColor: active ? theme.accent : theme.surface }]}
                  >
                    <Text style={[styles.categoryChipText, { color: active ? theme.accentText : theme.text }]}>{category}</Text>
                  </TouchableOpacity>
                );
              })}
            </ScrollView>
          ) : null}

          {loading ? <Text style={[styles.infoText, { color: theme.textMuted }]}>Carregando lojas...</Text> : null}
          {error ? <Text style={[styles.errorText, { color: '#B91C1C' }]} onPress={clearError}>{error}</Text> : null}

          {stores.map((store) => {
            const featuredProduct = store.featuredProducts?.[0];
            return (
            <Link
              key={store.id}
              href={`/restaurant?slug=${store.slug}` as never}
              style={[styles.card, { backgroundColor: theme.surface, borderColor: theme.cardBorder }]}
            >
              <View style={styles.cardBody}>
                <View style={styles.cardText}>
                  <Text style={[styles.cardTitle, { color: theme.text }]}>{featuredProduct?.name ?? store.name}</Text>
                  <Text style={[styles.cardDescription, { color: theme.textMuted }]}>
                    {featuredProduct?.description ?? store.description ?? 'Cardapio pronto para pedido.'}
                  </Text>
                  <View style={styles.cardStoreSignature}>
                    {store.logoUrl ? <Image source={{ uri: store.logoUrl }} style={styles.cardLogoInline} resizeMode="cover" /> : null}
                    <Text numberOfLines={1} style={[styles.cardStore, { color: theme.textSoft }]}>
                      {store.name}
                    </Text>
                  </View>
                  <Text style={[styles.cardStoreMeta, { color: theme.textSoft }]}>
                    {[store.street, store.number].filter(Boolean).join(', ') || store.city} • {formatCurrency(store.baseDeliveryFee)}
                  </Text>
                </View>
                <View style={styles.cardMedia}>
                  {featuredProduct?.imageUrl ? (
                    <Image source={{ uri: featuredProduct.imageUrl }} style={styles.cardImage} resizeMode="cover" />
                  ) : store.coverImageUrl ? (
                    <Image source={{ uri: store.coverImageUrl }} style={styles.cardImage} resizeMode="cover" />
                  ) : null}
                </View>
              </View>
            </Link>
          )})}
        </ScrollView>
        <CustomerBottomNav />
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeArea: { flex: 1 },
  screen: { flex: 1 },
  content: { padding: 20, gap: 14, paddingBottom: 24 },
  searchInput: { borderRadius: 18, borderWidth: 1, paddingHorizontal: 16, paddingVertical: 14, fontSize: 15, fontWeight: '700' },
  categoryRow: { gap: 8, paddingRight: 12 },
  categoryChip: { borderRadius: 999, paddingHorizontal: 14, paddingVertical: 10 },
  categoryChipText: { fontSize: 12, fontWeight: '800' },
  infoText: { fontSize: 14 },
  errorText: { fontSize: 14, fontWeight: '700' },
  card: { borderRadius: 22, padding: 12, borderWidth: 1 },
  cardBody: { flexDirection: 'row', gap: 12 },
  cardText: { flex: 1, justifyContent: 'space-between' },
  cardTitle: { fontSize: 18, lineHeight: 22, fontWeight: '900' },
  cardDescription: { marginTop: 6, fontSize: 13, lineHeight: 18, fontWeight: '600' },
  cardStoreSignature: { marginTop: 8, flexDirection: 'row', alignItems: 'center', gap: 8, minHeight: 22 },
  cardStore: { flexShrink: 1, fontSize: 12, fontWeight: '700' },
  cardStoreMeta: { marginTop: 4, fontSize: 12, fontWeight: '700' },
  cardMedia: { width: 96, alignItems: 'center', justifyContent: 'center' },
  cardImage: { width: 96, height: 96, borderRadius: 18, backgroundColor: '#111827' },
  cardLogoInline: { width: 22, height: 22, borderRadius: 7 },
});
