// import { zodResolver } from '@hookform/resolvers/zod';
// import Grid from '@mui/material/Grid';
// import { useQueryClient } from '@tanstack/react-query';
// import type { GridRowSelectionModel } from 'node_modules/@mui/x-data-grid/esm/models/gridRowSelectionModel';
// import type React from 'react';
// import { useState } from 'react';
// import { FormProvider, useForm } from 'react-hook-form';
// import { Field } from 'src/components/hook-form';
// import DialogProgressBar from 'src/shared/components/dialog/DialogProgressBar';
// import DialogUmum from 'src/shared/components/dialog/DialogUmum';
// import useDialogProgressBar from 'src/shared/hooks/useDialogProgressBar';
// import z from 'zod';
// import { LoadingButton } from '@mui/lab';
// import Stack from '@mui/material/Stack';
// import { enqueueSnackbar } from 'notistack';
// import type { TUploadFakturPMRequest } from '../../types/types';
// import usePrepopulatedPM from '../../hooks/usePrepopulatedPM';

// interface ModalPrepopulatedFakturProps {
//   dataSelected?: GridRowSelectionModel;
//   setSelectionModel?: React.Dispatch<React.SetStateAction<GridRowSelectionModel | undefined>>;
//   tableApiRef?: React.MutableRefObject<any>;
//   isOpenDialogUpload: boolean;
//   setIsOpenDialogUpload: (v: boolean) => void;
//   successMessage?: string;
//   onConfirmUpload?: () => Promise<void> | void;
// }
// const ModalPrepolulatedPM: React.FC<ModalPrepopulatedFakturProps> = ({
//   dataSelected,
//   setSelectionModel,
//   tableApiRef,
//   isOpenDialogUpload,
//   setIsOpenDialogUpload,
//   successMessage = 'Data berhasil diupload',
//   onConfirmUpload,
// }) => {
//   const queryClient = useQueryClient();

//   const [isOpenDialogProgressBar, setIsOpenDialogProgressBar] = useState(false);

//   const {
//     numberOfData,
//     setNumberOfData,
//     numberOfDataFail,
//     numberOfDataProcessed,
//     numberOfDataSuccess,
//     processSuccess,
//     processFail,
//     resetToDefault,
//     status,
//   } = useDialogProgressBar();

//   const schema = z.object({
//     masaTahunPajak: z.string().min(1, 'Masa tahun pajak wajib diisi'), // karena DatePicker output string
//   });

//   const methods = useForm({
//     mode: 'all',
//     resolver: zodResolver(schema),
//   });

//   const { handleSubmit } = methods;

//   const { mutateAsync, isPending } = usePrepopulatedPM({
//     onSuccess: () => {
//       enqueueSnackbar('Berhasil unduh faktur', { variant: 'success' });
//     },
//     onError: (err) => {
//       enqueueSnackbar(err.message || 'Gagal unduh faktur', { variant: 'error' });
//     },
//   });

//   const onSubmit = async (values: { masaTahunPajak: string }) => {
//     const [masaPajak, tahunPajak] = values.masaTahunPajak.split('/');

//     await mutateAsync({
//       fgPermintaan: 1,
//       requestFakturMasukan: {
//         masaPajak,
//         tahunPajak,
//       },
//     });
//   };

//   const handleCloseModal = () => {
//     setIsOpenDialogUpload(false);
//     resetToDefault();
//   };

//   const onSubmit = async (values: { masaTahunPajak: string }) => {
//     try {
//       setIsOpenDialogProgressBar(true);

//       // contoh payload (sesuaikan dengan API kamu)
//       const payload: TUploadFakturPMRequest = {
//         fgPermintaan: 2,
//         masaTahunPajak: values.masaTahunPajak,
//         // tambahkan field lain jika perlu
//       };

//       await mutateAsync(payload);
//     } finally {
//       queryClient.invalidateQueries({ queryKey: ['upload-prepop-faktur-pm'] });
//     }
//   };

//   return (
//     <>
//       <FormProvider {...methods}>
//         <DialogUmum
//           isOpen={isOpenDialogUpload}
//           onClose={handleCloseModal}
//           title="Apakah Anda yakin ingin mengubah data menjadi Credit?"
//           maxWidth="sm"
//         >
//           <Grid size={{ md: 12 }}>
//             <Field.DatePicker
//               name="masaTahunPajak"
//               label="Masa Pajak"
//               slotProps={{ textField: { helperText: '' } }}
//               views={['year', 'month']} // urutan views tampil sesuai array
//               openTo="month" // buka langsung ke bulan
//               format="MM/YYYY" // untuk menampilkan di input
//             />
//           </Grid>

//           <Stack direction="row" justifyContent="end" spacing="16px">
//             <LoadingButton
//               onClick={handleCloseModal}
//               variant="text"
//               sx={{
//                 fontSize: '14px',
//               }}
//               size="medium"
//             >
//               Tutup
//             </LoadingButton>

//             <LoadingButton
//               // onClick={handleSubmit(handleSubmit)}
//               type="button"
//               variant="text"
//               size="medium"
//               sx={{
//                 fontSize: '14px',
//               }}
//               // loading={isLoading}
//             >
//               Unduh Faktur
//             </LoadingButton>
//           </Stack>
//         </DialogUmum>
//       </FormProvider>

//       <DialogProgressBar
//         isOpen={isOpenDialogProgressBar}
//         handleClose={() => {
//           handleCloseModal();
//           setIsOpenDialogProgressBar(false);
//         }}
//         numberOfData={numberOfData}
//         numberOfDataProcessed={numberOfDataProcessed}
//         numberOfDataFail={numberOfDataFail}
//         numberOfDataSuccess={numberOfDataSuccess}
//         status={status}
//       />
//     </>
//   );
// };

// export default ModalPrepolulatedPM;

import { zodResolver } from '@hookform/resolvers/zod';
import Grid from '@mui/material/Grid';
import { useQueryClient } from '@tanstack/react-query';
import type { GridRowSelectionModel } from '@mui/x-data-grid-premium';
import type React from 'react';
import { useState } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import { Field } from 'src/components/hook-form';
import DialogProgressBar from 'src/shared/components/dialog/DialogProgressBar';
import DialogUmum from 'src/shared/components/dialog/DialogUmum';
import useDialogProgressBar from 'src/shared/hooks/useDialogProgressBar';
import z from 'zod';
import { LoadingButton } from '@mui/lab';
import Stack from '@mui/material/Stack';
import { enqueueSnackbar } from 'notistack';
import usePrepopulatedPM from '../../hooks/usePrepopulatedPM';
import dayjs from 'dayjs';

interface ModalPrepopulatedFakturProps {
  dataSelected?: GridRowSelectionModel;
  setSelectionModel?: React.Dispatch<React.SetStateAction<GridRowSelectionModel | undefined>>;
  tableApiRef?: React.MutableRefObject<any>;
  isOpenDialogUpload: boolean;
  setIsOpenDialogUpload: (v: boolean) => void;
  successMessage?: string;
  onConfirmUpload?: () => Promise<void> | void;
}

/* -------------------------------------------------------------------------- */
/*                                    Schema                                  */
/* -------------------------------------------------------------------------- */
const schema = z.object({
  masaTahunPajak: z.string().min(1, 'Masa tahun pajak wajib diisi'),
});

type FormValues = z.infer<typeof schema>;

const ModalPrepolulatedPM: React.FC<ModalPrepopulatedFakturProps> = ({
  isOpenDialogUpload,
  setIsOpenDialogUpload,
  successMessage = 'Berhasil unduh faktur',
  onConfirmUpload,
}) => {
  const queryClient = useQueryClient();
  const [isOpenDialogProgressBar, setIsOpenDialogProgressBar] = useState(false);

  const {
    numberOfData,
    setNumberOfData,
    numberOfDataFail,
    numberOfDataProcessed,
    numberOfDataSuccess,
    processSuccess,
    processFail,
    resetToDefault,
    status,
  } = useDialogProgressBar();

  const methods = useForm<FormValues>({
    mode: 'all',
    resolver: zodResolver(schema),
    defaultValues: {
      masaTahunPajak: '',
    },
  });

  const { handleSubmit } = methods;

  const { mutateAsync, isPending } = usePrepopulatedPM({
    onSuccess: () => {
      processSuccess();
      enqueueSnackbar(successMessage, { variant: 'success' });
    },
    onError: (err) => {
      processFail();
      enqueueSnackbar(err.message || 'Gagal unduh faktur', {
        variant: 'error',
      });
    },
  });

  /* -------------------------------------------------------------------------- */
  /*                                   Submit                                   */
  /* -------------------------------------------------------------------------- */
  const onSubmit = async (values: FormValues) => {
    const d = dayjs(values.masaTahunPajak);

    if (!d.isValid()) {
      enqueueSnackbar('Masa pajak tidak valid', { variant: 'error' });
      return;
    }

    const payload = {
      fgPermintaan: 1,
      requestFakturMasukan: {
        tahunPajak: d.format('YYYY'),
        masaPajak: d.format('MM'),
      },
    };

    try {
      // 🔥 WAJIB buka dulu
      setIsOpenDialogProgressBar(true);
      setNumberOfData(1);

      await mutateAsync(payload);

      await onConfirmUpload?.();
    } catch {
      // error sudah ditangani di hook
    } finally {
      queryClient.invalidateQueries({
        queryKey: ['prepopulated-faktur-pm'],
      });
    }
  };

  const handleCloseModal = () => {
    setIsOpenDialogUpload(false);
    resetToDefault();
  };

  return (
    <>
      <FormProvider {...methods}>
        <DialogUmum
          isOpen={isOpenDialogUpload}
          onClose={handleCloseModal}
          title="Unduh Faktur Prepopulated"
          maxWidth="sm"
        >
          <Grid size={{ md: 12 }} sx={{ mt: 2 }}>
            <Field.DatePicker
              name="masaTahunPajak"
              label="Masa Pajak"
              slotProps={{ textField: { helperText: '' } }}
              views={['year', 'month']}
              openTo="month"
              format="MM/YYYY"
              maxDate={dayjs()}
            />
          </Grid>

          <Stack direction="row" justifyContent="end" spacing="16px" mt={3}>
            <LoadingButton onClick={handleCloseModal} variant="text" size="medium">
              Tutup
            </LoadingButton>

            <LoadingButton
              onClick={handleSubmit(onSubmit)}
              loading={isPending}
              variant="contained"
              size="medium"
            >
              Unduh Faktur
            </LoadingButton>
          </Stack>
        </DialogUmum>
      </FormProvider>

      <DialogProgressBar
        isOpen={isOpenDialogProgressBar}
        handleClose={() => {
          handleCloseModal();
          setIsOpenDialogProgressBar(false);
        }}
        numberOfData={numberOfData}
        numberOfDataProcessed={numberOfDataProcessed}
        numberOfDataFail={numberOfDataFail}
        numberOfDataSuccess={numberOfDataSuccess}
        status={status}
      />
    </>
  );
};

export default ModalPrepolulatedPM;
