import React, { useRef } from 'react';
import { usePDF } from 'react-to-pdf';
import { CV } from '../types/cv';
import { CVTemplate } from './CVTemplate';

interface PDFGeneratorProps {
  cv: CV;
}

export const PDFGenerator: React.FC<PDFGeneratorProps> = ({ cv }) => {
  const { toPDF, targetRef } = usePDF({
    filename: `${cv.generalInfo.name || 'CV'}_${new Date().toISOString().slice(0, 10)}.pdf`,
    page: { margin: 20 },
    method: 'open'
  });

  // Add a method that can be called from outside this component
  React.useEffect(() => {
    // Add a global function that can be called from the parent component
    window.generatePDF = () => {
      toPDF();
    };
    
    return () => {
      // Clean up when component unmounts
      delete window.generatePDF;
    };
  }, [toPDF]);

  return (
    <div>
      <div 
        style={{ 
          textAlign: 'center', 
          fontSize: '1rem', 
          color: '#4d4d4d', 
          margin: '1rem 0'
        }}
      >
        Click the button below to generate a PDF of your CV
      </div>
      
      <div 
        ref={targetRef} 
        style={{ 
          width: '210mm', // A4 width
          padding: '10mm',
          display: 'none' // Hide from view
        }}
        className="pdf-template"
      >
        <CVTemplate cv={cv} isPDF={true} />
      </div>
    </div>
  );
}; 