import React, { useEffect, useState } from 'react';
import { Container, Typography, Box, Grid, Alert } from '@mui/material';
import { PropertiesAPI } from 'types';
import PropertySearchFilters from 'components/sections/dashboard/Home/Property/PropertySearchFilters';
import PropertyListItem from 'components/sections/dashboard/Home/Property/PropertyListItem';
import { useNavigate } from 'react-router-dom';
import MapSerachComponent from 'components/base/MapSearchComponent';
import { AxiosResponse } from 'axios';
import { axiosInstance } from '../../axiosApi';
import { useMapsLibrary } from '@vis.gl/react-google-maps';

const PropertySearchPage: React.FC = () => {
  const navigate = useNavigate();
  const [searchResults, setSearchResults] = useState<PropertiesAPI[]>([]);
  const [initialLoad, setInitialLoad] = useState(true);
  const [selectedPropertyId, setSelectedPropertyId] = useState<number | null>(null);
  const [mapState, setMapState] = useState({
    center: { lat: 39.8283, lng: -98.5795 }, // Center of the US
    zoom: 4,
  });

  useEffect(() => {
    const fetchProperties = async () => {
      try {
        const { data }: AxiosResponse<PropertiesAPI[]> =
          await axiosInstance.get(`/properties/?search=1`);
        console.log(data);
        data.map((item) => {
          console.log(item);
        });
        if (data !== undefined) {
          setSearchResults(data);
        }
      } catch {
      } finally {
        setInitialLoad(true);
      }
    };
    fetchProperties();
  }, []);

  const filterProperties = async (filters: any) => {
    const searchParams = new URLSearchParams();

    for (const key in filters) {
      if (filters.hasOwnProperty(key)) {
        const value = filters[key];

        // Exclude attributes that don't have values (null, undefined, empty string)
        if (value !== null && value !== undefined && value !== '') {
          searchParams.append(key, String(value)); // Ensure value is a string
        }
      }
    }
    const queryString = searchParams.toString();
    console.log(queryString);
    try {
      const { data }: AxiosResponse<PropertiesAPI[]> = await axiosInstance.get(
        `/properties/?search=1&${queryString}`,
      );
      console.log(data);
      setSearchResults(data);
    } catch {
    } finally {
      setInitialLoad(false);
    }
  };

  const handleSearch = async (filters: any) => {
    console.log(filters);
    await filterProperties(filters);
  };

  const handleClearSearch = () => {
    setSearchResults([]); // Clear results on clear
    setInitialLoad(true); // Reset to initial state
  };

  const handleMapBoundsChange = ({ center, zoom, bounds }: any) => {
    setMapState({ center, zoom });
    // Optional: you could filter search results based on the map bounds
  };

  const handleBoxDrawn = (bounds: any) => {
    const filtered = mockProperties.filter((p) => {
      if (!p.latitude || !p.longitude) return false;
      return (
        p.latitude <= bounds.ne.lat &&
        p.latitude >= bounds.sw.lat &&
        p.longitude <= bounds.ne.lng &&
        p.longitude >= bounds.sw.lng
      );
    });
    setSearchResults(filtered);
    setInitialLoad(false);
    // Optional: Adjust map zoom to fit the new search results
    // You'd need to calculate the new center and zoom based on the filtered results.
  };

  const handleMarkerClick = (propertyId: number) => {
    navigate(`/properties/${propertyId}`);
  };

  const handleMarkerHover = (property: PropertiesAPI) => {
    setSelectedPropertyId(property.id);
  };

  const handleMarkerUnhover = () => {
    setSelectedPropertyId(null);
  };

  // Handler for a map marker click, this will navigate to the details page
  const handleMapMarkerClick = (propertyId: number) => {
    navigate(`/properties/${propertyId}/&search=1`);
  };

  console.log(searchResults);

  return (
    <Container maxWidth="xl" sx={{ mt: 4, mb: 4 }}>
      <Typography variant="h4" component="h1" gutterBottom sx={{ color: 'background.paper' }}>
        Property Search & Map
      </Typography>
      <PropertySearchFilters onSearch={handleSearch} onClear={handleClearSearch} />

      <Grid container spacing={3}>
        {/* Property List Section */}
        <Grid size={{ xs: 12, md: 6 }}>
          <Box sx={{ maxHeight: '70vh', overflowY: 'auto' }}>
            <Typography variant="h5" sx={{ mb: 2, color: 'background.paper' }}>
              {initialLoad ? 'All Properties' : `Search Results (${searchResults.length} found)`}
            </Typography>
            {searchResults.length === 0 ? (
              <Alert severity="info">No properties found matching your criteria.</Alert>
            ) : (
              searchResults.map((property) => (
                <PropertyListItem
                  key={property.id}
                  property={property}
                  onHover={handleMarkerHover}
                  onUnhover={handleMarkerUnhover}
                  // The click logic will now be handled by the marker
                  // We just highlight the selected marker
                  isSelected={selectedPropertyId === property.id}
                />
              ))
            )}
          </Box>
        </Grid>

        {/* Map Section */}
        <Grid size={{ xs: 12, md: 6 }}>
          <MapSerachComponent
            center={mapState.center}
            zoom={mapState.zoom}
            properties={searchResults}
            selectedPropertyId={selectedPropertyId}
            onBoundsChanged={handleMapBoundsChange}
            onBoxDrawn={handleBoxDrawn}
            onMarkerClick={handleMapMarkerClick} // Pass the navigation handler
            onMarkerHover={handleMarkerHover}
            onMarkerUnhover={handleMarkerUnhover}
          />
        </Grid>
      </Grid>
    </Container>
  );
};

export default PropertySearchPage;
