import React, { useEffect, useState } from 'react';
import {
  View,
  Text,
  FlatList,
  StyleSheet,
  TouchableOpacity,
  TextInput,
  Modal,
  ScrollView,
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import { Property } from '../types';
import { apiService } from '../services/apiService';
import PropertyCard from '../components/PropertyCard';

interface Filters {
  type?: string;
  propertyType?: string;
  location?: string;
  minPrice?: number;
  maxPrice?: number;
}

export default function PropertyListScreen({ navigation }: any) {
  const [properties, setProperties] = useState<Property[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchText, setSearchText] = useState('');
  const [showFilters, setShowFilters] = useState(false);
  const [filters, setFilters] = useState<Filters>({});

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

  const loadProperties = async () => {
    try {
      setLoading(true);
      const data = await apiService.getProperties({
        ...filters,
        search: searchText,
      });
      setProperties(data);
    } catch (error) {
      console.error('Failed to load properties:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = () => {
    loadProperties();
  };

  const clearFilters = () => {
    setFilters({});
    setSearchText('');
    setShowFilters(false);
  };

  const FilterButton = ({ title, isActive, onPress }: any) => (
    <TouchableOpacity
      style={[styles.filterButton, isActive && styles.activeFilterButton]}
      onPress={onPress}
    >
      <Text style={[styles.filterButtonText, isActive && styles.activeFilterButtonText]}>
        {title}
      </Text>
    </TouchableOpacity>
  );

  const renderProperty = ({ item }: { item: Property }) => (
    <PropertyCard
      property={item}
      onPress={() => navigation.navigate('PropertyDetail', { property: item })}
    />
  );

  const FiltersModal = () => (
    <Modal visible={showFilters} animationType="slide" presentationStyle="pageSheet">
      <View style={styles.modalContainer}>
        <View style={styles.modalHeader}>
          <Text style={styles.modalTitle}>Filters</Text>
          <TouchableOpacity onPress={() => setShowFilters(false)}>
            <Icon name="close" size={24} color="#666" />
          </TouchableOpacity>
        </View>

        <ScrollView style={styles.modalContent}>
          {/* Property Type */}
          <Text style={styles.filterSectionTitle}>Property Type</Text>
          <View style={styles.filterSection}>
            <FilterButton
              title="Buy"
              isActive={filters.type === 'buy'}
              onPress={() => setFilters({ ...filters, type: filters.type === 'buy' ? undefined : 'buy' })}
            />
            <FilterButton
              title="Rent"
              isActive={filters.type === 'rent'}
              onPress={() => setFilters({ ...filters, type: filters.type === 'rent' ? undefined : 'rent' })}
            />
          </View>

          {/* Property Category */}
          <Text style={styles.filterSectionTitle}>Category</Text>
          <View style={styles.filterSection}>
            <FilterButton
              title="House"
              isActive={filters.propertyType === 'house'}
              onPress={() => setFilters({ ...filters, propertyType: filters.propertyType === 'house' ? undefined : 'house' })}
            />
            <FilterButton
              title="Apartment"
              isActive={filters.propertyType === 'apartment'}
              onPress={() => setFilters({ ...filters, propertyType: filters.propertyType === 'apartment' ? undefined : 'apartment' })}
            />
            <FilterButton
              title="Villa"
              isActive={filters.propertyType === 'villa'}
              onPress={() => setFilters({ ...filters, propertyType: filters.propertyType === 'villa' ? undefined : 'villa' })}
            />
            <FilterButton
              title="Land"
              isActive={filters.propertyType === 'land'}
              onPress={() => setFilters({ ...filters, propertyType: filters.propertyType === 'land' ? undefined : 'land' })}
            />
          </View>

          {/* Location */}
          <Text style={styles.filterSectionTitle}>Location</Text>
          <TextInput
            style={styles.locationInput}
            placeholder="Enter location"
            value={filters.location || ''}
            onChangeText={(text) => setFilters({ ...filters, location: text })}
          />

          {/* Price Range */}
          <Text style={styles.filterSectionTitle}>Price Range</Text>
          <View style={styles.priceInputs}>
            <TextInput
              style={styles.priceInput}
              placeholder="Min Price"
              keyboardType="numeric"
              value={filters.minPrice?.toString() || ''}
              onChangeText={(text) => setFilters({ ...filters, minPrice: text ? parseFloat(text) : undefined })}
            />
            <TextInput
              style={styles.priceInput}
              placeholder="Max Price"
              keyboardType="numeric"
              value={filters.maxPrice?.toString() || ''}
              onChangeText={(text) => setFilters({ ...filters, maxPrice: text ? parseFloat(text) : undefined })}
            />
          </View>
        </ScrollView>

        <View style={styles.modalActions}>
          <TouchableOpacity style={styles.clearButton} onPress={clearFilters}>
            <Text style={styles.clearButtonText}>Clear All</Text>
          </TouchableOpacity>
          <TouchableOpacity style={styles.applyButton} onPress={() => setShowFilters(false)}>
            <Text style={styles.applyButtonText}>Apply Filters</Text>
          </TouchableOpacity>
        </View>
      </View>
    </Modal>
  );

  return (
    <View style={styles.container}>
      {/* Search Bar */}
      <View style={styles.searchContainer}>
        <View style={styles.searchBar}>
          <Icon name="search" size={20} color="#666" />
          <TextInput
            style={styles.searchInput}
            placeholder="Search properties..."
            value={searchText}
            onChangeText={setSearchText}
            onSubmitEditing={handleSearch}
          />
        </View>
        <TouchableOpacity style={styles.filterIcon} onPress={() => setShowFilters(true)}>
          <Icon name="options-outline" size={24} color="#0091B9" />
        </TouchableOpacity>
      </View>

      {/* Active Filters */}
      {(filters.type || filters.propertyType || filters.location) && (
        <ScrollView horizontal style={styles.activeFilters} showsHorizontalScrollIndicator={false}>
          {filters.type && (
            <TouchableOpacity
              style={styles.activeFilter}
              onPress={() => setFilters({ ...filters, type: undefined })}
            >
              <Text style={styles.activeFilterText}>{filters.type}</Text>
              <Icon name="close" size={16} color="#0091B9" />
            </TouchableOpacity>
          )}
          {filters.propertyType && (
            <TouchableOpacity
              style={styles.activeFilter}
              onPress={() => setFilters({ ...filters, propertyType: undefined })}
            >
              <Text style={styles.activeFilterText}>{filters.propertyType}</Text>
              <Icon name="close" size={16} color="#0091B9" />
            </TouchableOpacity>
          )}
          {filters.location && (
            <TouchableOpacity
              style={styles.activeFilter}
              onPress={() => setFilters({ ...filters, location: undefined })}
            >
              <Text style={styles.activeFilterText}>{filters.location}</Text>
              <Icon name="close" size={16} color="#0091B9" />
            </TouchableOpacity>
          )}
        </ScrollView>
      )}

      {/* Results Count */}
      <View style={styles.resultsHeader}>
        <Text style={styles.resultsText}>
          {properties.length} properties found
        </Text>
      </View>

      {/* Properties List */}
      <FlatList
        data={properties}
        renderItem={renderProperty}
        keyExtractor={(item) => item.id}
        contentContainerStyle={styles.listContent}
        refreshing={loading}
        onRefresh={loadProperties}
        showsVerticalScrollIndicator={false}
      />

      <FiltersModal />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f8f9fa',
  },
  searchContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 15,
    paddingVertical: 10,
    backgroundColor: '#fff',
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
  searchBar: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#f5f5f5',
    borderRadius: 10,
    paddingHorizontal: 15,
    height: 45,
  },
  searchInput: {
    flex: 1,
    marginLeft: 10,
    fontSize: 16,
  },
  filterIcon: {
    marginLeft: 15,
    padding: 5,
  },
  activeFilters: {
    paddingHorizontal: 15,
    paddingVertical: 10,
    backgroundColor: '#fff',
  },
  activeFilter: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#BAF4F0',
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 20,
    marginRight: 10,
  },
  activeFilterText: {
    color: '#0091B9',
    fontSize: 14,
    marginRight: 5,
    textTransform: 'capitalize',
  },
  resultsHeader: {
    paddingHorizontal: 15,
    paddingVertical: 10,
    backgroundColor: '#fff',
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
  resultsText: {
    fontSize: 16,
    color: '#004F9B',
    fontWeight: '500',
  },
  listContent: {
    padding: 15,
    gap: 15,
  },
  modalContainer: {
    flex: 1,
    backgroundColor: '#fff',
  },
  modalHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 20,
    paddingVertical: 15,
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
  modalTitle: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#004F9B',
  },
  modalContent: {
    flex: 1,
    paddingHorizontal: 20,
  },
  filterSectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#004F9B',
    marginTop: 20,
    marginBottom: 10,
  },
  filterSection: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 10,
    marginBottom: 10,
  },
  filterButton: {
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 20,
    borderWidth: 1,
    borderColor: '#ddd',
  },
  activeFilterButton: {
    backgroundColor: '#0091B9',
    borderColor: '#0091B9',
  },
  filterButtonText: {
    color: '#666',
    fontSize: 14,
  },
  activeFilterButtonText: {
    color: '#fff',
  },
  locationInput: {
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 8,
    paddingHorizontal: 15,
    paddingVertical: 12,
    fontSize: 16,
    marginBottom: 10,
  },
  priceInputs: {
    flexDirection: 'row',
    gap: 10,
  },
  priceInput: {
    flex: 1,
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 8,
    paddingHorizontal: 15,
    paddingVertical: 12,
    fontSize: 16,
  },
  modalActions: {
    flexDirection: 'row',
    paddingHorizontal: 20,
    paddingVertical: 15,
    borderTopWidth: 1,
    borderTopColor: '#e0e0e0',
    gap: 10,
  },
  clearButton: {
    flex: 1,
    paddingVertical: 15,
    borderRadius: 8,
    borderWidth: 1,
    borderColor: '#ddd',
    alignItems: 'center',
  },
  clearButtonText: {
    color: '#666',
    fontSize: 16,
    fontWeight: '600',
  },
  applyButton: {
    flex: 1,
    paddingVertical: 15,
    borderRadius: 8,
    backgroundColor: '#0091B9',
    alignItems: 'center',
  },
  applyButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '600',
  },
});