import React, { useEffect, useRef, useState } from 'react';
import { useParams } from 'react-router-dom'; // Import useParams
import { apiPath, adobeAPIKey } from "../../../auth/utils";

const PdfViewer = ({ pdfUrl, formCode }) => {
  const { id } = useParams();
  pdfUrl = pdfUrl + "&clientId=" + id;

  const viewerRef = useRef(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    console.log('pdfUrl:', pdfUrl);
    const token = localStorage.getItem('accessToken')
    console.log('JWT:', token || 'No JWT found');

    if (!token) {
      setError('No JWT found. Please log in.');
      return;
    }

    // Test PDF fetch with JWT
    fetch(pdfUrl, {
      method: 'GET',
      headers: {
        Authorization: `Bearer ${token}`,
      },
    })
      .then(response => {
        console.log('Fetch response:', response);
        if (!response.ok) throw new Error(`Failed to fetch PDF: ${response.status} ${response.statusText}`);
        return response.blob();
      })
      .then(blob => {
        console.log('PDF blob:', blob);
        if (blob.type !== 'application/pdf') {
          throw new Error('Fetched file is not a PDF');
        }
      })
      .catch(error => {
        console.error('Fetch error:', error);
        setError(error.message);
      });

    const loadAdobeSDK = () => {
      if (window.AdobeDC) {
        const adobeDCView = new window.AdobeDC.View({
          clientId:  `${adobeAPIKey}`, 
          divId: 'adobe-dc-view',
        });

        adobeDCView.previewFile(
          {
            content: {
              location: {
                url: pdfUrl,
                headers: [{ key: 'Authorization', value: `Bearer ${token}` }],
              },
            },
            metaData: { fileName: 'document.pdf' },
          },
          {
            embedMode: 'FULL_WINDOW',
            showAnnotationTools: true,
            enableFormFilling: true,
          }
        ).catch(error => {
          console.error('Preview error:', error);
          setError('Failed to load PDF: ' + error.message);
        });

        adobeDCView.registerCallback(
          window.AdobeDC.View.Enum.CallbackType.SAVE_API,
          async (metaData, content, options) => {
            try {
              const saveUrl = `${apiPath}/pdf2/save-pdf?clientId=${encodeURIComponent(id)}&formCode=${encodeURIComponent(formCode)}`;
              console.log('Saving to:', saveUrl);
              console.log('Authorization header:', `Bearer ${token}`);
              const response = await fetch(saveUrl, {
                method: 'POST',
                headers: {
                  'Content-Type': 'application/pdf',
                  Authorization: `Bearer ${token}`,
                },
                body: content,
              });
              console.log('Save response:', response);
              if (response.ok) {
                console.log('PDF saved successfully');
                // Ensure metaData is preserved for the SDK
                return {
                  code: window.AdobeDC.View.Enum.ApiResponseCode.SUCCESS,
                  data: { metaData } // Return metaData to prevent t.data undefined
                };
              }
              const errorText = await response.text();
              throw new Error(`Save failed: ${response.status} ${response.statusText} - ${errorText}`);
            } catch (error) {
              console.error('Error saving PDF:', error);
              setError('Error saving PDF: ' + error.message);
              return { code: window.AdobeDC.View.Enum.ApiResponseCode.FAIL };
            }
          },
          { autoSaveFrequency: 0, enableFormFilling: true }
        );
      } else {
        console.error('AdobeDC not available');
        setError('Adobe SDK not loaded');
      }
    };

    if (window.AdobeDC) {
      loadAdobeSDK();
    } else {
      document.addEventListener('adobe_dc_view_sdk.ready', loadAdobeSDK);
    }

    return () => {
      document.removeEventListener('adobe_dc_view_sdk.ready', loadAdobeSDK);
    };
  }, [pdfUrl]);

  if (error) {
    return <div style={{ color: 'red' }}>Error: {error}</div>;
  }

  return <div id="adobe-dc-view" ref={viewerRef} style={{ height: '100vh', border: '1px solid red' }} />;
};

export default PdfViewer;