/* eslint-disable react-hooks/exhaustive-deps */
import Box from '@mui/material/Box';
import CircularProgress from '@mui/material/CircularProgress';
import DialogContent from '@mui/material/DialogContent';
import { enqueueSnackbar } from 'notistack';
import { useEffect, useState } from 'react';
import DialogUmum from 'src/shared/components/dialog/DialogUmum';
import { useAppSelector } from 'src/store';
import { useCetakBulanan } from '../../../cetakpdf';

interface ModalCetakPdfDnProps {
  payload?: Record<string, any>;
  isOpen: boolean;
  onClose: () => void;
}

const ModalCetakPdfBulanan: React.FC<ModalCetakPdfDnProps> = ({ payload, isOpen, onClose }) => {
  const [pdfUrl, setPdfUrl] = useState<string | null>(null);
  const [loading, setLoading] = useState<boolean>(false);
  const AppSelector = useAppSelector((selector) => selector.user.data);

  const { mutateAsync } = useCetakBulanan({
    onError: (error: any) => {
      enqueueSnackbar(error?.message || 'Gagal memuat PDF', { variant: 'error' });
      setLoading(false);
    },
    onSuccess: (res: any) => {
      const fileUrl = res?.url || res?.data?.url;
      if (!fileUrl) {
        enqueueSnackbar('URL PDF tidak ditemukan di respons API', { variant: 'warning' });
        setLoading(false);
        return;
      }
      setPdfUrl(fileUrl);
      setLoading(false);
      enqueueSnackbar(res?.MsgStatus || 'PDF berhasil dibentuk', { variant: 'success' });
    },
  });

  useEffect(() => {
    const runCetak = async () => {
      if (!isOpen || !payload) return;
      setLoading(true);
      setPdfUrl(null);

      try {
        console.log('Payload final cetak PDF:', payload);
        await mutateAsync({
          ...payload,
          npwpPemotong: AppSelector.npwp_trial,
          namaPemotong: AppSelector.company_name,
          nitkuPemotong: AppSelector.nitku_trial,
          namaPenandatangan: AppSelector.signer,
        } as any);
      } catch (err) {
        console.error('❌ Error cetak PDF:', err);
        enqueueSnackbar('Gagal generate PDF', { variant: 'error' });
        setLoading(false);
      }
    };

    runCetak();
  }, [isOpen, payload, mutateAsync]);

  return (
    <DialogUmum
      maxWidth="lg"
      isOpen={isOpen}
      onClose={onClose}
      title="Detail Bupot Unifikasi (PDF)"
    >
      <DialogContent classes={{ root: 'p-16 sm:p-24' }}>
        {loading && (
          <Box display="flex" justifyContent="center" alignItems="center" height="60vh">
            <CircularProgress />
          </Box>
        )}

        {!loading && pdfUrl && (
          <iframe
            src={pdfUrl}
            style={{
              width: '100%',
              height: '80vh',
              border: 'none',
              borderRadius: 8,
            }}
            title="Preview PDF Bupot"
          />
        )}

        {!loading && !pdfUrl && (
          <Box textAlign="center" color="text.secondary" py={4}>
            PDF tidak tersedia untuk ditampilkan.
          </Box>
        )}
      </DialogContent>
    </DialogUmum>
  );
};

export default ModalCetakPdfBulanan;
