import React, { useEffect, useState } from 'react';
import { enqueueSnackbar } from 'notistack';
import DialogProgressBar from 'src/shared/components/dialog/DialogProgressBar';
import useDialogProgressBar from 'src/shared/hooks/useDialogProgressBar';
import DialogConfirm from 'src/shared/components/dialog/DialogConfirm';
import type { GridRowSelectionModel } from '@mui/x-data-grid-premium';

interface ModalDeleteBarangJasaProps {
  /** data yang sedang dipilih untuk dihapus */
  dataSelected?: GridRowSelectionModel;
  /** buka / tutup modal delete */
  isOpenDialogDelete: boolean;
  setIsOpenDialogDelete: (v: boolean) => void;
  /** callback setelah delete sukses */
  onConfirmDelete?: () => Promise<void> | void;
  /** pesan sukses */
  successMessage?: string;
}

/**
 * Normalisasi selection model agar selalu jadi array id
 */
const normalizeSelection = (sel?: GridRowSelectionModel): (string | number)[] => {
  if (!sel) return [];

  // ✅ v7 shape baru: { type: 'include', ids: Set(...) }
  if (typeof sel === 'object' && 'ids' in sel && sel.ids instanceof Set) {
    return Array.from(sel.ids);
  }

  // fallback untuk bentuk array lama
  if (Array.isArray(sel)) return sel;

  // fallback terakhir, kalau object key-value
  if (typeof sel === 'object') {
    return Object.keys(sel);
  }

  return [];
};

const ModalDeleteBarangJasa: React.FC<ModalDeleteBarangJasaProps> = ({
  dataSelected,
  isOpenDialogDelete,
  setIsOpenDialogDelete,
  onConfirmDelete,
  successMessage = 'Data berhasil dihapus',
}) => {
  const {
    numberOfData,
    setNumberOfData,
    numberOfDataFail,
    numberOfDataProcessed,
    numberOfDataSuccess,
    processSuccess,
    processFail,
    resetToDefault,
    status,
  } = useDialogProgressBar();

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

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

  const onSubmit = async () => {
    try {
      // setIsOpenDialogProgressBar(true);
      await onConfirmDelete?.();
      processSuccess();
      enqueueSnackbar(successMessage, { variant: 'success' });
      handleCloseModal();
    } catch (error: any) {
      processFail();
      enqueueSnackbar(error?.message || 'Gagal menghapus data', { variant: 'error' });
    }
  };

  useEffect(() => {
    setNumberOfData(normalizeSelection(dataSelected).length || 1);
  }, [isOpenDialogDelete, dataSelected, setNumberOfData]);

  return (
    <>
      <DialogConfirm
        fullWidth
        maxWidth="xs"
        title="Apakah Anda yakin ingin menghapus data ini?"
        description="Data yang sudah dihapus tidak dapat dikembalikan."
        actionTitle="Hapus"
        isOpen={isOpenDialogDelete}
        isLoadingBtnSubmit={false}
        handleClose={handleCloseModal}
        handleSubmit={onSubmit}
      />

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

export default ModalDeleteBarangJasa;
