import React, { 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';

// Reusing the mockProperties from PropertyDetailPage for consistent data
const mockProperties: PropertiesAPI[] = [
  {
    id: 101,
    owner: {
      user: {
        id: 1,
        email: 'john.doe@example.com',
        first_name: 'John',
        last_name: 'Doe',
        user_type: 'property_owner',
        is_active: true,
        date_joined: '2023-01-15',
        tos_signed: true,
        profile_created: true,
        tier: 'basic',
      },
      phone_number: '123-456-7890',
    },
    address: '123 Main St',
    city: 'Anytown',
    state: 'CA',
    zip_code: '90210',
    market_value: '500000',
    loan_amount: '300000',
    loan_term: 30,
    loan_start_date: '2020-05-01',
    created_at: '2020-04-20',
    last_updated: '2023-10-10',
    pictures: [
      'https://via.placeholder.com/600x400?text=Property+1+Exterior',
      'https://via.placeholder.com/600x400?text=Property+1+Living',
    ],
    description:
      'A beautiful 3-bedroom, 2-bathroom house in a quiet neighborhood. Features a spacious backyard and modern kitchen.',
    sq_ft: 1800,
    features: ['Garage', 'Central AC', 'Hardwood Floors'],
    num_bedrooms: 3,
    num_bathrooms: 2,
    latitude: 34.0522, // Example coordinates for Los Angeles
    longitude: -118.2437,
  },
  {
    id: 102,
    owner: {
      user: {
        id: 1,
        email: 'john.doe@example.com',
        first_name: 'John',
        last_name: 'Doe',
        user_type: 'property_owner',
        is_active: true,
        date_joined: '2023-01-15',
        tos_signed: true,
        profile_created: true,
        tier: 'basic',
      },
      phone_number: '123-456-7890',
    },
    address: '456 Oak Ave',
    city: 'Anytown',
    state: 'CA',
    zip_code: '90210',
    market_value: '750000',
    loan_amount: '500000',
    loan_term: 20,
    loan_start_date: '2022-01-10',
    created_at: '2021-12-01',
    last_updated: '2023-11-20',
    pictures: ['https://via.placeholder.com/600x400?text=Property+2+Front'],
    description: 'Large family home with 4 bedrooms and a large pool. Perfect for entertaining.',
    sq_ft: 2500,
    features: ['Pool', 'Fireplace', 'Large Yard'],
    num_bedrooms: 4,
    num_bathrooms: 3,
    latitude: 34.075, // Another example coordinate
    longitude: -118.3,
  },
  {
    id: 103,
    owner: {
      user: {
        id: 99,
        email: 'another.owner@example.com',
        first_name: 'Jane',
        last_name: 'Doe',
        user_type: 'property_owner',
        is_active: true,
        date_joined: '2023-01-15',
        tos_signed: true,
        profile_created: true,
        tier: 'basic',
      },
      phone_number: '987-654-3210',
    },
    address: '789 Pine Lane',
    city: 'Otherville',
    state: 'NY',
    zip_code: '10001',
    market_value: '1200000',
    loan_amount: '800000',
    loan_term: 15,
    loan_start_date: '2021-03-20',
    created_at: '2021-02-15',
    last_updated: '2024-01-05',
    pictures: ['https://via.placeholder.com/600x400?text=NY+Property'],
    description: 'Luxury apartment in the heart of the city with stunning views.',
    sq_ft: 1200,
    features: ['City View', 'Gym Access', 'Doorman'],
    num_bedrooms: 2,
    num_bathrooms: 2,
    latitude: 40.7128, // NYC
    longitude: -74.006,
  },
  {
    id: 104,
    owner: {
      user: {
        id: 100,
        email: 'test.user@example.com',
        first_name: 'Bob',
        last_name: 'Brown',
        user_type: 'property_owner',
        is_active: true,
        date_joined: '2024-01-01',
        tos_signed: true,
        profile_created: true,
        tier: 'premium',
      },
      phone_number: '555-987-6543',
    },
    address: '101 Elm Street',
    city: 'Sampleton',
    state: 'TX',
    zip_code: '75001',
    market_value: '350000',
    loan_amount: '250000',
    loan_term: 30,
    loan_start_date: '2023-07-01',
    created_at: '2023-06-20',
    last_updated: '2024-06-15',
    pictures: ['https://via.placeholder.com/600x400?text=TX+House'],
    description: 'Cozy starter home with a large yard, ideal for families.',
    sq_ft: 1500,
    features: ['Large Yard', 'New Roof'],
    num_bedrooms: 3,
    num_bathrooms: 2,
    latitude: 32.7767, // Dallas
    longitude: -96.797,
  },
];

const Property: React.FC = () => {
  const [searchResults, setSearchResults] = useState<PropertiesAPI[]>([]);
  const [initialLoad, setInitialLoad] = useState(true);

  const filterProperties = (filters: any) => {
    const filtered = mockProperties.filter((property) => {
      const addressMatch = filters.address
        ? property.address.toLowerCase().includes(filters.address.toLowerCase())
        : true;
      const cityMatch = filters.city
        ? property.city.toLowerCase().includes(filters.city.toLowerCase())
        : true;
      const stateMatch = filters.state
        ? property.state.toLowerCase() === filters.state.toLowerCase()
        : true;
      const zipCodeMatch = filters.zipCode ? property.zip_code.includes(filters.zipCode) : true;

      const sqFtMatch =
        (filters.minSqFt === '' || property.sq_ft >= filters.minSqFt) &&
        (filters.maxSqFt === '' || property.sq_ft <= filters.maxSqFt);
      const bedroomsMatch =
        (filters.minBedrooms === '' || property.num_bedrooms >= filters.minBedrooms) &&
        (filters.maxBedrooms === '' || property.num_bedrooms <= filters.maxBedrooms);
      const bathroomsMatch =
        (filters.minBathrooms === '' || property.num_bathrooms >= filters.minBathrooms) &&
        (filters.maxBathrooms === '' || property.num_bathrooms <= filters.maxBathrooms);

      return (
        addressMatch &&
        cityMatch &&
        stateMatch &&
        zipCodeMatch &&
        sqFtMatch &&
        bedroomsMatch &&
        bathroomsMatch
      );
    });
    setSearchResults(filtered);
    setInitialLoad(false);
  };

  const handleSearch = (filters: any) => {
    filterProperties(filters);
  };

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

  return (
    <Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
      <Typography variant="h4" component="h1" gutterBottom>
        Property Search
      </Typography>
      <PropertySearchFilters onSearch={handleSearch} onClear={handleClearSearch} />

      <Typography variant="h5" sx={{ mt: 4, mb: 2 }}>
        {initialLoad
          ? 'Enter search criteria to find properties.'
          : `Search Results (${searchResults.length} found)`}
      </Typography>
      <Grid container spacing={2}>
        {searchResults.length === 0 && !initialLoad ? (
          <Grid size={{ xs: 12 }}>
            <Alert severity="info">No properties found matching your criteria.</Alert>
          </Grid>
        ) : (
          searchResults.map((property) => (
            <Grid size={{ xs: 12, sm: 6, md: 4 }} key={property.id}>
              <PropertyListItem
                property={property}
                onViewDetails={() => console.log('Navigate to details for:', property.id)} // Handled internally by navigate
              />
            </Grid>
          ))
        )}
      </Grid>
    </Container>
  );
};

export default Property;

// import { ReactElement, useContext, useEffect, useState } from 'react';
// import { drawerWidth } from 'layouts/main-layout';
// import PropertyDetailsCard from 'components/sections/dashboard/Home/Property/PropertyDetailsCard';
// import HomePriceEstimate from 'components/sections/dashboard/Home/Property/HomePriceEstimate';
// import PhotoGalleryCard from 'components/sections/dashboard/Home/Property/PhotoGalleryCard';
// import MarketStatistics from 'components/sections/dashboard/Home/Property/MarketStatistics';
// import PropertyListingCard from 'components/sections/dashboard/Home/Property/PropertyListingCard';
// import LoanDetailsCard from 'components/sections/dashboard/Home/Property/LoanDetailsCard';
// import PropertyValueGraphCard from 'components/sections/dashboard/Home/Property/PropertyValueGraphCard';
// import {axiosInstance} from '../../axiosApi'
// import { PropertiesAPI } from 'types';
// import { AxiosResponse } from 'axios';
// import LoadingSkeleton from 'components/base/LoadingSkeleton';
// import { AccountContext } from 'contexts/AccountContext';
// import { Box, Container, List, Grid, ListItem, ListItemText, Typography, Paper, TextField, Button, Avatar, Stack } from '@mui/material';
// import HouseIcon from '@mui/icons-material/House';
// import { formatTimestamp } from 'utils';

// const Property = (): ReactElement => {
//     const [properties, setProperties] = useState<PropertiesAPI[]>([]);
//     const [selectedPropertyId, setSelectedPropertyId] = useState<number | null>(null)
//     const {account, accountLoading} = useContext(AccountContext);
//     if(accountLoading){
//         return <LoadingSkeleton />
//     }
//     useEffect(() => {
//         const fetchProperties = async() => {
//             try{
//                 const {data, }: AxiosResponse<PropertiesAPI[]> = await axiosInstance.get('/properties/')
//                 if(data.length > 0){
//                     setProperties(data);
//                     setSelectedPropertyId(data[0].id)

//                 }

//             }catch(error){
//                 console.log(error)
//             }
//         }
//         fetchProperties();
//     }, [])

//     const selectedProperty = properties.find(
//     (property) => property.id === selectedPropertyId
//   );

//     return(
//     <Container maxWidth="lg" sx={{ py: 4, minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
//             <Paper elevation={3} sx={{ flexGrow: 1, display: 'flex', borderRadius: 3, overflow: 'hidden' }}>
//               <Grid container sx={{ minHeight: '100%' }}>
//                 {/* Left Panel: Conversation List */}
//                 <Grid item xs={12} md={4} sx={{ borderRight: { md: '1px solid', borderColor: 'grey.200' }, display: 'flex', flexDirection: 'column' }}>
//                   <Box sx={{ p: 3, borderBottom: '1px solid', borderColor: 'grey.200', display:'flex' }}>
//                     <Stack direction="row" sx={{width:'100%'}}>

//                     <Typography variant="h5" component="h2" sx={{ fontWeight: 'bold' }}>
//                       Properties
//                     </Typography>
//                     </Stack>
//                   </Box>
//                   <List sx={{ flexGrow: 1, overflowY: 'auto', p: 1 }}>
//                     {properties.length === 0 ? (
//                       <Box sx={{ p: 2, textAlign: 'center', color: 'grey.500' }}>
//                         <HouseIcon sx={{ fontSize: 40, mb: 1 }} />
//                         <Typography>No properties yet. Go to profile to add one.</Typography>
//                       </Box>
//                     ) : (

//                       properties
//                         .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
//                         .map((conv) => (
//                           <ListItem
//                             key={conv.id}
//                             button
//                             selected={selectedPropertyId === conv.id}
//                             onClick={() => setSelectedPropertyId(conv.id)}
//                             sx={{ py: 1.5, px: 2 }}
//                           >
//                             <ListItemText
//                               primary={
//                                 <Typography variant="subtitle1" sx={{ fontWeight: 'medium' }}>
//                                   {conv.address}
//                                 </Typography>
//                               }
//                               secondary={
//                                 <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
//                                   <Typography variant="body2" color="text.secondary" noWrap sx={{ flexGrow: 1, pr: 1 }}>
//                                     {conv.market_value}
//                                   </Typography>
//                                   <Typography variant="caption" color="text.disabled">
//                                     {formatTimestamp(conv.last_updated)}
//                                   </Typography>
//                                 </Box>
//                               }
//                             />
//                           </ListItem>
//                         ))
//                     )}
//                   </List>
//                 </Grid>

//                 {/* Right Panel: Conversation Detail */}
//                 <Grid item xs={12} md={8} sx={{ display: 'flex', flexDirection: 'column' }}>
//                   {selectedProperty ? (
//                     <>
//                       {/* Conversation Header */}
//                       <Box sx={{ p: 3, borderBottom: '1px solid', borderColor: 'grey.200', display: 'flex', alignItems: 'center', gap: 2 }}>
//                         <Avatar sx={{ bgcolor: 'purple.200'}}>
//                           {/* {selectedProperty.withName.split(' ').map(n => n[0]).join('')} */}
//                         </Avatar>
//                         <Typography variant="h6" component="h3" sx={{ fontWeight: 'bold' }}>
//                           {selectedProperty.address}
//                         </Typography>
//                       </Box>

//                       {/* Messages Area */}
//                       <Box sx={{ flexGrow: 1, overflowY: 'auto', p: 3, bgcolor: 'grey.50' }}>
//                         <Grid
//                             container
//                             component="main"
//                             columns={12}
//                             spacing={3.75}
//                             flexGrow={1}
//                             pt={4.375}
//                             pr={1.875}
//                             pb={0}
//                             sx={{
//                                 width: { md: `calc(100% - ${drawerWidth}px)` },
//                                 pl: { xs: 3.75, lg: 0 },
//                             }}
//                             >
//                                 <Grid xs={12} md={8}>

//                                     <PropertyDetailsCard />
//                                 </Grid>
//                                 <Grid xs={12} md={4}>
//                                     <HomePriceEstimate />

//                                 </Grid>
//                                 <Grid xs={12} md={8}>
//                                     <PhotoGalleryCard />

//                                 </Grid>
//                                 <Grid xs={12} md={4}>
//                                     <MarketStatistics />

//                                 </Grid>
//                                 <Grid xs={12} md={8}>
//                                     <PropertyValueGraphCard />

//                                 </Grid>
//                                 <Grid xs={12} md={4}>
//                                     <LoanDetailsCard />

//                                 </Grid>
//                                 <Grid xs={12} md={4}>
//                                     <PropertyListingCard />

//                                 </Grid>
//                                 </Grid>

//                                             </Box>

//                                             </>
//                                         ) : (
//                                             <Box sx={{ flexGrow: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', p: 3, color: 'grey.500' }}>
//                                             <HouseIcon sx={{ fontSize: 80, mb: 2 }} />
//                                             <Typography variant="h6">Select a property to manage</Typography>
//                                             <Typography variant="body2">Click on a property from the left panel to get started.</Typography>
//                                             </Box>
//                                         )}
//                                         </Grid>
//                                     </Grid>
//                                     </Paper>
//                                 </Container>
//     )

//     // return(
//     //     <Grid
//     //   container
//     //   component="main"
//     //   columns={12}
//     //   spacing={3.75}
//     //   flexGrow={1}
//     //   pt={4.375}
//     //   pr={1.875}
//     //   pb={0}
//     //   sx={{
//     //     width: { md: `calc(100% - ${drawerWidth}px)` },
//     //     pl: { xs: 3.75, lg: 0 },
//     //   }}
//     // >
//     //     <Grid xs={12} md={8}>

//     //         <PropertyDetailsCard />
//     //     </Grid>
//     //     <Grid xs={12} md={4}>
//     //         <HomePriceEstimate />

//     //     </Grid>
//     //     <Grid xs={12} md={8}>
//     //         <PhotoGalleryCard />

//     //     </Grid>
//     //     <Grid xs={12} md={4}>
//     //         <MarketStatistics />

//     //     </Grid>
//     //     <Grid xs={12} md={8}>
//     //         <PropertyValueGraphCard />

//     //     </Grid>
//     //     <Grid xs={12} md={4}>
//     //         <LoanDetailsCard />

//     //     </Grid>
//     //     <Grid xs={12} md={4}>
//     //         <PropertyListingCard />

//     //     </Grid>
//     //     </Grid>
//     // )
// }

// export default Property;
