import React, { useState, useEffect } from 'react';
import {
  Container,
  Typography,
  Grid,
  Card,
  CardContent,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
} from '@mui/material';

import { BidAPI, PropertiesAPI } from 'types';
import { AddBidDialog } from 'components/sections/dashboard/Home/Bids/AddBidDialog';
import { BidCard } from 'components/sections/dashboard/Home/Bids/BidCard';
import { axiosInstance } from '../../axiosApi';
import { AxiosResponse } from 'axios';

const BidsPage: React.FC = () => {
  const [bids, setBids] = useState<BidAPI[]>([]);
  const [properties, setProperties] = useState<PropertiesAPI[]>([]);
  const [openAddBidDialog, setOpenAddBidDialog] = useState(false);

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    // You'll need an endpoint to get all properties for the current owner
    const { data }: AxiosResponse<PropertiesAPI[]> = await axiosInstance.get('/properties/');
    setProperties(data);

    // You'll need an endpoint to get all bids for the current owner's properties
    const { data: bidData }: AxiosResponse<BidAPI[]> = await axiosInstance.get('/bids/');
    setBids(bidData);
  };

  const handleDeleteBid = async (bidId: number) => {
    try {
      await axios.delete(`/api/bids/${bidId}/`);
      fetchData(); // Refresh the list
    } catch (error) {
      console.error('Failed to delete bid', error);
    }
  };

  return (
    <Container>
      <Typography variant="h4" gutterBottom sx={{ color: 'background.paper' }}>
        My Property Bids
      </Typography>
      <Button variant="contained" onClick={() => setOpenAddBidDialog(true)}>
        Add New Bid
      </Button>

      <Grid container spacing={3} sx={{ mt: 3 }}>
        {bids.map((bid) => (
          <Grid size={{ xs: 12 }} key={bid.id}>
            <BidCard bid={bid} onDelete={handleDeleteBid} isOwner={true} />
          </Grid>
        ))}
      </Grid>

      <AddBidDialog
        open={openAddBidDialog}
        onClose={() => setOpenAddBidDialog(false)}
        properties={properties}
        onBidAdded={fetchData}
      />
    </Container>
  );
};

export default BidsPage;
