'use client';

import Container from '@mui/material/Container';
import { useEffect, useState } from 'react';
import { paths } from '@/routes/paths';
import { _invoices } from '@/shared/_mock';
import { useSettingsContext } from '@/shared/components/settings';
import CustomBreadcrumbs from '@/shared/components/custom-breadcrumbs';
import InvoiceDetails from '../invoice-details';
import { fetchInvoiceById,downloadSignature } from '@/shared/api/invoice';
import { IInvoice, IInvoiceClient} from '@/shared/types/invoice';
import InvoiceLayout from './invoice-layout';


// ----------------------------------------------------------------------

type Props = {
  id: string;
};

export default function InvoiceDetailsView({ id }: Props) {
  const settings = useSettingsContext();
  const [invoice, setInvoice] = useState<IInvoice | null>(null);
  const [invoiceIssuer, setInvoiceIssuer] = useState<IInvoiceClient | undefined>(undefined);
  const [signatureUrl, setSignatureUrl] = useState<string>('');

 
  useEffect(() => {
    const fetchInvoice = async () => {
      try {
        const invoiceData = await fetchInvoiceById(id);
        setInvoice(invoiceData);

       
      
        if (invoiceData.signatureUrl) {
          const signature = await downloadSignature(invoiceData.signatureUrl);
          setSignatureUrl(signature);
          console.log("Succes to fetch signature file");
        }
      } catch (error) {
        console.error('Failed to fetch signature file:', error);
      }
    };

    fetchInvoice();
  }, [id]);

  return (
    <InvoiceLayout>
    <Container maxWidth={settings.themeStretch ? false : 'lg'}>
      <CustomBreadcrumbs
        heading={invoice?.invoiceNumber}
        links={[
          {
            name: 'Dashboard',
            href: paths.dashboard.root,
          },
          {
            name: 'Invoice',
            href: paths.dashboard.invoice.root,
          },
          { name: invoice?.invoiceNumber || 'Invoice Details' },
        ]}
        sx={{ mb: { xs: 3, md: 5 } }}
      />
      {invoice && <InvoiceDetails invoice={invoice} invoiceIssuer={invoiceIssuer} signatureUrl={signatureUrl} />}
    </Container>
    </InvoiceLayout>
  );
}