import React, { useEffect, useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { enqueueSnackbar } from 'notistack';
import DialogProgressBar from 'src/shared/components/dialog/DialogProgressBar';
import useDialogProgressBar from 'src/shared/hooks/useDialogProgressBar';
import type { GridRowSelectionModel } from '@mui/x-data-grid-premium';
import DialogUmum from 'src/shared/components/dialog/DialogUmum';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import Alert from '@mui/material/Alert';
import Typography from '@mui/material/Typography';
import { usePostCreditUncredited } from '../../hooks/usePostCreditUncredited';
// import usePostCreditUncredited from '../../hooks/usePostCreditUncredited';

interface ModalUploadCreditedProps {
  dataSelected?: GridRowSelectionModel;
  tableApiRef?: React.MutableRefObject<any>;
  isOpenDialogUpload: boolean;
  setIsOpenDialogUpload: (v: boolean) => void;
  statusPembeli: 'CREDITED' | 'UNCREDITED' | 'INVALID';
  successMessage?: string;
  onConfirmUpload?: () => Promise<void> | void;
}

/** normalize selection MUI */
const normalizeSelection = (sel?: any): (number | string)[] => {
  if (!sel) return [];
  if (Array.isArray(sel)) return sel;
  if (sel?.ids instanceof Set) return Array.from(sel.ids);
  return [];
};

const ModalUploadCreditedDokumenLainMasukan: React.FC<ModalUploadCreditedProps> = ({
  dataSelected,
  tableApiRef,
  isOpenDialogUpload,
  setIsOpenDialogUpload,
  onConfirmUpload,
  statusPembeli,
  successMessage = 'Status dokumen berhasil diperbarui',
}) => {
  const queryClient = useQueryClient();
  const [openProgress, setOpenProgress] = useState(false);

  const {
    numberOfData,
    setNumberOfData,
    numberOfDataFail,
    numberOfDataProcessed,
    numberOfDataSuccess,
    processSuccess,
    processFail,
    resetToDefault,

    status,
  } = useDialogProgressBar();

  const { mutateAsync, isPending } = usePostCreditUncredited({
    onSuccess: () => processSuccess(),
    onError: () => processFail(),
  });

  const ids = normalizeSelection(dataSelected);

  const handleSubmit = async () => {
    try {
      setOpenProgress(true);
      setNumberOfData(ids.length);

      const promises = ids.map((id) =>
        mutateAsync({
          id: Number(id),
          statusPembeli,
        })
      );

      await Promise.allSettled(promises);
      await onConfirmUpload?.();

      enqueueSnackbar(successMessage, { variant: 'success' });
    } catch (err: any) {
      enqueueSnackbar(err?.message || 'Gagal memproses data', { variant: 'error' });
    } finally {
      queryClient.invalidateQueries({ queryKey: ['dokumen-lain-masukan'] });
    }
  };

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

  useEffect(() => {
    setNumberOfData(ids.length);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isOpenDialogUpload, dataSelected]);

  return (
    <>
      <DialogUmum
        isOpen={isOpenDialogUpload}
        onClose={handleClose}
        title="Apakah Anda yakin ingin mengubah status dokumen?"
        maxWidth="sm"
      >
        <Stack spacing={2}>
          <Alert severity="warning">
            <Typography variant="body2">
              Status dokumen akan diubah menjadi <b>{statusPembeli}</b>.
            </Typography>
          </Alert>

          <Stack direction="row" justifyContent="flex-end" spacing={1}>
            <Button variant="contained" onClick={handleClose}>
              Tidak
            </Button>
            <Button variant="contained" loading={isPending} onClick={handleSubmit}>
              Ya, Lanjutkan
            </Button>
          </Stack>
        </Stack>
      </DialogUmum>

      <DialogProgressBar
        isOpen={openProgress}
        handleClose={() => {
          handleClose();
          setOpenProgress(false);
        }}
        numberOfData={numberOfData}
        numberOfDataProcessed={numberOfDataProcessed}
        numberOfDataFail={numberOfDataFail}
        numberOfDataSuccess={numberOfDataSuccess}
        status={status}
      />
    </>
  );
};

export default ModalUploadCreditedDokumenLainMasukan;
