import React from 'react';
import {
  Card,
  CardContent,
  Typography,
  Box,
  Chip,
  Button,
  IconButton,
  Select,
  MenuItem,
} from '@mui/material';
import VisibilityIcon from '@mui/icons-material/Visibility';
import FavoriteIcon from '@mui/icons-material/Favorite';
import AccessTimeIcon from '@mui/icons-material/AccessTime';
import { PropertiesAPI, SavedPropertiesAPI } from 'types';
import FavoriteBorderIcon from '@mui/icons-material/FavoriteBorder';

const getIcon = (
  savedProperty: SavedPropertiesAPI | null,
): typeof FavoriteBorderIcon | typeof FavoriteIcon => {
  return savedProperty ? FavoriteIcon : FavoriteBorderIcon;
};

interface PropertyStatusCardProps {
  property: PropertiesAPI;
  isOwner: boolean;
  onStatusChange?: (string) => void;
  onSavedPropertySave?: () => void;
  savedProperty: SavedPropertiesAPI | null;
  sellerDisclosureExists: boolean;
}

const PropertyStatusCard: React.FC<PropertyStatusCardProps> = ({
  property,
  isOwner,
  onStatusChange,
  onSavedPropertySave,
  savedProperty,
  sellerDisclosureExists,
}) => {
  const handleStatusChange = (e) => {
    const newStatus = e.target.value;
    if (newStatus === 'active' && !sellerDisclosureExists) {
      alert('A seller disclosure document is required before putting the property on the market.');
      return;
    }
    onStatusChange(newStatus);
  };
  const getStatusColor = (status: PropertiesAPI['property_status']) => {
    switch (status) {
      case 'active':
        return 'success';
      case 'pending':
        return 'warning';
      case 'contingent':
        return 'primary';
      case 'sold':
        return 'secondary';
      default:
        return 'default';
    }
  };

  const timeSinceListed = (dateString: string) => {
    const listedDate = new Date(dateString.split('T')[0]);
    const now = new Date();
    const diffInMs = now.getTime() - listedDate.getTime();
    const diffInDays = Math.floor(diffInMs / (1000 * 60 * 60 * 24));
    return `${diffInDays} days`;
  };
  const getTimeOnMarketString = (status: PropertiesAPI['property_status'], listed_date: string) => {
    switch (status) {
      case 'active':
        return timeSinceListed(listed_date) + ' On Market';
      case 'pending':
        return timeSinceListed(listed_date) + ' On Market';
      case 'contingent':
        return timeSinceListed(listed_date) + ' On Market';
      case 'sold':
        return '';
      default:
        return '';
    }
  };
  const timeOnMarketString: string = getTimeOnMarketString(
    property.property_status,
    property?.listed_date ? property?.listed_date : '',
  );

  return (
    <Card>
      <CardContent>
        <Typography variant="h6" gutterBottom>
          Property Status
        </Typography>
        <Box display="flex" justifyContent="space-between" alignItems="center">
          <Typography variant="h4" color="primary" sx={{ fontWeight: 'bold' }}>
            ${property.listed_price ? property.listed_price : property.market_value}
          </Typography>
          {isOwner ? (
            <Select
              value={property.property_status}
              onChange={handleStatusChange}
              displayEmpty
              variant="standard"
              sx={{ mt: 2 }}
            >
              <MenuItem value="off_market" disabled={property.property_status === 'off_market'}>
                Off Market
              </MenuItem>
              <MenuItem value="active" disabled={property.property_status === 'active'}>
                Active
              </MenuItem>
            </Select>
          ) : (
            <Chip
              label={property.property_status.toUpperCase()}
              color={getStatusColor(property.property_status)}
              sx={{ fontSize: '1rem', fontWeight: 'bold' }}
            />
          )}
        </Box>
        <Box mt={2} display="flex" alignItems="center" justifyContent="space-around">
          <Box display="flex" alignItems="center">
            <VisibilityIcon color="primary" sx={{ mr: 1 }} />
            <Typography variant="body1">{property.views} Views</Typography>
          </Box>
          <Box display="flex" alignItems="center">
            {isOwner ? (
              <FavoriteIcon color="primary" sx={{ mr: 1 }} />
            ) : (
              <Box
                component={getIcon(savedProperty)}
                color="primary"
                sx={{ mr: 1 }}
                onClick={onSavedPropertySave}
              />
            )}

            <Typography variant="body1">{property.saves} Saves</Typography>
          </Box>
          {timeOnMarketString && (
            <Box display="flex" alignItems="center">
              <AccessTimeIcon color="primary" sx={{ mr: 1 }} />
              <Typography variant="body1">{timeOnMarketString}</Typography>
            </Box>
          )}
        </Box>
      </CardContent>
    </Card>
  );
};

export default PropertyStatusCard;
