import React, { useState, useEffect, useContext } from 'react';
import { useLocation, useParams, useNavigate } from 'react-router-dom';
import {
  Container,
  Typography,
  CircularProgress,
  Grid,
  Alert,
  Divider,
  Card,
  CardContent,
  Button,
} from '@mui/material';
import { PropertiesAPI, SavedPropertiesAPI } from 'types';
import PropertyDetailCard from 'components/sections/dashboard/Home/Property/PropertyDetailCard';
import SaleTaxHistoryCard from 'components/sections/dashboard/Home/Property/SaleTaxHistoryCard';
import WalkScoreCard from 'components/sections/dashboard/Home/Property/WalkScoreCard';
import OpenHouseCard from 'components/sections/dashboard/Home/Profile/OpenHouseCard';
import PropertyStatusCard from 'components/sections/dashboard/Home/Property/PropertyStatusCard';
import EstimatedMonthlyCostCard from 'components/sections/dashboard/Home/Profile/EstimatedMonthlyCostCard';
import OfferSubmissionCard from 'components/sections/dashboard/Home/Profile/OfferSubmissionCard';
import SchoolCard from 'components/sections/dashboard/Home/Property/SchoolCard';
import { cleanAxiosInstance } from '../../axiosApi';

import SellerInformationCard from 'components/sections/dashboard/Home/Property/SellerInformationCard';
import LogInNotificationCard from 'components/sections/dashboard/Home/Property/LogInNotificationCard';

const PublicPropertyDetail: React.FC = () => {
  // In a real app, you'd get propertyId from URL params or a global state

  const { propertyId } = useParams<{ propertyId: string }>();
  const location = useLocation();
  const navigate = useNavigate();
  const searchParams = new URLSearchParams(location.search);
  const [property, setProperty] = useState<PropertiesAPI | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  useEffect(() => {
    // Simulate API call
    const getProperty = async () => {
      try {
        setLoading(true);
        setError(null);
        const url = `/public/${propertyId}/`;
        const { data }: AxiosResponse<PropertiesAPI> = await cleanAxiosInstance.get(url);

        if (data !== undefined) {
          setProperty(data);
        }
        await cleanAxiosInstance.post(`/public/${propertyId}/increment_view_count/`);
      } catch (error) {
        console.error(error);
        setError('Property not found.');
      } finally {
        setLoading(false);
      }
    };

    getProperty();
  }, [propertyId]);

  if (loading) {
    return (
      <Container maxWidth="lg" sx={{ mt: 4, mb: 4, textAlign: 'center' }}>
        <CircularProgress />
        <Typography>Loading property details...</Typography>
      </Container>
    );
  }

  if (error) {
    return (
      <Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
        <Alert severity="error">{error}</Alert>
      </Container>
    );
  }

  if (!property) {
    return (
      <Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
        <Alert severity="info">No property data available.</Alert>
      </Container>
    );
  }

  // Determine if the current user is the owner of this property
  const isOwnerOfProperty = false;
  const priceForAnalysis = property.listed_price ? property.listed_price : property.market_value;

  console.log('here');
  console.log(property);

  return (
    <Container maxWidth="xl" sx={{ mt: 4, mb: 4 }}>
      {message && (
        <Alert severity={message.type} sx={{ mb: 2 }}>
          {message.text}
        </Alert>
      )}

      <Grid container spacing={3}>
        {/* Main Property Details */}
        <Grid size={{ xs: 12, md: 8 }}>
          <PropertyDetailCard
            property={property}
            isPublicPage={true}
            onSave={null}
            isOwnerView={isOwnerOfProperty}
            onDelete={() => null}
          />
        </Grid>

        {/* Status, Cost, Offers */}
        <Grid size={{ xs: 12, md: 4 }}>
          <Grid container spacing={3}>
            <Grid size={{ xs: 12 }}>
              <PropertyStatusCard
                property={property}
                isOwner={isOwnerOfProperty}
                onStatusChange={null}
                onSavedPropertySave={null}
                savedProperty={null}
                sellerDisclosureExists={null}
              />
            </Grid>
            <Grid size={{ xs: 12 }}>
              <EstimatedMonthlyCostCard price={parseFloat(priceForAnalysis)} />
            </Grid>

            <Grid size={{ xs: 12 }}>
              <LogInNotificationCard />
            </Grid>

            <Grid size={{ xs: 12 }}>
              <OpenHouseCard openHouses={property.open_houses} />
            </Grid>
          </Grid>
        </Grid>

        {/* Additional Information */}
        <Grid size={{ xs: 12 }}>
          <Divider sx={{ my: 2 }} />
        </Grid>

        <Grid size={{ xs: 12, md: 4 }}>
          <SaleTaxHistoryCard saleHistory={property.sale_info} taxInfo={property.tax_info} />
        </Grid>
        <Grid size={{ xs: 12, md: 4 }}>
          <WalkScoreCard walkScore={property.walk_score} />
        </Grid>
        <Grid size={{ xs: 12, md: 4 }}>
          {property.schools && <SchoolCard schools={property.schools} />}
        </Grid>
      </Grid>
    </Container>
  );
};

export default PublicPropertyDetail;
