import React, { useEffect, useState } from 'react';
import { enqueueSnackbar } from 'notistack';
import DialogUmum from 'src/shared/components/dialog/DialogUmum';
import DialogContent from '@mui/material/DialogContent';
import CircularProgress from '@mui/material/CircularProgress';
import Box from '@mui/material/Box';
import useCetakPdfDn from '../../hooks/useCetakPdfNr';
import normalizePayloadCetakPdf from '../../utils/normalizePayloadCetakPdf';

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

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

  const { mutateAsync } = useCetakPdfDn({
    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 {
        // Payload sudah lengkap dari parent (sudah ada namaObjekPajak, pasalPPh, statusPPh)
        const normalized = normalizePayloadCetakPdf(payload);
        console.log('📤 Payload final cetak PDF:', normalized);
        await mutateAsync(normalized);
      } 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 ModalCetakPdfNr;
