import { ReactElement, useContext, useEffect, useRef, useState } from 'react';
import { drawerWidth } from 'layouts/main-layout';

import {
  ConverationAPI,
  ConversationItem,
  GenericCategory,
  MessagesAPI,
  OfferAPI,
  VendorCategory,
  VendorItem,
} from 'types';
import DashboardTemplate from 'components/DasboardTemplate';
import CategoryGridTemplate from 'components/CategoryGridTemplate';
import VendorCategoryCard from 'components/sections/dashboard/Home/Vendor/VendorCategoryCard';
import ItemListDetailTemplate from 'components/ItemListDetailTemplate';
import VendorListItem from 'components/sections/dashboard/Home/Vendor/VendorListItem';
import VendorDetail from 'components/sections/dashboard/Home/Vendor/VendorDetail';
import { axiosInstance } from '../../axiosApi';
import {
  Box,
  Container,
  List,
  Grid,
  ListItem,
  ListItemText,
  Typography,
  Paper,
  TextField,
  Button,
  Avatar,
  Stack,
  Accordion,
  AccordionActions,
  AccordionSummary,
  AccordionDetails,
  Dialog,
  DialogTitle,
  DialogActions,
  DialogContent,
} from '@mui/material';
import LocalOffer from '@mui/icons-material/ChatBubbleOutline';
import SendIcon from '@mui/icons-material/Send';
import { AxiosResponse } from 'axios';
import { AccountContext } from 'contexts/AccountContext';
import { DefaultDataProvider } from 'echarts/types/src/data/helper/dataProvider.js';
import { formatTimestamp } from 'utils';
import CreateOfferDialog from 'components/sections/dashboard/Home/Offer/CreateOfferDialog';
import DeleteForeverIcon from '@mui/icons-material/DeleteForever';

interface OfferDetail {
  id: number;
  senderId: 'owner' | 'vendor'; // 'owner' represents the property owner, 'vendor' is the other party
  content: string;
  timestamp: string; // ISO string for date/time
}

interface Offer {
  id: number;
  sender: string; // the name of the person who sent it
  sender_id: number;
  property_id: number;
  address: string;
  status: 'draft' | 'submitted' | 'accepted' | 'rejected' | 'countered';
  is_active: boolean;
  lastMessageTimestamp: string;
  market_value: string;
  offer_value: string;
}

type submitOfferProps = {
  offer_id: number;
  sender_id: number;
  property_id: number;
};

const Offers = (): ReactElement => {
  const [offers, setOffers] = useState<Offer[]>([]);
  const [selectedOfferId, setSelectedOfferId] = useState<number | null>(null);
  const { account } = useContext(AccountContext);

  const [showDialog, setShowDialog] = useState<boolean>(false);
  const closeDialog = () => {
    setShowDialog(false);
  };
  const createOffer = async (property_id: number) => {
    console.log(account);
    if (account) {
      console.log({
        user: account.id,
        property: property_id,
      });
      response = await axiosInstance.post(`/offers/`, {
        user: account.id,
        property: property_id,
      });
      setShowDialog(false);

      setShowDialog(false);
    }
  };

  const submitOffer = async ({ offer_id, sender_id, property_id }: submitOfferProps) => {
    response = await axiosInstance.put(`/offers/${offer_id}/`, {
      user: sender_id,
      property: property_id,
      status: 'submitted',
    });
    console.log(response);

    // TODO: update the selectedOffer' status
    const updatedOffers: Offer[] = offers.map((item) => ({
      ...item, // Spread operator to copy existing properties
      status: 'submitted',
    }));
    setOffers(updatedOffers);
  };

  const withdrawOffer = async ({ offer_id, sender_id, property_id }: submitOfferProps) => {};

  useEffect(() => {
    const fetchOffers = async () => {
      try {
        const { data }: AxiosResponse<OfferAPI[]> = await axiosInstance.get('/offers/');
        console.log(data);
        if (data.length > 0) {
          console.log(data);
          const fetchedOffers: Offer[] = data.map((item) => {
            console.log(item);
            return {
              id: item.id,
              sender: item.user.first_name + ' ' + item.user.last_name,
              status: item.status,
              address: item.property.address,
              is_active: item.is_active,
              lastMessageTimestamp: item.updated_at,
              market_value: item.property.market_value,
              offer_value: '100000',
              sender_id: item.user.id,
              property_id: item.property.id,
            };
          });
          console.log(fetchedOffers);
          setOffers(fetchedOffers);
        }
      } catch (error) {}
    };
    fetchOffers();
  }, []);

  type offerChoice = 'accept' | 'counter' | 'reject';

  const handleOffer = async (choice: offerChoice) => {
    console.log(choice);
  };

  const selectedOffer = offers.find((conv) => conv.id === selectedOfferId);

  return (
    <Container
      maxWidth="lg"
      sx={{ py: 4, height: '100vh', display: 'flex', flexDirection: 'column' }}
    >
      <Paper
        elevation={3}
        sx={{ flexGrow: 1, display: 'flex', borderRadius: 3, overflow: 'hidden' }}
      >
        <Grid container sx={{ height: '100%' }}>
          {/* Left Panel: Offer List */}
          <Grid
            size={{ xs: 12, md: 4 }}
            sx={{
              borderRight: { md: '1px solid', borderColor: 'grey.200' },
              display: 'flex',
              flexDirection: 'column',
            }}
          >
            <Box sx={{ p: 3, borderBottom: '1px solid', borderColor: 'grey.200', display: 'flex' }}>
              <Stack direction="row" sx={{ width: '100%' }}>
                <Typography variant="h5" component="h2" sx={{ fontWeight: 'bold' }}>
                  Offers
                </Typography>
                <Button
                  variant="contained"
                  color="primary"
                  sx={{ ml: 'auto' }}
                  onClick={() => setShowDialog(true)}
                >
                  Create Offer
                </Button>
              </Stack>
            </Box>
            <List sx={{ flexGrow: 1, overflowY: 'auto', p: 1 }}>
              {offers.length === 0 ? (
                <Box sx={{ p: 2, textAlign: 'center', color: 'grey.500' }}>
                  <LocalOffer sx={{ fontSize: 40, mb: 1 }} />
                  <Typography>No offers submited yet.</Typography>
                </Box>
              ) : (
                offers
                  .sort(
                    (a, b) =>
                      new Date(b.lastMessageTimestamp).getTime() -
                      new Date(a.lastMessageTimestamp).getTime(),
                  )
                  .map((conv) => (
                    <ListItem
                      key={conv.id}
                      button
                      selected={selectedOfferId === conv.id}
                      onClick={() => setSelectedOfferId(conv.id)}
                      sx={{ py: 1.5, px: 2 }}
                    >
                      <ListItemText
                        primary={
                          <Typography variant="subtitle1" sx={{ fontWeight: 'medium' }}>
                            {conv.sender}
                          </Typography>
                        }
                        secondary={
                          <Box
                            sx={{
                              display: 'flex',
                              justifyContent: 'space-between',
                              alignItems: 'center',
                            }}
                          >
                            <Typography
                              variant="body2"
                              color="text.secondary"
                              noWrap
                              sx={{ flexGrow: 1, pr: 1 }}
                            >
                              {conv.address}
                            </Typography>
                            <Typography variant="caption" color="text.disabled">
                              {formatTimestamp(conv.lastMessageTimestamp)}
                            </Typography>
                          </Box>
                        }
                      />
                    </ListItem>
                  ))
              )}
            </List>
          </Grid>

          {/* Right Panel: Offer Detail */}
          <Grid size={{ xs: 12, md: 8 }} sx={{ display: 'flex', flexDirection: 'column' }}>
            {selectedOffer ? (
              <>
                {/* Offer Header */}
                <Box
                  sx={{
                    p: 3,
                    borderBottom: '1px solid',
                    borderColor: 'grey.200',
                    display: 'flex',
                    alignItems: 'center',
                    gap: 2,
                  }}
                >
                  <Avatar sx={{ bgcolor: 'purple.200' }}>
                    {selectedOffer.sender
                      .split(' ')
                      .map((n) => n[0])
                      .join('')}
                  </Avatar>
                  <Typography variant="h6" component="h3" sx={{ fontWeight: 'bold' }}>
                    {selectedOffer.sender}
                  </Typography>
                </Box>

                {/* Messages Area */}
                <Box sx={{ flexGrow: 1, overflowY: 'auto', p: 3, bgcolor: 'grey.50' }}>
                  {/* add the offer details here */}
                  <Accordion>
                    <AccordionSummary>Offer for {selectedOffer.address}</AccordionSummary>
                    <AccordionDetails>
                      <Typography>
                        Offer Price: <strong>{selectedOffer.offer_value}</strong>
                      </Typography>
                      <Typography>
                        Waived Inspection: <strong>No</strong>
                      </Typography>
                      <Typography>
                        Closing date: <strong>90 days</strong>
                      </Typography>
                      <Typography>
                        Status: <strong>{selectedOffer.status}</strong>
                      </Typography>
                    </AccordionDetails>
                    <AccordionActions>
                      {selectedOffer.status === 'submitted' ? (
                        <Box
                          sx={{
                            p: 2,
                            borderTop: '1px solid',
                            borderColor: 'grey.200',
                            display: 'flex',
                            alignItems: 'center',
                            gap: 2,
                          }}
                        >
                          <Button
                            variant="contained"
                            color="primary"
                            onClick={async () => handleOffer('accept')}
                            endIcon={<SendIcon />}
                            sx={{ px: 3, py: 1.2 }}
                          >
                            Accept
                          </Button>
                          <Button
                            variant="contained"
                            color="primary"
                            onClick={async () => handleOffer('counter')}
                            endIcon={<SendIcon />}
                            sx={{ px: 3, py: 1.2 }}
                          >
                            Counter
                          </Button>
                          <Button
                            variant="contained"
                            color="primary"
                            onClick={async () => handleOffer('reject')}
                            endIcon={<SendIcon />}
                            sx={{ px: 3, py: 1.2 }}
                          >
                            Reject
                          </Button>
                        </Box>
                      ) : (
                        <Box
                          sx={{
                            p: 2,
                            borderTop: '1px solid',
                            borderColor: 'grey.200',
                            display: 'flex',
                            alignItems: 'center',
                            gap: 2,
                          }}
                        >
                          <Button
                            variant="contained"
                            color="primary"
                            onClick={async () =>
                              withdrawOffer({
                                offer_id: selectedOffer.id,
                                sender_id: selectedOffer.sender_id,
                                property_id: selectedOffer.property_id,
                              })
                            }
                            endIcon={<DeleteForeverIcon />}
                            sx={{ px: 3, py: 1.2 }}
                          >
                            Withdraw Offer
                          </Button>
                          <Button
                            variant="contained"
                            color="primary"
                            onClick={async () =>
                              submitOffer({
                                offer_id: selectedOffer.id,
                                sender_id: selectedOffer.sender_id,
                                property_id: selectedOffer.property_id,
                              })
                            }
                            endIcon={<SendIcon />}
                            sx={{ px: 3, py: 1.2 }}
                          >
                            Submit
                          </Button>
                        </Box>
                      )}
                    </AccordionActions>
                  </Accordion>
                </Box>

                {/* Message Input */}
              </>
            ) : (
              <Box
                sx={{
                  flexGrow: 1,
                  display: 'flex',
                  flexDirection: 'column',
                  justifyContent: 'center',
                  alignItems: 'center',
                  p: 3,
                  color: 'grey.500',
                }}
              >
                <LocalOffer sx={{ fontSize: 80, mb: 2 }} />
                <Typography variant="h6">Select an offer to view</Typography>
                <Typography variant="body2">
                  Click on an offer from the left panel to get started.
                </Typography>
              </Box>
            )}
          </Grid>
        </Grid>
        <CreateOfferDialog
          showDialog={showDialog}
          createOffer={createOffer}
          closeDialog={closeDialog}
        />
      </Paper>
    </Container>
  );
};

export default Offers;
