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 dayjs from 'dayjs';
import usePrepopulatedDokumenLainMasukan from '../../hooks/usePrepopulatedDokumenLainMasukan';

interface ModalPrepopulatedDokumenLainMasukanProps {
  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 ModalPrepolulatedDokumenLainMasukan: React.FC<ModalPrepopulatedDokumenLainMasukanProps> = ({
  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 } = usePrepopulatedDokumenLainMasukan({
    onSuccess: () => {
      processSuccess();
      enqueueSnackbar(successMessage, { variant: 'success' });
    },
    onError: (err) => {
      processFail();
      enqueueSnackbar(err.message || 'Gagal unduh Dokumen Lain Masukan', {
        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 = {
      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 ModalPrepolulatedDokumenLainMasukan;
