// src/components/DocumentManager.tsx

import React, { useState, useEffect, useContext } from 'react';
import { useSearchParams } from 'react-router-dom';

import {
  Button,
  List,
  ListItem,
  ListItemText,
  Typography,
  Box,
  Grid,
  Paper,
  Container,
  Stack,
} from '@mui/material';
import { AxiosResponse } from 'axios';
import { BidAPI, DocumentAPI, PropertiesAPI } from 'types';
import { axiosInstance } from '../../../../../axiosApi';
import { AccountContext } from 'contexts/AccountContext';
import DashboardLoading from '../Dashboard/DashboardLoading';
import DashboardErrorPage from '../Dashboard/DashboardErrorPage';

import ArticleIcon from '@mui/icons-material/Article';
import { formatTimestamp } from 'utils';
import AddDocumentDialog from './AddDocumentDialog';
import SellerDisclosureDisplay from './SellerDisclosureDisplay';
import { PropertyOwnerDocumentType } from './Dialog/PropertyOwnerDocumentDialog';
import HomeImprovementReceiptDisplay from './HomeImprovementReceiptDisplay';
import OfferDisplay from './OfferDisplay';
import OfferNegotiationHistory from './OfferNegotiationHistory';

interface DocumentManagerProps {}

const getDocumentTitle = (docType: PropertyOwnerDocumentType) => {
  if (docType === 'seller_disclosure') {
    return 'Seller Disclosure';
  } else if (docType === 'offer_letter') {
    return 'Offer';
  } else if (docType === 'home_improvement_receipt') {
    return 'Home Improvement Receipt';
  } else {
    return docType;
  }
};

const isMyTypeDocument = (upload_by: number, account_id: number, document_type: string) => {
  console.log(upload_by, account_id, document_type);
  if (document_type === 'offer_letter') {
    return !(upload_by === account_id);
  } else if (document_type === 'seller_disclosure') {
    return upload_by === account_id;
  }
};

const DocumentManager: React.FC<DocumentManagerProps> = ({}) => {
  const { account, accountLoading } = useContext(AccountContext);
  const [searchParams] = useSearchParams();
  const [documents, setDocuments] = useState<DocumentAPI[]>([]);
  const [properties, setProperties] = useState<PropertiesAPI[]>([]);
  const [bids, setBids] = useState<BidAPI[]>([]);
  const [selectedDocument, setSelectedDocument] = useState<DocumentAPI | null>(null);
  const [showDialog, setShowDialog] = useState<boolean>(false);
  const [selectedPropertyForDocument, setSelectedPropertyForDocument] =
    useState<PropertiesAPI | null>(null);

  const closeDialog = () => {
    setShowDialog(false);
  };

  useEffect(() => {
    const fetchDocuments = async () => {
      try {
        const { data }: AxiosResponse<DocumentAPI[]> = await axiosInstance.get('/document/');
        setDocuments(data);
      } catch (error) {
        console.error('Failed to fetch documents:', error);
      }
    };
    const fetchProperties = async () => {
      try {
        const { data }: AxiosResponse<PropertiesAPI[]> = await axiosInstance.get('/properties/');
        setProperties(data);
      } catch (error) {
        console.error('Failed to fetch properties:', error);
      }
    };
    const fetchBids = async () => {
      try {
        const { data }: AxiosResponse<BidAPI[]> = await axiosInstance.get('/bids/');
        setBids(data);
      } catch (error) {
        console.error('Failed to fetch properties');
      }
    };
    fetchDocuments();
    fetchProperties();
    fetchBids();
  }, []);

  useEffect(() => {
    const selectedDocumentId = searchParams.get('selectedDocument');
    if (selectedDocumentId) {
      fetchDocument(parseInt(selectedDocumentId, 10));
    }
  }, [searchParams]);

  useEffect(() => {
    const fetchProperty = async () => {
      console.log(account.id);
      console.log(selectedDocument?.uploaded_by);
      console.log(
        isMyTypeDocument(selectedDocument?.uploaded_by, account.id, selectedDocument.document_type),
      );
      const url = isMyTypeDocument(
        selectedDocument?.uploaded_by,
        account.id,
        selectedDocument.document_type,
      )
        ? `/properties/${selectedDocument.property}/`
        : `/properties/${selectedDocument.property}/?search=1`;
      try {
        const { data }: AxiosResponse<PropertiesAPI> = await axiosInstance.get(url);
        setSelectedPropertyForDocument(data);
      } catch (error) {
        try {
          const other_url =
            url === `/properties/${selectedDocument.property}/`
              ? `/properties/${selectedDocument.property}/?search=1`
              : `/properties/${selectedDocument.property}/`;
          const { data }: AxiosResponse<PropertiesAPI> = await axiosInstance.get(other_url);
          setSelectedPropertyForDocument(data);
        } catch (error) {}
      }
    };

    fetchProperty();
  }, [selectedDocument]);

  console.log(documents);

  const fetchDocument = async (documentId: number) => {
    try {
      const response = await axiosInstance.get(`/documents/retrieve/?docId=${documentId}`);
      if (response?.data) {
        setSelectedDocument(response.data);
      }
    } catch (error) {
      setSelectedDocument(null);
      console.error('Failed to fetch document:', error);
    }
  };

  const getDocumentPaneComponent = (selectedDocument: DocumentAPI) => {
    console.log(selectedDocument?.document_type);
    if (!selectedDocument) {
      return (
        <Box
          sx={{
            flexGrow: 1,
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'center',
            alignItems: 'center',
            p: 3,
            color: 'grey.500',
          }}
        >
          <ArticleIcon sx={{ fontSize: 80, mb: 2 }} />
          <Typography variant="h6">Select a document to view</Typography>
          <Typography variant="body2">
            Click on a document from the left panel to get started.
          </Typography>
        </Box>
      );
    } else if (selectedDocument.document_type === 'seller_disclosure') {
      console.log(selectedDocument);
      return (
        <SellerDisclosureDisplay
          disclosureData={selectedDocument.sub_document}
          property={selectedPropertyForDocument}
        />
      );
    } else if (selectedDocument.document_type === 'home_improvement_receipt') {
      return (
        <HomeImprovementReceiptDisplay
          receiptData={selectedDocument.sub_document}
          property={selectedDocument.property}
        />
      );
    } else if (selectedDocument.document_type === 'offer_letter') {
      return (
        <OfferNegotiationHistory
          property={selectedPropertyForDocument}
          isPropertyOwner={selectedDocument?.uploaded_by !== account?.id}
          offerData={selectedDocument}
        />
        // <OfferDisplay
        //   offerData={selectedDocument.sub_document}
        //   property={selectedPropertyForDocument}
        //   isPropertyOwner={selectedDocument?.uploaded_by !== account?.id}
        //   documentId={selectedDocument.id}
        // />
      );
    } else {
      return <Typography>Not sure what this is</Typography>;
    }
  };

  if (accountLoading) {
    return <DashboardLoading />;
  } else if (!account) {
    return <DashboardErrorPage />;
  }

  return (
    <Container
      maxWidth="lg"
      sx={{ py: 4, minHeight: '100vh', display: 'flex', flexDirection: 'column' }}
    >
      <Paper
        elevation={3}
        sx={{ flexGrow: 1, display: 'flex', borderRadius: 3, overflow: 'hidden' }}
      >
        <Grid container sx={{ height: '100%' }}>
          {/* Left Panel: Document 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' }}>
                  Documents
                </Typography>
                <Button
                  variant="contained"
                  color="primary"
                  sx={{ ml: 'auto', mb: 0 }}
                  onClick={() => setShowDialog(true)}
                >
                  Create
                </Button>
              </Stack>
            </Box>
            <List sx={{ flexGrow: 1, overflowY: 'auto', p: 1 }}>
              {documents.length === 0 ? (
                <Box sx={{ p: 2, textAlign: 'center', color: 'grey.500' }}>
                  <ArticleIcon sx={{ fontSize: 40, mb: 1 }} />
                  <Typography>There are no documents yet.</Typography>
                </Box>
              ) : (
                documents
                  .sort(
                    (a, b) => new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime(),
                  )
                  .map((document) => (
                    <ListItem
                      key={document.id}
                      button
                      selected={selectedDocument?.id === document.id}
                      onClick={() => fetchDocument(document.id)}
                      sx={{ py: 1.5, px: 2 }}
                    >
                      <ListItemText
                        primary={
                          <Typography variant="subtitle1" sx={{ fontWeight: 'medium' }}>
                            {getDocumentTitle(document.document_type)}
                          </Typography>
                        }
                        secondary={
                          <Box
                            sx={{
                              display: 'flex',
                              justifyContent: 'space-between',
                              alignItems: 'center',
                            }}
                          >
                            <Typography
                              variant="body2"
                              color="text.secondary"
                              noWrap
                              sx={{ flexGrow: 1, pr: 1 }}
                            >
                              {document.description}
                            </Typography>
                            <Typography variant="caption" color="text.disabled">
                              {formatTimestamp(document.updated_at)}
                            </Typography>
                          </Box>
                        }
                      />
                    </ListItem>
                  ))
              )}
            </List>
          </Grid>
          {/* Right Panel: Offer Detail */}
          <Grid size={{ xs: 12, md: 8 }} sx={{ display: 'flex', flexDirection: 'column' }}>
            {getDocumentPaneComponent(selectedDocument)}
          </Grid>
        </Grid>
        <AddDocumentDialog
          showDialog={showDialog}
          closeDialog={closeDialog}
          account={account}
          properties={properties}
          bids={bids}
        />
      </Paper>
    </Container>
  );
};

export default DocumentManager;
