/**
 * Property match — AI-matched listings for a specific client.
 * RealScout replacement: preference learning, collaborative search.
 */

import React, { useEffect, useState, useCallback } from 'react';
import { View, Text, StyleSheet, FlatList, RefreshControl } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useTheme } from '../../themes/ThemeProvider';
import PropertyCard from '../../components/PropertyCard';
import { getPropertyMatches, Property } from '../../services/api';

export default function PropertyMatch({ route, navigation }: any) {
  const { theme } = useTheme();
  const { clientId } = route.params;
  const [matches, setMatches] = useState<Property[]>([]);
  const [refreshing, setRefreshing] = useState(false);

  const load = useCallback(async () => {
    const res = await getPropertyMatches(clientId);
    if (res.success && res.data) setMatches(res.data);
  }, [clientId]);

  useEffect(() => {
    load();
  }, [load]);

  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    await load();
    setRefreshing(false);
  }, [load]);

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.colors.background }]} edges={['bottom']}>
      <View style={[styles.headerInfo, { backgroundColor: theme.colors.card }]}>
        <Text style={[styles.headerText, { color: theme.colors.text }]}>
          AI-matched properties based on client preferences and search history.
        </Text>
        <Text style={[styles.matchCount, { color: theme.colors.accent }]}>
          {matches.length} match{matches.length !== 1 ? 'es' : ''} found
        </Text>
      </View>

      <FlatList
        data={matches}
        keyExtractor={(item) => String(item.id)}
        renderItem={({ item }) => (
          <PropertyCard
            property={item}
            onPress={() => navigation.navigate('PropertyDetail', { id: item.id })}
          />
        )}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />
        }
        ListEmptyComponent={
          <View style={styles.empty}>
            <Text style={[styles.emptyText, { color: theme.colors.textSecondary }]}>
              No matches yet. The AI learns from saved searches and client interactions.
            </Text>
          </View>
        }
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1 },
  headerInfo: { padding: 16 },
  headerText: { fontSize: 14, lineHeight: 20 },
  matchCount: { fontSize: 15, fontWeight: '700', marginTop: 8 },
  empty: { padding: 40, alignItems: 'center' },
  emptyText: { fontSize: 14, textAlign: 'center', lineHeight: 20 },
});
