/**
 * Property list — searchable listings with filters.
 * RealScout replacement: browse active listings.
 */

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

export default function PropertyList({ navigation }: any) {
  const { theme } = useTheme();
  const [properties, setProperties] = useState<Property[]>([]);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('active');
  const [refreshing, setRefreshing] = useState(false);
  const [nearbyMode, setNearbyMode] = useState(false);

  const loadProperties = useCallback(async () => {
    if (nearbyMode) {
      const loc = await getCurrentLocation();
      if (loc) {
        const res = await getNearbyProperties(loc.latitude, loc.longitude, 10);
        if (res.success && res.data) setProperties(res.data);
      }
    } else {
      const params: Record<string, string> = {};
      if (statusFilter !== 'all') params.status = statusFilter;
      if (search) params.search = search;
      const res = await getProperties(params);
      if (res.success && res.data) setProperties(res.data);
    }
  }, [search, statusFilter, nearbyMode]);

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

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

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.colors.background }]} edges={['bottom']}>
      <View style={[styles.searchBar, { backgroundColor: theme.colors.surface }]}>
        <TextInput
          style={[styles.searchInput, { color: theme.colors.text, backgroundColor: theme.colors.inputBg }]}
          placeholder="Search address, MLS#, city..."
          placeholderTextColor={theme.colors.textSecondary}
          value={search}
          onChangeText={setSearch}
          onSubmitEditing={loadProperties}
          returnKeyType="search"
        />
        <TouchableOpacity
          style={[styles.nearbyBtn, { backgroundColor: nearbyMode ? theme.colors.success : theme.colors.inputBg }]}
          onPress={() => setNearbyMode(!nearbyMode)}
        >
          <Text style={[styles.nearbyText, { color: nearbyMode ? '#FFF' : theme.colors.textSecondary }]}>
            📍
          </Text>
        </TouchableOpacity>
      </View>

      <View style={styles.filterRow}>
        {['active', 'pending', 'sold', 'all'].map((f) => (
          <TouchableOpacity
            key={f}
            style={[styles.filterChip, {
              backgroundColor: statusFilter === f ? theme.colors.primary : theme.colors.surface,
              borderColor: statusFilter === f ? theme.colors.primary : theme.colors.border,
            }]}
            onPress={() => setStatusFilter(f)}
          >
            <Text style={[styles.filterText, { color: statusFilter === f ? '#FFF' : theme.colors.textSecondary }]}>
              {f.charAt(0).toUpperCase() + f.slice(1)}
            </Text>
          </TouchableOpacity>
        ))}
      </View>

      <FlatList
        data={properties}
        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 }]}>
              {nearbyMode ? 'No nearby listings found' : 'No properties found'}
            </Text>
          </View>
        }
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1 },
  searchBar: { flexDirection: 'row', padding: 12, gap: 8 },
  searchInput: { flex: 1, height: 40, borderRadius: 10, paddingHorizontal: 14, fontSize: 15 },
  nearbyBtn: { width: 40, height: 40, borderRadius: 10, justifyContent: 'center', alignItems: 'center' },
  nearbyText: { fontSize: 18 },
  filterRow: { flexDirection: 'row', paddingHorizontal: 12, paddingBottom: 8, gap: 8 },
  filterChip: { paddingHorizontal: 14, paddingVertical: 6, borderRadius: 20, borderWidth: 1 },
  filterText: { fontSize: 13, fontWeight: '600' },
  empty: { padding: 40, alignItems: 'center' },
  emptyText: { fontSize: 15 },
});
