import { Box, Chip, CircularProgress } from '@mui/material';
import React, { useEffect, useMemo, useState } from 'react';
import CustomModal from '../../../views/Modal/Modal';
import SimpleDataTable from '../../../components/SimpleDataTable';
import { useStyles } from './transactionHistoryPopupStyles';
import downloadIcon from '../../../assets/images/icon/downloadreciept.svg';
import pdfIcon from '../../../assets/images/icon/pdfIcon.svg';
import { NOTIFICATION, PAYMENT_STATUS } from '../../../constants';
import { getTransactionHistory } from '../../../services/transaction.history.services';
import { format } from 'date-fns';
import { fileDownloadUsingUrl } from '../../../utils/share';
import { pdf } from '@react-pdf/renderer';
import ReceiptDownload from '../../../views/ReceiptDownload';
import { pushNotification } from '../../../utils/notification';

const statusColorMap = {
  [PAYMENT_STATUS.PAYMENT_SUCCESS]: {
    color: '#12B76A',
    backgroundColor: '#ECFDF3',
  },
  [PAYMENT_STATUS.PAYMENT_FAILURE]: {
    color: '#D6313A',
    backgroundColor: '#FFF0F1',
  },
};

function TransactionHistoryPopup({ handleTransactionHistoryPopupClose }) {
  const classes = useStyles();
  const [transactionHistoryData, setTransactionHistoryData] = useState();
  const [companyDetails, setCompanyDetails] = useState();
  const [downloadingReceiptId, setDownloadingReceiptId] = useState(null);
  const [loading, setLoading] = useState(false);

  const fetchTransactionHistory = async () => {
    try {
      setLoading(true);
      const response = await getTransactionHistory();
      setTransactionHistoryData(response?.data?.data?.records);
      setCompanyDetails(response?.data?.data?.companyDetails);
    } catch (error) {
      // eslint-disable-next-line no-console
      console.log(error);
    } finally {
      setLoading(false);
    }
  };

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

  const handleReceiptDownload = async (row) => {
    setDownloadingReceiptId(row.id);
    try {
      const MyDocument = (
        <ReceiptDownload
          transactionId={row?.transactionId}
          date={row?.createdAt}
          amount={row?.amount}
          paymentMethod={row?.paymentMode}
          status={row?.status}
          email={row?.payer?.email}
          companyName={companyDetails?.name}
        />
      );

      const blob = await pdf(MyDocument).toBlob();
      const url = URL.createObjectURL(blob);

      fileDownloadUsingUrl(url, `receipt_${row.transactionId || ''}.pdf`);

      URL.revokeObjectURL(url);
    } catch (error) {
      pushNotification('Error while downloading receipt', NOTIFICATION.ERROR);
    } finally {
      setDownloadingReceiptId(null);
    }
  };

  const columns = useMemo(
    () => [
      {
        accessorKey: 'transactionId',
        header: 'Transaction ID',
        minWidth: 140,
        isBold: true,
      },
      {
        accessorKey: 'createdAt',
        header: 'Trantaction Date',
        minWidth: 160,
        Cell: ({ row }) => (
          <div>{format(new Date(row?.createdAt), 'dd MMM yyyy')}</div>
        ),
      },
      {
        accessorKey: 'amount',
        header: 'Amount',
        Cell: ({ row }) => <div>₹{row?.amount}</div>,
      },
      {
        accessorKey: 'paymentMode',
        header: 'Payment Mode',
        minWidth: 160,
        Cell: ({ row }) => (
          <>
            <div className={classes.paymentText}>
              {row?.paymentMode?.toUpperCase()}
            </div>
          </>
        ),
      },
      {
        accessorKey: 'status',
        header: 'Status',
        minWidth: 140,
        align: 'center',
        Cell: ({ row }) => (
          <Chip
            label={
              <div style={{ display: 'flex', alignItems: 'center' }}>
                {/* {capitalizeFirstLetter(row.original?.status)} */}
                {row?.status === PAYMENT_STATUS.PAYMENT_SUCCESS
                  ? 'Payment Done'
                  : 'Payment Error'}
              </div>
            }
            style={{
              backgroundColor:
                row?.status in statusColorMap
                  ? statusColorMap[row?.status].backgroundColor
                  : '#FFFFFF',
              color:
                row?.status in statusColorMap
                  ? statusColorMap[row?.status].color
                  : '#000000',
            }}
          />
        ),
      },
      {
        accessorKey: 'paymentReceipt',
        header: 'Receipt',
        align: 'center',
        width: 140,
        Cell: ({ row }) => (
          <div className={classes.receipt}>
            {downloadingReceiptId === row.id ? (
              <div>
                <CircularProgress size={30} />
              </div>
            ) : (
              row.paymentMode !== 'Offline' && (
                <div
                  className={classes.receiptOuter}
                  onClick={() => handleReceiptDownload(row)}
                >
                  <img
                    className={classes.receiptIcon}
                    src={downloadIcon}
                    alt="Download receipt"
                  />
                </div>
              )
            )}
          </div>
        ),
      },
      {
        accessorKey: 'gstInvoice',
        header: 'GST Invoice',
        align: 'center',
        minWidth: 160,
        Cell: ({ row }) => (
          <div className={classes.gst}>
            {row?.gstInvoice ? (
              <div
                className={classes.gstOuter}
                onClick={() => handleGstDownload(row)}
              >
                <img className={classes.gstIcon} src={pdfIcon} />
              </div>
            ) : (
              ''
            )}
          </div>
        ),
      },
    ],
    [classes, companyDetails, transactionHistoryData, downloadingReceiptId]
  );

  const handleGstDownload = (row) => {
    fileDownloadUsingUrl(row.gstInvoice, `GST_Invoice_${row.transactionId}`);
  };

  return (
    <CustomModal
      //   onClose={handleCloseModal}
      showCloseButton={true}
      contentScroll
      isTitleLeft={true}
      title="Transaction History"
      onClose={handleTransactionHistoryPopupClose}
      modalBodyFunction={() => (
        <Box className={classes.transactionHistoryTableWrapper}>
          <SimpleDataTable
            columns={columns}
            rows={transactionHistoryData}
            showLoader={loading}
          />
        </Box>
      )}
    />
  );
}

export default TransactionHistoryPopup;
