import * as Yup from 'yup';
import React, { useMemo, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import { Resolver } from 'react-hook-form';
import Card from '@mui/material/Card';
import Stack from '@mui/material/Stack';
import LoadingButton from '@mui/lab/LoadingButton';

import { paths } from '@/routes/paths';
import { useRouter } from '@/hooks';

import { useBoolean } from '@/hooks/use-boolean';

import { _addressBooks } from '@/shared/_mock';

import FormProvider from '@/shared/components/hook-form';

import { IInvoice, IInvoiceClient } from '@/shared/types/invoice';

import InvoiceNewEditDetails from './invoice-new-edit-details';
import InvoiceNewEditAddress from './invoice-new-edit-address';
import InvoiceNewEditStatusDate from './invoice-new-edit-status-date';
import { updateInvoice } from '@/shared/api/invoice';
import {enqueueSnackbar} from "notistack"; // Import de la fonction API




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

type Props = {
  currentInvoice?: IInvoice;
  signatureUrl?:string;
};

export default function InvoiceNewEditForm({ currentInvoice }: Props) {
  const router = useRouter();

  const loadingSave = useBoolean();

  const loadingSend = useBoolean();

  const NewInvoiceSchema = Yup.object().shape({
    invoiceClient: Yup.mixed<any>().nullable().required('Invoice to is required'),
    createDate: Yup.mixed<any>().nullable().required('Create date is required'),
    dueDate: Yup.mixed<any>()
      .required('Due date is required')
      .test(
        'date-min',
        'Due date must be later than create date',
        (value, { parent }) => value.getTime() > parent.createDate.getTime()
      ),
    productLine: Yup.lazy(() =>
      Yup.array().of(
        Yup.object({
          title: Yup.string().required('Title is required'),
          quantity: Yup.number()
            .required('Quantity is required')
            .min(1, 'Quantity must be more than 0'),
        })
      )
    ),
    taxes: Yup.number(),
    notes:Yup.string(),
    devise: Yup.string().required('Devise is required'),
    paymentMode: Yup.object().shape({
      id: Yup.number(),
      name: Yup.string().required('Payment mode name is required'),
    }).required('Payment mode is required'),
    status: Yup.string(),
    invoiceIssuer: Yup.number(),
    totalAmount: Yup.number(),
    agencyId: Yup.number(),
    invoiceNumber: Yup.string(),
    signatureUrl: Yup.string().nullable(),
    signatureUrlS3:Yup.string().nullable(),
    subTotal : Yup.number(),
    responsibleId: Yup.number(),

  });

  const defaultValues = useMemo(
    () => ({
      id: currentInvoice?.id || 0,
      invoiceNumber: currentInvoice?.invoiceNumber || '',
      createDate: currentInvoice?.createDate || new Date(),
      dueDate: currentInvoice?.dueDate || null,
      taxes: currentInvoice?.taxes || 0,
      status: currentInvoice?.status || 'draft',
      invoiceIssuer: currentInvoice?.invoiceIssuer || 2,
      invoiceClient: currentInvoice?.invoiceClient || null,
      productLine: currentInvoice?.productLine || [
        {
          title: '',
          description: '',
          quantity: 1,
          price: 0,
          total: 0,
        },
      ],
      totalAmount: currentInvoice?.totalAmount || 0,
      subTotal: currentInvoice?.subTotal || 0,
      signatureUrl: currentInvoice?.signatureUrl || null,
      signatureUrlS3:currentInvoice?.signatureUrlS3|| null,
      responsibleId: currentInvoice?.responsibleId ?? undefined,
      agencyId: currentInvoice?.agencyId ?? undefined,
      notes: currentInvoice?.notes || '',
      paymentMode: currentInvoice?.paymentMode || { id: '', name: '' },
      devise:currentInvoice?.devise || '',
      

    }),
    [currentInvoice]
  );

  const methods = useForm<IInvoice>({
    resolver: yupResolver(NewInvoiceSchema) as unknown as Resolver<IInvoice>,
    defaultValues: defaultValues as IInvoice,
  });

  const {
    reset,

    handleSubmit,
    formState: { isSubmitting },
  } = methods;

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

  useEffect(() => {
    if (currentInvoice) {
      reset({
        invoiceNumber: currentInvoice.invoiceNumber,
        createDate: currentInvoice.createDate ? new Date(currentInvoice.createDate) : new Date(),
        dueDate: currentInvoice.dueDate ? new Date(currentInvoice.dueDate) : undefined,
        taxes: currentInvoice.taxes,
        status: currentInvoice.status,
        invoiceIssuer: currentInvoice.invoiceIssuer,
        invoiceClient: currentInvoice.invoiceClient,
        productLine: currentInvoice.productLine,
        totalAmount: currentInvoice.totalAmount,
        subTotal: currentInvoice.subTotal,
        signatureUrl: currentInvoice.signatureUrl,
        responsibleId: currentInvoice.responsibleId,
        agencyId:currentInvoice.agencyId,
        signatureUrlS3: currentInvoice.signatureUrlS3,
        notes: currentInvoice.notes,
        paymentMode: currentInvoice.paymentMode,
        devise: currentInvoice.devise,
      });
    }
  }, [currentInvoice, reset]);


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

  const handleSaveAsDraft = handleSubmit(async (data) => {
    loadingSave.onTrue();

    try {
      await new Promise((resolve) => setTimeout(resolve, 500));
      reset();
      loadingSave.onFalse();
      router.push(paths.dashboard.invoice.root);
      console.info('DATA', JSON.stringify(data, null, 2));
    } catch (error) {
      console.error(error);
      loadingSave.onFalse();
    }
  });

 
  const handleUpdateInvoice = handleSubmit(async (data: any) => {
    loadingSave.onTrue();
    try {
      if (currentInvoice && currentInvoice.id) {
        const invoiceData: IInvoice = {
          ...data,
          id: currentInvoice.id, 
        };
        await updateInvoice(Number(currentInvoice.id), invoiceData);
        enqueueSnackbar('Invoice updated successfully!', { variant: 'success' });
        router.push(paths.dashboard.invoice.root);
      } else {
        throw new Error('No invoice to update');
      }
    } catch (error) {
      console.error('Error updating invoice:', error);
      enqueueSnackbar('Error updating invoice', { variant: 'error' });
    } finally {
      loadingSave.onFalse();
    }
  });
  


  return (
    <FormProvider methods={methods}>
      <Card>
        <InvoiceNewEditAddress />

        <InvoiceNewEditStatusDate isEdit={ true}/>

        <InvoiceNewEditDetails  />
      </Card>

      <Stack justifyContent="flex-end" direction="row" spacing={2} sx={{ mt: 3 }}>
        <LoadingButton
          color="inherit"
          size="large"
          variant="outlined"
          loading={loadingSave.value && isSubmitting}
          onClick={handleSaveAsDraft}
        >
          Cancel
        </LoadingButton>

        <LoadingButton
          size="large"
          variant="contained"
          loading={loadingSend.value && isSubmitting}
          onClick={handleUpdateInvoice}
        >
          {currentInvoice ? 'Update' : 'Create'}
        </LoadingButton>
      </Stack>
    </FormProvider>
  );
}
