import {
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Typography,
  Button,
  Box,
} from '@mui/material';
import React from 'react';
import { useNavigate } from 'react-router-dom';
import { PropertiesAPI, SavedPropertiesAPI } from 'types';

interface SavedPropertiesTableProps {
  savedProperties: PropertiesAPI[];
}

const SavedPropertiesTable: React.FC<SavedPropertiesTableProps> = ({ savedProperties }) => {
  const navigate = useNavigate();

  const getUpcomingOpenHouseDate = (property: PropertiesAPI): string => {
    if (!property.open_houses || property.open_houses.length === 0) {
      return 'N/A';
    }
    const today = new Date();
    const futureOpenHouses = property.open_houses.filter(
      (openHouse) => new Date(openHouse.listed_date) >= today,
    );
    if (futureOpenHouses.length > 0) {
      // Sort to get the soonest upcoming one
      futureOpenHouses.sort(
        (a, b) => new Date(a.listed_date).getTime() - new Date(b.listed_date).getTime(),
      );
      // Format the date for display
      return new Date(futureOpenHouses[0].listed_date).toLocaleDateString();
    }
    return 'No upcoming dates';
  };

  if (savedProperties.length === 0) {
    return (
      <Box sx={{ mt: 4 }}>
        <Typography variant="h6" align="center">
          You don't have any saved properties.
        </Typography>
      </Box>
    );
  }

  return (
    <TableContainer component={Paper} sx={{ mt: 4 }}>
      <Table sx={{ minWidth: 650 }} aria-label="saved properties table">
        <TableHead>
          <TableRow>
            <TableCell>Street Address</TableCell>
            <TableCell>Status</TableCell>
            <TableCell>Price</TableCell>
            <TableCell>Upcoming Open House</TableCell>
            <TableCell align="right">Actions</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {savedProperties.map((property) => {
            const displayPrice = property.listed_price
              ? `$${property.listed_price}`
              : `$${property.market_value}`;

            const openHouseDate = getUpcomingOpenHouseDate(property);

            return (
              <TableRow key={property.id}>
                <TableCell>{property.street}</TableCell>
                <TableCell>{property.property_status}</TableCell>
                <TableCell>{displayPrice}</TableCell>
                <TableCell>{openHouseDate}</TableCell>
                <TableCell align="right">
                  <Button
                    variant="contained"
                    color="primary"
                    onClick={() => navigate(`/property/${property.id}/?search=1`)}
                  >
                    View Listing
                  </Button>
                </TableCell>
              </TableRow>
            );
          })}
        </TableBody>
      </Table>
    </TableContainer>
  );
};

export default SavedPropertiesTable;
