import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  CircularProgress,
  Accordion,
  AccordionSummary,
  AccordionDetails,
} from '@mui/material';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import { axiosInstance } from '../../../../../axiosApi';
import OfferDisplay, { OfferData } from './OfferDisplay';
import { DocumentAPI } from 'types';

// Interfaces for consistency across components
interface Property {
  id: number;
  address: string;
  city: string;
  state: string;
  zip_code: string;
}

interface OfferNegotiationHistoryProps {
  property: Property;
  isPropertyOwner: boolean;
  offerData: DocumentAPI;
}

const OfferNegotiationHistory: React.FC<OfferNegotiationHistoryProps> = ({
  property,
  isPropertyOwner,
  offerData,
}) => {
  const [offer, setOffer] = useState<OfferData>(offerData);
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);
  const [expandedAccordion, setExpandedAccordion] = useState<number | false>(false);

  const [history, setHistory] = useState<OfferData[]>([]);
  // This useEffect builds the negotiation history
  useEffect(() => {
    let currentOffer = offerData.sub_document;
    const negotiationHistory: OfferData[] = [];

    // Traverse the parent chain until there is no parent
    while (currentOffer) {
      negotiationHistory.push(currentOffer);
      currentOffer = currentOffer.parent_offer;
    }
    console.log(negotiationHistory);
    const reversedHistory = negotiationHistory.reverse();

    setHistory(reversedHistory);
    if (reversedHistory.length > 0) {
      setExpandedAccordion(reversedHistory[reversedHistory.length - 1].id);
    }
  }, [offerData]);

  const handleChange = (panelId: number) => (event: React.SyntheticEvent, isExpanded: boolean) => {
    console.log(panelId, isExpanded);
    setExpandedAccordion(isExpanded ? panelId : false);
  };

  // const fetchOffers = async () => {
  //   setLoading(true);
  //   setError(null);
  //   try {
  //     // Assuming a new endpoint or a modified one that returns all offers for a property.
  //     // You may need to create this in your Django views.
  //     const response = await axiosInstance.get(`/documents/retrieve/?docId=${property.id}/`);
  //     setOffers(response.data);
  //   } catch (err) {
  //     console.error('Failed to fetch offers:', err);
  //     setError('Failed to load offers. Please try again later.');
  //   } finally {
  //     setLoading(false);
  //   }
  // };
  // console.log(property);
  // useEffect(() => {
  //   if (property) {
  //     fetchOffers();
  //   }
  // }, [property]);

  const handleOfferAction = async (
    documentId: number,
    action: 'accept' | 'reject' | 'counter',
    newOfferData?: any,
  ) => {
    setLoading(true);
    try {
      const payload = {
        document_id: documentId,
        action: action,
        ...newOfferData, // Pass new offer data for a counter-offer
      };
      await axiosInstance.patch('/documents/retrieve/', payload);
      //await fetchOffers(); // Re-fetch offers to see the updated status
    } catch (err) {
      console.error(`Failed to perform action '${action}':`, err);
      setError('Failed to update offer status. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
        <CircularProgress />
      </Box>
    );
  }

  if (error) {
    return (
      <Box sx={{ p: 3 }}>
        <Typography variant="h6" color="error">
          {error}
        </Typography>
      </Box>
    );
  }

  // if (offers.length === 0) {
  //   return (
  //     <Box sx={{ p: 3 }}>
  //       <Typography variant="h6" color="text.secondary">
  //         No offers have been submitted for this property.
  //       </Typography>
  //     </Box>
  //   );
  // }

  return (
    <Box sx={{ my: 4 }}>
      <Typography variant="h4" component="h2" gutterBottom>
        Negotiation History
      </Typography>

      {history.length > 0 ? (
        history.map((offer, index) => (
          <Accordion
            key={index}
            expanded={expandedAccordion === index}
            onChange={handleChange(index)}
          >
            <AccordionSummary expandIcon={<ExpandMoreIcon />}>
              <Typography>
                Offer - {offer.status.toUpperCase()} - ${offer.offer_price}
              </Typography>
            </AccordionSummary>
            <AccordionDetails>
              <OfferDisplay
                offerData={offer}
                property={property}
                isPropertyOwner={isPropertyOwner}
                onAccept={() => handleOfferAction(offer.id, 'accept')}
                onReject={() => handleOfferAction(offer.id, 'reject')}
                onCounter={() => {
                  const newPrice = offer.offer_price * 0.95;
                  handleOfferAction(offer.id, 'counter', { offer_price: newPrice });
                }}
              />
            </AccordionDetails>
          </Accordion>
        ))
      ) : (
        <Typography>No negotiation history available.</Typography>
      )}
    </Box>
  );
};

export default OfferNegotiationHistory;
