import React, { useMemo } from 'react';
import DialogConfirm from 'src/shared/components/dialog/DialogConfirm';
import type { GridRowSelectionModel } from '@mui/x-data-grid-premium';
import { useNavigate } from 'react-router-dom';
// import { useNavigate } from 'react-router';

interface ModalReturFakturProps {
  dataSelected?: GridRowSelectionModel;
  setSelectionModel?: React.Dispatch<React.SetStateAction<GridRowSelectionModel | undefined>>;
  tableApiRef?: React.MutableRefObject<any>;
  isOpenDialogCancel: boolean;
  setIsOpenDialogCancel: (v: boolean) => void;
  type?: 'retur' | 'ubah';
}

/**
 * Ambil single ID dari berbagai bentuk rowSelectionModel
 */
const getSingleId = (sel?: any): string | null => {
  if (!sel) return null;

  if (Array.isArray(sel)) {
    return sel[0]?.toString() ?? null;
  }

  if (sel instanceof Set) {
    return Array.from(sel)[0]?.toString() ?? null;
  }

  if (sel?.ids instanceof Set) {
    return Array.from(sel.ids)[0]?.toString() ?? null;
  }

  return null;
};

const ModalReturDokumenLainMasukan: React.FC<ModalReturFakturProps> = ({
  dataSelected,
  setSelectionModel,
  tableApiRef,
  isOpenDialogCancel,
  setIsOpenDialogCancel,
  type = 'retur',
}) => {
  const navigate = useNavigate();

  const selectedId = useMemo(() => getSingleId(dataSelected), [dataSelected]);

  const handleCloseModal = () => {
    setIsOpenDialogCancel(false);
  };

  const clearSelection = () => {
    tableApiRef?.current?.setRowSelectionModel?.([]);
    setSelectionModel?.(undefined);
  };

  const handleSubmit = () => {
    console.log('dataSelected:', dataSelected);
    console.log('selectedId:', selectedId);
    if (!selectedId) return;

    handleCloseModal();
    clearSelection();

    navigate(`/faktur/dokumen-lain/pajak-masukan/${selectedId}/${type}`);
  };

  return (
    <DialogConfirm
      fullWidth
      maxWidth="xs"
      title="Apakah Anda yakin akan melakukan Retur Dokumen Lain Masukan ?"
      description=""
      actionTitle="Iya"
      isOpen={isOpenDialogCancel}
      isLoadingBtnSubmit={false}
      handleClose={handleCloseModal}
      handleSubmit={handleSubmit}
    />
  );
};

export default ModalReturDokumenLainMasukan;
