'use client';

import Container from '@mui/material/Container';

import { paths } from '@/routes/paths';
import React, { useEffect, useState } from 'react';
import { _invoices } from '@/shared/_mock';
import { useSettingsContext } from '@/shared/components/settings';
import CustomBreadcrumbs from '@/shared/components/custom-breadcrumbs';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { fetchInvoiceById} from '@/shared/api/invoice';
import InvoiceNewEditForm from '../invoice-new-edit-form';
import { IInvoice, IInvoiceClient} from '@/shared/types/invoice';
import InvoiceLayout from './invoice-layout';

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

type Props = {
  id: string;
};

export default function InvoiceEditView({ id }: Props) {
  const settings = useSettingsContext();
  const [currentInvoice, setCurrentInvoice] = useState<IInvoice | undefined>(undefined);



  useEffect(() => {
    const fetchInvoice = async () => {
      try {
        const invoiceData = await fetchInvoiceById(id);
        setCurrentInvoice(invoiceData);
        console.log("CurrentInvoice-->", invoiceData);
      } catch (error) {
        console.error('Failed to fetch invoice:', error);
      }
    };
    fetchInvoice();
  }, [id]);



  return (
    <InvoiceLayout>
    <LocalizationProvider dateAdapter={AdapterDateFns}>
        <Container maxWidth={settings.themeStretch ? false : 'lg'}>
        <CustomBreadcrumbs
            heading="Edit"
            links={[
            {
              name: 'Dashboard',
              href: paths.dashboard.root,
            },
            {
              name: 'Invoice',
              href: paths.dashboard.invoice.root,
            },
            {
              name: currentInvoice?.invoiceNumber
            },
            ]}
            sx={{
            mb: { xs: 3, md: 5 },
            }}
        />
        <InvoiceNewEditForm currentInvoice={currentInvoice}  />
        </Container>
    </LocalizationProvider>
    </InvoiceLayout>
  );
}
