'use client';

import { pdf } from '@react-pdf/renderer';

import Button from '@/components/Button';
import { Icon } from '@iconify/react';
import ExpensePDF from '@/components/pages/expense/pdf/ExpensePDF';

import { Expense } from '@/types/api/expense';

interface ExpensePDFPreviewButtonProps {
  expense?: Expense;
}

const ExpensePDFPreviewButton = ({ expense }: ExpensePDFPreviewButtonProps) => {
  const openPdf = async () => {
    const expensePdfBlob = await pdf(<ExpensePDF expense={expense} />).toBlob();

    const expensePdfUrl = URL.createObjectURL(expensePdfBlob);
    window.open(expensePdfUrl, '_blank');
  };

  const downloadPdf = async () => {
    const blob = await pdf(<ExpensePDF expense={expense} />).toBlob();
    const url = URL.createObjectURL(blob);

    const link = document.createElement('a');
    link.href = url;
    link.download = `${expense?.po_number}.pdf`;
    link.click();

    URL.revokeObjectURL(url);
  };

  return (
    <div className='w-fit flex flex-col'>
      <Button onClick={downloadPdf} className='text-xs'>
        <Icon icon='bx:file' width={16} height={16} />
        {expense?.po_number}
      </Button>

      <Button
        onClick={openPdf}
        variant='link'
        className='p-0 mt-1 text-xs justify-start'
      >
        Lihat Dokumen
      </Button>
    </div>
  );
};

export default ExpensePDFPreviewButton;
