import React from 'react';
import { GRD, NotaFiscal } from '../types';

declare const html2canvas: any;
declare const jspdf: any;

interface GrdDetailModalProps {
  grd: GRD;
  relatedNFs: NotaFiscal[];
  onClose: () => void;
}

const GrdDetailModal: React.FC<GrdDetailModalProps> = ({ grd, relatedNFs, onClose }) => {
    
    const handleSavePdf = () => {
        const input = document.getElementById('grd-document');
        if (!input) return;

        const { jsPDF } = jspdf;

        html2canvas(input, {
            scale: 2, // Adjusted for better rendering
            useCORS: true,
            backgroundColor: '#ffffff',
            letterRendering: 1, // Improves text rendering
        }).then((canvas) => {
            const imgData = canvas.toDataURL('image/png');
            // A4 size in points: 841.89 x 595.28 (landscape)
            const pdf = new jsPDF({
                orientation: 'landscape',
                unit: 'pt',
                format: 'a4'
            });

            const pdfWidth = pdf.internal.pageSize.getWidth();
            const pdfHeight = pdf.internal.pageSize.getHeight();
            const canvasAspectRatio = canvas.width / canvas.height;
            
            let finalCanvasWidth = pdfWidth;
            let finalCanvasHeight = finalCanvasWidth / canvasAspectRatio;

            if (finalCanvasHeight > pdfHeight) {
                finalCanvasHeight = pdfHeight;
                finalCanvasWidth = finalCanvasHeight * canvasAspectRatio;
            }
            
            const x = (pdfWidth - finalCanvasWidth) / 2;
            const y = (pdfHeight - finalCanvasHeight) / 2;
            
            pdf.addImage(imgData, 'PNG', x, y, finalCanvasWidth, finalCanvasHeight);
            pdf.save(`GRD_${grd.numeroGRD}.pdf`);
        });
    };
    
    const formatDate = (dateString?: string) => {
        if (!dateString) return '';
        return new Date(dateString).toLocaleDateString('pt-BR', { timeZone: 'UTC' });
    }
    
    return (
        <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
            <div className="bg-primary-dark border border-primary-medium rounded-2xl shadow-2xl shadow-primary-light/10 w-full max-w-6xl max-h-[90vh] flex flex-col transform transition-all duration-300 scale-95 animate-fade-in-up">
                <div className="p-4 border-b border-primary-medium/50 flex justify-between items-center">
                    <h2 className="text-xl font-bold text-white">Detalhes do GRD: <span className="text-primary-light">Nº {grd.numeroGRD}</span></h2>
                    <div className="flex items-center gap-4">
                        <button onClick={handleSavePdf} className="px-4 py-2 text-sm rounded-full font-semibold text-primary-dark bg-primary-light hover:bg-opacity-90 transition-colors">Salvar PDF</button>
                        <button onClick={onClose} className="text-gray-400 hover:text-white transition-colors text-3xl font-light">&times;</button>
                    </div>
                </div>

                <div className="p-2 sm:p-6 overflow-y-auto">
                   <div id="grd-document" className="bg-white text-black p-8" style={{ fontFamily: "'Montserrat', sans-serif" }}>
                       <header className="grid grid-cols-3 gap-4 border-b-2 border-black pb-2">
                            <div className="col-span-1">
                                <h1 className="text-xl font-bold">CONSAG</h1>
                                <p className="text-xs">ENGENHARIA ICS</p>
                            </div>
                            <h2 className="col-span-2 text-2xl font-bold text-center self-center">GRD - Guia de Remessa de Documentos</h2>
                       </header>
                       
                       <div className="grid grid-cols-5 gap-px my-4 text-sm">
                            <div className="font-bold border border-black p-2">De:</div>
                            <div className="col-span-4 border border-black p-2">SUPRIMENTOS/ALMOXARIFADO</div>
                            <div className="font-bold border border-black p-2">Para:</div>
                            <div className="col-span-4 border border-black p-2">SUPRIMENTOS/PROCESSAMENTO</div>
                       </div>
                       
                        <div className="grid grid-cols-3 gap-px mb-4 text-sm">
                            <div className="font-bold border border-black p-2">Data:</div>
                            <div className="border border-black p-2">{formatDate(grd.dataEmissao)}</div>
                            <div className="font-bold border border-black p-2">GRD Nº {grd.numeroGRD}</div>
                       </div>

                       <table className="w-full border-collapse border border-black text-xs">
                           <thead>
                               <tr className="bg-gray-200 text-left font-bold">
                                   <th className="border border-black p-2">ID</th>
                                   <th className="border border-black p-2">CT-E</th>
                                   <th className="border border-black p-2">NF</th>
                                   <th className="border border-black p-2">RAZÃO SOCIAL</th>
                                   <th className="border border-black p-2">DATA DO RECEBIMENTO</th>
                                   <th className="border border-black p-2">DATA DA CONFERENCIA</th>
                                   <th className="border border-black p-2">PEDIDO DE COMPRA</th>
                                   <th className="border border-black p-2">OBS</th>
                               </tr>
                           </thead>
                           <tbody>
                                {relatedNFs.map((nf, index) => (
                                   <tr key={nf.id} className="even:bg-gray-50">
                                       <td className="border border-black p-2">{(index + 1).toString().padStart(2, '0')}</td>
                                       <td className="border border-black p-2">{nf.numeroCTE || ''}</td>
                                       <td className="border border-black p-2">{nf.numeroNF}</td>
                                       <td className="border border-black p-2">{nf.fornecedor}</td>
                                       <td className="border border-black p-2">{formatDate(nf.dataRecebimento)}</td>
                                       <td className="border border-black p-2">{formatDate(nf.dataConferencia)}</td>
                                       <td className="border border-black p-2">{nf.numeroPedido}</td>
                                       <td className="border border-black p-2">{grd.observacao || ''}</td>
                                   </tr>
                               ))}
                               {[...Array(Math.max(0, 28 - relatedNFs.length))].map((_, i) => (
                                   <tr key={`empty-${i}`} className="even:bg-gray-50">
                                      <td className="border border-black p-2" dangerouslySetInnerHTML={{ __html: '&nbsp;' }} />
                                      <td className="border border-black p-2" dangerouslySetInnerHTML={{ __html: '&nbsp;' }} />
                                      <td className="border border-black p-2" dangerouslySetInnerHTML={{ __html: '&nbsp;' }} />
                                      <td className="border border-black p-2" dangerouslySetInnerHTML={{ __html: '&nbsp;' }} />
                                      <td className="border border-black p-2" dangerouslySetInnerHTML={{ __html: '&nbsp;' }} />
                                      <td className="border border-black p-2" dangerouslySetInnerHTML={{ __html: '&nbsp;' }} />
                                      <td className="border border-black p-2" dangerouslySetInnerHTML={{ __html: '&nbsp;' }} />
                                      <td className="border border-black p-2" dangerouslySetInnerHTML={{ __html: '&nbsp;' }} />
                                   </tr>
                               ))}
                           </tbody>
                       </table>
                       
                       <footer className="mt-12 flex justify-between text-xs">
                            <div>
                                <div className="border-t border-black w-64 text-center pt-1">Ass.Responsavel recebimento</div>
                            </div>
                             <div>
                                <div className="border-t border-black w-64 text-center pt-1">Data Conferência</div>
                            </div>
                       </footer>
                   </div>
                </div>
            </div>
        </div>
    );
};

export default GrdDetailModal;