import React, { useState } from 'react';
import { Dropdown } from 'react-bootstrap';
import { useRequest } from "@/components/App/request";
import { toastrC } from "@/utils/helpers";
import styles from "@/styles/Component/Dashboard/MonthlyStatement.module.scss";
import moment from 'moment';

interface DownloadDropdownProps {
  startDate: moment.Moment;
  endDate: moment.Moment;
}

const DownloadDropdown: React.FC<DownloadDropdownProps> = ({ startDate , endDate }) => {
  const [isDownloading, setIsDownloading] = useState(false);
  const { request } = useRequest();

  const handleDownload = async (format: 'pdf' | 'xlsx') => {
    setIsDownloading(true);
    try {
      
      const res = await request(
        (format == 'pdf') ? "DOWNLOAD_STATEMENT_PDF" : "DOWNLOAD_STATEMENT_EXCEL" ,
        { 
          start_date: startDate,
          end_date: endDate,
          format 
        },
        {},
        { responseType: "blob" }
      );
      
      if (!res || !(res instanceof Blob)) {
        toastrC("Invalid response, expected a Blob", "error", "error");
        return;
      }
      
      const url = window.URL.createObjectURL(res);
      const a = document.createElement("a");
      a.href = url;
      a.download = `Statement ${moment(endDate).format("YYYY-MM-DD")}.${format}`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    } catch (e) {
      console.log(e);
      toastrC("Failed to download file", "error", "error");
    } finally {
      setIsDownloading(false);
    }
  };

  return (
    <Dropdown>
      <Dropdown.Toggle 
        className={`${styles.BtnCustom} ${styles.orangeBtn}`}
        disabled={isDownloading}
      >
        {isDownloading ? "Downloading..." : "Download"}
      </Dropdown.Toggle>

      <Dropdown.Menu>
        <Dropdown.Item 
          onClick={() => handleDownload('pdf')}
          disabled={isDownloading}
        >
          Download PDF
        </Dropdown.Item>
        <Dropdown.Item 
          onClick={() => handleDownload('xlsx')}
          disabled={isDownloading}
        >
          Download Excel
        </Dropdown.Item>
      </Dropdown.Menu>
    </Dropdown>
  );
};

export default DownloadDropdown; 