import React, { useEffect, useState, useRef } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  TextInput,
  FlatList,
  ActivityIndicator,
  Platform,
  StatusBar,
} from 'react-native';
import { useLocalSearchParams, useRouter, Stack } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import { Image as ExpoImage } from 'expo-image';
import { LinearGradient } from 'expo-linear-gradient';
import Animated, { FadeInDown, FadeIn } from 'react-native-reanimated';
import api from '../../../services/api';
import { Colors } from '../../../constants/theme';
import { Category, Service } from '../../../types';

export default function ServicesStore() {
  const router = useRouter();
  const params = useLocalSearchParams();
  const searchInputRef = useRef<TextInput>(null);

  const [query, setQuery] = useState('');
  const [activeCategory, setActiveCategory] = useState<number | null>(null);
  const [categories, setCategories] = useState<Category[]>([]);
  const [services, setServices] = useState<Service[]>([]);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [loading, setLoading] = useState(true);
  const [loadingMore, setLoadingMore] = useState(false);
  const [searching, setSearching] = useState(false);

  // Auto-focus search if navigated from search icon
  useEffect(() => {
    if (params.focus === 'search') {
      setTimeout(() => searchInputRef.current?.focus(), 400);
    }
  }, [params.focus]);

  // Fetch categories for filter chips
  useEffect(() => {
    api.get('/categories?is_mobile=yes').then(res => {
      setCategories(res.data?.data || []);
    }).catch(() => {});
  }, []);

  // Re-fetch services when query or category changes
  useEffect(() => {
    setPage(1);
    setServices([]);
    setHasMore(true);
    fetchServices(1, query, activeCategory, true);
  }, [query, activeCategory]);

  const fetchServices = async (
    pageNum: number,
    keyword: string,
    categoryId: number | null,
    reset = false,
  ) => {
    if (reset) setSearching(true); else setLoadingMore(true);
    try {
      const params: any = { is_mobile: 'yes', page: pageNum };
      if (keyword.trim()) params.keywords = keyword.trim();
      if (categoryId) params.category_id = categoryId;

      const res = await api.get('/services', { params });
      const raw = res.data?.data;
      const items: Service[] = Array.isArray(raw) ? raw : (raw?.data || []);
      const total = raw?.last_page ?? 1;

      setServices(prev => (reset ? items : [...prev, ...items]));
      setHasMore(pageNum < total);
    } catch {
      setHasMore(false);
    } finally {
      setSearching(false);
      setLoadingMore(false);
      setLoading(false);
    }
  };

  const loadMore = () => {
    if (!hasMore || loadingMore) return;
    const next = page + 1;
    setPage(next);
    fetchServices(next, query, activeCategory);
  };

  const renderService = ({ item, index }: { item: Service; index: number }) => (
    <Animated.View entering={FadeInDown.duration(400).delay(index * 50)} style={styles.cardWrapper}>
      <TouchableOpacity style={styles.card} onPress={() => router.push(`/(public)/service/${item.slug}` as any)} activeOpacity={0.85}>
        <View style={styles.cardImageContainer}>
          <ExpoImage
            source={{ uri: item.image_url || item.image }}
            style={StyleSheet.absoluteFill}
            contentFit="cover"
          />
          <LinearGradient
            colors={['transparent', 'rgba(0,0,0,0.4)']}
            style={styles.cardImageGradient}
          />
        </View>
        <View style={styles.cardBody}>
          <Text style={styles.cardName} numberOfLines={1}>{item.source_name}</Text>
          <Text style={styles.cardPrice}>
            {item.price
              ? Number(item.price).toLocaleString('pt-PT') + ' Kz'
              : '--'}
          </Text>
          <View style={styles.cardRatingRow}>
            <Ionicons name="star" size={12} color="#FFD700" />
            <Text style={styles.cardRating}>{item.rating ?? '5.0'}</Text>
          </View>
        </View>
      </TouchableOpacity>
    </Animated.View>
  );

  const renderCategoryChip = (cat: Category) => {
    const active = activeCategory === cat.id;
    return (
      <TouchableOpacity
        key={cat.id}
        style={[styles.chip, active && styles.chipActive]}
        onPress={() => setActiveCategory(active ? null : cat.id)}
      >
        <Text style={[styles.chipText, active && styles.chipTextActive]}>{cat.name}</Text>
      </TouchableOpacity>
    );
  };

  const renderHeader = () => (
    <>
      {/* Search Bar */}
      <Animated.View entering={FadeIn.duration(400)} style={styles.searchContainer}>
        <Ionicons name="search-outline" size={20} color={Colors.light.textMuted} style={styles.searchIcon} />
        <TextInput
          ref={searchInputRef}
          style={styles.searchInput}
          placeholder="Procurar serviços..."
          placeholderTextColor={Colors.light.textMuted}
          value={query}
          onChangeText={setQuery}
          returnKeyType="search"
          clearButtonMode="while-editing"
        />
        {query.length > 0 && (
          <TouchableOpacity onPress={() => setQuery('')} style={styles.clearBtn}>
            <Ionicons name="close-circle" size={18} color={Colors.light.textMuted} />
          </TouchableOpacity>
        )}
      </Animated.View>

      {/* Category Chips */}
      {categories.length > 0 && (
        <Animated.ScrollView
          entering={FadeIn.duration(500).delay(100)}
          horizontal
          showsHorizontalScrollIndicator={false}
          contentContainerStyle={styles.chipList}
        >
          {categories.map(renderCategoryChip)}
        </Animated.ScrollView>
      )}

      {/* Results count */}
      <View style={styles.resultsHeader}>
        <Text style={styles.resultsText}>
          {searching ? 'A pesquisar...' : `${services.length} resultado${services.length !== 1 ? 's' : ''}`}
        </Text>
      </View>
    </>
  );

  return (
    <View style={styles.container}>
      <Stack.Screen options={{ headerShown: false }} />

      {/* Premium Gradient Header */}
      <Animated.View entering={FadeIn.duration(500)} style={styles.header}>
        <LinearGradient
          colors={[Colors.light.primary, '#005CEE']}
          style={StyleSheet.absoluteFill}
          start={{ x: 0, y: 0 }}
          end={{ x: 1, y: 1 }}
        />
        <View style={styles.headerTop}>
          <TouchableOpacity onPress={() => router.back()} style={styles.backBtn}>
            <Ionicons name="arrow-back" size={24} color="#FFF" />
          </TouchableOpacity>
        </View>
        <View style={styles.headerContent}>
          <Text style={styles.headerTitle}>Todos os Serviços</Text>
          <Text style={styles.headerDesc}>Encontre os melhores serviços</Text>
        </View>
      </Animated.View>

      {searching && services.length === 0 ? (
        <ActivityIndicator size="large" color={Colors.light.primary} style={{ marginTop: 60 }} />
      ) : (
        <FlatList
          data={services}
          keyExtractor={(item) => item.id.toString()}
          numColumns={2}
          renderItem={renderService}
          ListHeaderComponent={renderHeader}
          contentContainerStyle={styles.listContent}
          showsVerticalScrollIndicator={false}
          onEndReached={loadMore}
          onEndReachedThreshold={0.5}
          ListFooterComponent={
            loadingMore ? (
              <ActivityIndicator color={Colors.light.primary} style={{ margin: 20 }} />
            ) : null
          }
          ListEmptyComponent={
            !loading && !searching ? (
              <Animated.View entering={FadeIn} style={styles.emptyState}>
                <Ionicons name="search-outline" size={64} color={Colors.light.border} />
                <Text style={styles.emptyTitle}>Sem resultados</Text>
                <Text style={styles.emptyText}>Tenta outro termo ou categoria.</Text>
              </Animated.View>
            ) : null
          }
        />
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: '#F8F9FC' },
  header: {
    paddingTop: Platform.OS === 'ios' ? 60 : (StatusBar.currentHeight || 20) + 20,
    paddingBottom: 30,
    borderBottomLeftRadius: 30,
    borderBottomRightRadius: 30,
    overflow: 'hidden',
  },
  headerTop: {
    paddingHorizontal: 20,
    flexDirection: 'row',
    alignItems: 'center',
  },
  backBtn: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: 'rgba(255,255,255,0.2)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  headerContent: {
    paddingHorizontal: 24,
    marginTop: 20,
  },
  headerTitle: {
    fontSize: 28,
    fontWeight: '800',
    color: '#FFF',
    letterSpacing: -0.5,
  },
  headerDesc: {
    fontSize: 14,
    color: 'rgba(255,255,255,0.8)',
    marginTop: 4,
    fontWeight: '500',
  },
  searchContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#FFF',
    marginHorizontal: 15,
    marginTop: 16,
    marginBottom: 10,
    borderRadius: 14,
    paddingHorizontal: 14,
    height: 48,
    borderWidth: 1,
    borderColor: Colors.light.border,
  },
  searchIcon: { marginRight: 8 },
  searchInput: {
    flex: 1,
    fontSize: 15,
    color: Colors.light.text,
  },
  clearBtn: { padding: 4 },
  chipList: {
    paddingHorizontal: 15,
    paddingBottom: 6,
  },
  chip: {
    paddingHorizontal: 16,
    paddingVertical: 7,
    borderRadius: 20,
    backgroundColor: '#FFF',
    marginRight: 8,
    borderWidth: 1.5,
    borderColor: Colors.light.border,
  },
  chipActive: {
    backgroundColor: Colors.light.primary,
    borderColor: Colors.light.primary,
  },
  chipText: {
    fontSize: 13,
    color: Colors.light.textMuted,
    fontWeight: '600',
  },
  chipTextActive: { color: '#FFF' },
  resultsHeader: {
    paddingHorizontal: 16,
    paddingVertical: 8,
  },
  resultsText: {
    fontSize: 13,
    color: Colors.light.textMuted,
    fontWeight: '500',
  },
  listContent: { paddingBottom: 120, paddingHorizontal: 10 },
  cardWrapper: {
    flex: 1,
    padding: 5,
    maxWidth: '50%',
  },
  card: {
    backgroundColor: '#FFF',
    borderRadius: 14,
    borderWidth: StyleSheet.hairlineWidth,
    borderColor: Colors.light.primary,
  },
  cardImageContainer: {
    height: 130,
    backgroundColor: Colors.light.surface,
    borderTopLeftRadius: 14,
    borderTopRightRadius: 14,
    overflow: 'hidden',
  },
  cardImageGradient: {
    position: 'absolute',
    left: 0,
    right: 0,
    bottom: 0,
    height: '50%',
  },
  cardBody: { padding: 10 },
  cardName: {
    fontSize: 13,
    fontWeight: '700',
    color: Colors.light.text,
    marginBottom: 4,
  },
  cardPrice: {
    fontSize: 13,
    color: Colors.light.primary,
    fontWeight: '700',
    marginBottom: 6,
  },
  cardRatingRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 3,
  },
  cardRating: {
    fontSize: 11,
    color: Colors.light.textMuted,
    fontWeight: '600',
  },
  emptyState: {
    alignItems: 'center',
    paddingTop: 60,
    paddingHorizontal: 40,
  },
  emptyTitle: {
    fontSize: 18,
    fontWeight: '700',
    color: Colors.light.text,
    marginTop: 16,
    marginBottom: 8,
  },
  emptyText: {
    fontSize: 14,
    color: Colors.light.textMuted,
    textAlign: 'center',
  },
});
