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 useCetakPdfFakturPM from '../../hooks/useCetakFakturPM';

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

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

  console.log(payload, 'ini dari cetak');

  const { mutateAsync } = useCetakPdfFakturPM({
    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' });
      // console.log('Ok');
    },
  });

  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({ id: payload.id });
      } 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 Pajak Keluaran">
      <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 Faktur PK"
          />
        )}

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

export default ModalCetakFakturPM;
