import React, { useMemo } from 'react';
import {
  Card,
  CardContent,
  Typography,
  List,
  ListItem,
  ListItemText,
  Divider,
} from '@mui/material';
import { OpenHouseAPI } from 'types';
import { format } from 'date-fns';

interface OpenHouseCardProps {
  openHouses: OpenHouseAPI[] | undefined;
}

const OpenHouseCard: React.FC<OpenHouseCardProps> = ({ openHouses }) => {
  // Filter to only show future open houses
  const futureOpenHouses = useMemo(() => {
    if (!openHouses) return [];

    const now = new Date();
    return openHouses.filter((openHouse) => {
      // Combine the listed_date with end_time to get the full end datetime
      const endDateTime = new Date(`${openHouse.listed_date}T${openHouse.end_time}`);
      return endDateTime > now;
    });
  }, [openHouses]);

  if (openHouses) {
    return (
      <Card>
        <CardContent>
          <Typography variant="h6" gutterBottom>
            Open House Information
          </Typography>
          {futureOpenHouses.length > 0 ? (
            <List dense>
              {futureOpenHouses.map((openHouse, index) => (
                <React.Fragment key={index}>
                  <ListItem>
                    <ListItemText
                      primary={`${format(new Date(openHouse.listed_date), 'MMM d, yyyy')} at ${format(
                        new Date(`1970-01-01T${openHouse.start_time}`),
                        'h a',
                      )} - ${format(new Date(`1970-01-01T${openHouse.end_time}`), 'h a')}`}
                    />
                  </ListItem>
                  {index < futureOpenHouses.length - 1 && <Divider component="li" />}
                </React.Fragment>
              ))}
            </List>
          ) : (
            <Typography variant="body2" color="text.secondary">
              No upcoming open houses scheduled.
            </Typography>
          )}
        </CardContent>
      </Card>
    );
  } else {
    return (
      <Card>
        <CardContent>
          <Typography variant="h6" gutterBottom>
            Open House Information
          </Typography>
          <Typography variant="body2" color="text.secondary">
            No upcoming open houses scheduled.
          </Typography>
        </CardContent>
      </Card>
    );
  }
};

export default OpenHouseCard;
