import React, { useState, useRef } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TextInput,
  TouchableOpacity,
  RefreshControl,
  Animated,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useQuery } from '@tanstack/react-query';
import { NativeStackScreenProps } from '@react-navigation/native-stack';
import { MarketplaceStackParamList } from '../../navigation/types';
import { COLORS, FONT_SIZE, SPACING, RADIUS, TEXT, SHADOWS } from '../../theme';
import { useTheme } from '../../theme';
import { Spinner, EmptyState } from '../../components/ui';
import { marketplaceAPI } from '../../services/api';
import { MarketplaceChatbot } from '../../types';

type Props = NativeStackScreenProps<MarketplaceStackParamList, 'MarketplaceList'>;

export function MarketplaceScreen({ navigation }: Props) {
  const { theme, isDark } = useTheme();
  const [search, setSearch] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');
  const searchTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

  const handleSearchChange = (text: string) => {
    setSearch(text);
    if (searchTimer.current) clearTimeout(searchTimer.current);
    searchTimer.current = setTimeout(() => setDebouncedSearch(text), 400);
  };

  const { data, isLoading, refetch } = useQuery({
    queryKey: ['marketplace', debouncedSearch],
    queryFn: () => marketplaceAPI.list({ search: debouncedSearch || undefined, limit: 20 }),
  });

  const chatbots: MarketplaceChatbot[] = data?.chatbots ?? data?.items ?? data ?? [];

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.bg }]} edges={['top', 'bottom']}>
      {/* Header */}
      <View style={styles.header}>
        <Text style={[styles.headerTitle, { color: theme.text }]}>Explore</Text>
        <Text style={[styles.headerSub, { color: theme.textSecondary }]}>
          Discover AI chatbots built by the community
        </Text>
      </View>

      {/* Search */}
      <View style={[styles.searchContainer, { backgroundColor: theme.inputBg, borderColor: theme.border }]}>
        <Text style={styles.searchIcon}>🔍</Text>
        <TextInput
          style={[styles.searchInput, { color: theme.text }]}
          value={search}
          onChangeText={handleSearchChange}
          placeholder="Search chatbots..."
          placeholderTextColor={theme.placeholder}
          autoCorrect={false}
        />
        {search.length > 0 && (
          <TouchableOpacity onPress={() => { setSearch(''); setDebouncedSearch(''); }}>
            <View style={[styles.clearBtn, { backgroundColor: theme.bgSecondary }]}>
              <Text style={{ fontSize: 10, color: theme.textMuted }}>✕</Text>
            </View>
          </TouchableOpacity>
        )}
      </View>

      {isLoading ? (
        <Spinner centered label="Loading marketplace..." />
      ) : (
        <FlatList
          data={chatbots}
          keyExtractor={item => item.id}
          renderItem={({ item }) => (
            <BotCard item={item} onPress={() => navigation.navigate('MarketplaceDetail', { chatbotId: item.id })} />
          )}
          contentContainerStyle={styles.list}
          showsVerticalScrollIndicator={false}
          refreshControl={
            <RefreshControl refreshing={isLoading} onRefresh={refetch} tintColor={COLORS.primary} />
          }
          ListEmptyComponent={
            <EmptyState
              icon={<Text style={{ fontSize: 52 }}>🧭</Text>}
              title={debouncedSearch ? 'No results found' : 'Marketplace is empty'}
              description={debouncedSearch ? 'Try a different search term.' : 'No chatbots published yet.'}
            />
          }
        />
      )}
    </SafeAreaView>
  );
}

function BotCard({ item, onPress }: { item: MarketplaceChatbot; onPress: () => void }) {
  const { theme } = useTheme();
  const scale = useRef(new Animated.Value(1)).current;
  const accentColor = item.primary_color || COLORS.primary;

  const onPressIn = () => Animated.spring(scale, { toValue: 0.97, useNativeDriver: true, speed: 60 }).start();
  const onPressOut = () => Animated.spring(scale, { toValue: 1, useNativeDriver: true, speed: 30, bounciness: 4 }).start();

  return (
    <TouchableOpacity
      onPress={onPress}
      onPressIn={onPressIn}
      onPressOut={onPressOut}
      activeOpacity={1}>
      <Animated.View
        style={[
          styles.card,
          { backgroundColor: theme.surface, borderColor: theme.border, transform: [{ scale }] },
          SHADOWS.sm,
        ]}>
        {/* Top */}
        <View style={styles.cardTop}>
          <View style={[styles.botAvatar, { backgroundColor: accentColor }]}>
            <Text style={styles.botAvatarText}>{item.name[0]?.toUpperCase()}</Text>
          </View>
          <View style={styles.botMeta}>
            <Text style={[styles.botName, { color: theme.text }]} numberOfLines={1}>{item.name}</Text>
            {item.company_name ? (
              <Text style={[styles.companyName, { color: theme.textMuted }]}>by {item.company_name}</Text>
            ) : null}
          </View>
          <View style={styles.ratingPill}>
            <Text style={styles.ratingStar}>★</Text>
            <Text style={styles.ratingText}>{item.average_rating?.toFixed(1) ?? '–'}</Text>
          </View>
        </View>

        {/* Description */}
        {item.description ? (
          <Text style={[styles.desc, { color: theme.textSecondary }]} numberOfLines={2}>
            {item.description}
          </Text>
        ) : null}

        {/* Footer chips */}
        <View style={styles.chips}>
          {item.category ? (
            <View style={[styles.chip, { backgroundColor: COLORS.primaryUltraLight }]}>
              <Text style={[styles.chipText, { color: COLORS.primaryDark }]}>{item.category}</Text>
            </View>
          ) : null}
          {(item.conversation_count ?? 0) > 0 ? (
            <View style={[styles.chip, { backgroundColor: theme.bgSecondary }]}>
              <Text style={[styles.chipText, { color: theme.textSecondary }]}>
                💬 {item.conversation_count?.toLocaleString()} chats
              </Text>
            </View>
          ) : null}
          {(item.languages ?? []).length > 0 ? (
            <View style={[styles.chip, { backgroundColor: theme.bgSecondary }]}>
              <Text style={[styles.chipText, { color: theme.textSecondary }]}>
                🌐 {item.languages.slice(0, 2).join(', ')}
              </Text>
            </View>
          ) : null}
        </View>
      </Animated.View>
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1 },

  header: { paddingHorizontal: SPACING.lg, paddingTop: SPACING.md, paddingBottom: SPACING.sm },
  headerTitle: { ...TEXT.h2 },
  headerSub: { ...TEXT.small, marginTop: 4 },

  searchContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginHorizontal: SPACING.lg,
    marginBottom: SPACING.sm,
    borderRadius: RADIUS.full,
    borderWidth: 1.5,
    paddingHorizontal: SPACING.md,
    paddingVertical: SPACING.xs,
    gap: SPACING.sm,
  },
  searchIcon: { fontSize: 15 },
  searchInput: { flex: 1, fontSize: FONT_SIZE.md, paddingVertical: SPACING.xs },
  clearBtn: { width: 22, height: 22, borderRadius: RADIUS.full, alignItems: 'center', justifyContent: 'center' },

  list: { paddingHorizontal: SPACING.lg, paddingTop: SPACING.sm, paddingBottom: SPACING.xxxl, gap: SPACING.md },

  card: {
    borderRadius: RADIUS.xl,
    padding: SPACING.lg,
    borderWidth: 1,
    gap: SPACING.md,
  },
  cardTop: { flexDirection: 'row', alignItems: 'center', gap: SPACING.md },
  botAvatar: { width: 48, height: 48, borderRadius: RADIUS.lg, alignItems: 'center', justifyContent: 'center' },
  botAvatarText: { color: COLORS.white, fontSize: FONT_SIZE.xl, fontWeight: '700' },
  botMeta: { flex: 1 },
  botName: { ...TEXT.h4 },
  companyName: { ...TEXT.caption, marginTop: 2 },

  ratingPill: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#fef9c3',
    borderRadius: RADIUS.full,
    paddingVertical: 4,
    paddingHorizontal: SPACING.sm,
    gap: 3,
  },
  ratingStar: { fontSize: 12, color: '#d97706' },
  ratingText: { fontSize: FONT_SIZE.sm, fontWeight: '700', color: '#92400e' },

  desc: { ...TEXT.small, lineHeight: 20 },

  chips: { flexDirection: 'row', gap: SPACING.sm, flexWrap: 'wrap' },
  chip: { borderRadius: RADIUS.full, paddingVertical: 4, paddingHorizontal: SPACING.sm },
  chipText: { ...TEXT.captionM },
});
