import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  MenuItem,
  Select,
  Typography,
} from '@mui/material';
import { DocumentDialogProps } from '../AddDocumentDialog';
import React, { ReactElement, useState, useRef } from 'react';
import OfferDialogContent, { OfferDialogContentHandle, OfferData } from './OfferDialogContent'; // Import the handle and data types
import SellerDisclousureDialogContent, {
  SellerDisclousureDialogContentHandle,
  SellerDisclousureData,
} from './SellerDisclousureDialogContent';
import HomeImprovementReciptDialogContent, {
  HomeImprovementReceiptData,
  HomeImprovementReceiptDialogContentHandle,
} from './HomeImprovementReciptDialogContent';
import { axiosInstance } from '../../../../../../axiosApi';
// Assuming BidAPI, PropertiesAPI, VendorAPI are defined in types or available

export type PropertyOwnerDocumentType = 'offer' | 'seller_disclosure' | 'home_improvement_receipt';

// Custom message box component for user feedback
const MessageBox = ({ message, onClose }: { message: string; onClose: () => void }) => (
  <Dialog open={true} onClose={onClose}>
    <DialogTitle>Error</DialogTitle>
    <DialogContent>
      <Typography>{message}</Typography>
    </DialogContent>
    <DialogActions>
      <Button onClick={onClose}>OK</Button>
    </DialogActions>
  </Dialog>
);

const PropertyOwnerDocumentDialog = ({
  showDialog,
  closeDialog,
  properties,
  bids,
}: DocumentDialogProps): ReactElement => {
  const [documentType, setDocumentType] = useState<PropertyOwnerDocumentType | null>(null);
  const offerDialogRef = useRef<OfferDialogContentHandle>(null); // Ref for OfferDialogContent
  const sellerDisclosureRef = useRef<SellerDisclousureDialogContentHandle>(null);
  const homeImprovementRef = useRef<HomeImprovementReceiptDialogContentHandle>(null);
  const [submittedOfferData, setSubmittedOfferData] = useState<OfferData | null>(null); // State to hold submitted data
  const [showError, setShowError] = useState<boolean>(false);
  const [errorMessage, setErrorMessage] = useState<string>('');
  const [homeImprovmentErrors, setHomeImprovementErrors] = useState<{ [key: string]: string }>({});
  const [sellerDisclosureErrors, setSellerDisclosureErrors] = useState<{ [key: string]: string }>(
    {},
  );
  const [offerErrors, setOfferErrors] = useState<{ [key: string]: string }>({});

  // Callback function to receive data from OfferDialogContent
  const handleOfferSubmit = async (
    docType: PropertyOwnerDocumentType,
    data: OfferData | SellerDisclousureData | HomeImprovementReceiptData,
  ) => {
    if (docType === 'offer') {
      console.log(data);
      try {
        const response = await axiosInstance.post('/documents/upload/', {
          document_type: docType,
          ...data,
        });
        if (response.error) {
          setOfferErrors(error.response.data.errors);
        }
        closeDialog(); // Close the dialog after successful submission
      } catch (error) {
        console.log(error.response.data.errors);
        setOfferErrors(error.response.data.errors);
      }
    } else if (docType === 'seller_disclosure') {
      console.log(data);
      try {
        const response = await axiosInstance.post('/documents/upload/', {
          document_type: docType,
          ...data,
        });
        console.log(response);
        if (response.error) {
          setSellerDisclosureErrors(response.error);
        }
        closeDialog(); // Close the dialog after successful submission
      } catch (error) {
        console.log(error.response.data.errors);
        setSellerDisclosureErrors(error.response.data.errors);
      }

      console.log('SellerDisclousureData Data Received in PropertyOwnerDocumentDialog:', data);
    } else if (docType === 'home_improvement_receipt') {
      console.log('HomeImprovementReceiptData Data Received in PropertyOwnerDocumentDialog:', data);
      closeDialog(); // Close the dialog after successful submission
    }

    // Here you would typically send this 'data' to your backend API
  };

  // Function to render the appropriate dialog content based on document type
  const getDialogContent = (document_type: PropertyOwnerDocumentType | null): ReactElement => {
    if (document_type === 'offer') {
      return (
        <OfferDialogContent
          ref={offerDialogRef} // Pass the ref to the OfferDialogContent
          onSubmit={handleOfferSubmit} // Pass the callback for submitted data
          offerErrors={offerErrors}
        />
      );
    } else if (document_type === 'seller_disclosure') {
      // If SellerDisclousureDialogContent also needs to pass data, it would need
      // a similar ref and onSubmit prop setup.
      return (
        <SellerDisclousureDialogContent
          ref={sellerDisclosureRef}
          onSubmit={handleOfferSubmit}
          properties={properties} // Pass properties down
          sellerDisclosureErrors={sellerDisclosureErrors}
        />
      );
    } else if (document_type === 'home_improvement_receipt') {
      // Similar to offer, if HomeImprovementReciptDialogContent needs to pass data.
      return (
        <HomeImprovementReciptDialogContent
          ref={homeImprovementRef} // Example: needs its own ref
          onSubmit={handleOfferSubmit} // Example: needs its own handler
          properties={properties}
          vendors={[]}
          bids={bids}
          homeImprovmentErrors={homeImprovmentErrors}
        />
      );
    } else {
      return <Typography>Please select a document type</Typography>;
    }
  };

  // Store the currently active dialog content as a React element
  const dialogContentElement = getDialogContent(documentType);

  // Function to handle the "Create" button click in the parent dialog
  const handleCreate = async () => {
    if (documentType === 'offer') {
      if (offerDialogRef.current) {
        // Trigger the submitForm method exposed by OfferDialogContent via the ref
        offerDialogRef.current.submitForm();
      } else {
        setErrorMessage('Offer dialog content not ready. Please select a document type.');
        setShowError(true);
      }
    } else if (documentType === 'seller_disclosure') {
      if (sellerDisclosureRef.current) {
        sellerDisclosureRef.current.submitForm();
      } else {
        setErrorMessage('Seller Disclosure submission not implemented yet.');
        setShowError(true);
      }
    } else if (documentType === 'contractor_recipt') {
      // Placeholder for home improvement receipt submission
      if (homeImprovementRef.current) {
        homeImprovementRef.current.submitForm();
      } else {
        setErrorMessage('Home Improvement Recipt submission not implemented yet.');
        setShowError(true);
      }
    } else {
      // If no document type is selected
      setErrorMessage('Please select a document type before creating.');
      setShowError(true);
    }
  };

  return (
    <Dialog open={showDialog} onClose={closeDialog}>
      <DialogTitle>Create a new document</DialogTitle>
      <DialogContent>
        <Select
          value={documentType || ''} // Control the value of the Select component
          onChange={(e) => {
            if (
              e.target.value === 'offer' ||
              e.target.value === 'seller_disclosure' ||
              e.target.value === 'contractor_recipt'
            ) {
              setDocumentType(e.target.value as PropertyOwnerDocumentType);
            }
          }}
          displayEmpty // Allows the placeholder to be displayed when value is empty
          sx={{ mb: 2, minWidth: 200 }} // Add some margin-bottom for spacing
        >
          <MenuItem value="" disabled>
            Select Document Type
          </MenuItem>
          <MenuItem value="offer">Offer</MenuItem>
          <MenuItem value="seller_disclosure">Seller Disclosure</MenuItem>
          <MenuItem value="contractor_recipt">Home Improvement Recipt</MenuItem>
        </Select>
        {dialogContentElement} {/* Render the selected dialog content */}
      </DialogContent>
      <DialogActions>
        <Button onClick={closeDialog}>Cancel</Button>
        <Button variant="contained" color="primary" sx={{ ml: 'auto' }} onClick={handleCreate}>
          Create
        </Button>
      </DialogActions>
      {/* Render the message box if there's an error */}
      {showError && <MessageBox message={errorMessage} onClose={() => setShowError(false)} />}
    </Dialog>
  );
};

export default PropertyOwnerDocumentDialog;
