'use client';

import { useEffect, useState } from 'react';
import { apiRequest, getApiBaseUrl } from '@/lib/dashboardHelpers';

interface DocumentModalProps {
  isOpen: boolean;
  onClose: () => void;
  documentNumber: string | null;
  documentId: number | null;
  mode?: 'single' | 'gallery' | 'allPages';
  transactionId?: number | null;
}

export default function DocumentModal({ 
  isOpen, 
  onClose, 
  documentNumber, 
  documentId,
  mode = 'single',
  transactionId 
}: DocumentModalProps) {
  const [pdfUrl, setPdfUrl] = useState<string>('');
  const [modalTitle, setModalTitle] = useState<string>('Document Viewer');
  const [error, setError] = useState<string>('');

  useEffect(() => {
    if (isOpen && mode === 'single' && documentId) {
      loadDocument();
    } else if (isOpen && mode === 'gallery' && transactionId) {
      loadDocumentsGallery();
    } else if (isOpen && mode === 'allPages' && transactionId) {
      loadAllPages();
    }

    return () => {
      // Cleanup blob URL
      if (pdfUrl && pdfUrl.startsWith('blob:')) {
        URL.revokeObjectURL(pdfUrl);
      }
    };
  }, [isOpen, documentId, transactionId, mode]);

  async function loadDocument() {
    if (!documentId) return;

    console.log('👁️ Viewing document:', documentId, 'Number:', documentNumber);

    setModalTitle('Loading document...');
    setPdfUrl('');
    setError('');

    try {
      // Use fixed endpoint which handles:
      // - PDF display (if already PDF)
      // - Image to PDF conversion (for .bin files)
      // - Null document numbers (supporting documents)
      // - Direct document_id lookups
      let endpoint;
      
      if (documentNumber && documentNumber !== 'null' && documentNumber !== 'undefined' && documentNumber !== '') {
        // Regular document with document_number
        endpoint = `/documents/pdf-by-document-number-fixed?` +
              `document_number=${encodeURIComponent(documentNumber)}&` +
              `document_id=${documentId}`;
        setModalTitle(`${documentNumber} • Document ID: ${documentId}`);
      } else {
        // Supporting document (NULL document_number) - use document_id only
        endpoint = `/documents/pdf-by-document-number-fixed?document_id=${documentId}`;
        setModalTitle(`Supporting Document • ID: ${documentId}`);
      }

      console.log('📥 Fetching PDF:', `${getApiBaseUrl()}${endpoint}`);

      const response = await apiRequest(endpoint);
      
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`HTTP ${response.status}: ${errorText}`);
      }

      // Get the PDF blob and create object URL
      const blob = await response.blob();
      const pdfUrl = URL.createObjectURL(blob);
      
      console.log('✅ PDF loaded successfully');
      setPdfUrl(pdfUrl);
      
    } catch (err: any) {
      console.error('❌ PDF loading error:', err);
      setError(err.message);
      setModalTitle('Error Loading Document');
    }
  }

  async function loadDocumentsGallery() {
    if (!transactionId) return;

    console.log('👁️ Viewing documents gallery for transaction:', transactionId);

    setModalTitle('Loading documents...');
    setPdfUrl('');
    setError('');
    
    try {
      const response = await apiRequest(`/transactions/${transactionId}`);
      
      if (!response.ok) {
        throw new Error('Failed to load transaction details');
      }
      
      const transaction = await response.json();
      const { getDocumentIcon } = await import('@/lib/dashboardHelpers');
      
      setModalTitle(`All Documents - Transaction ${transaction.transaction_number}`);
      
      // Create HTML gallery view with clickable documents
      let galleryHtml = `
        <!DOCTYPE html>
        <html>
        <head>
          <style>
            body {
              font-family: system-ui, -apple-system, sans-serif;
              padding: 30px;
              background: #f9fafb;
              margin: 0;
            }
            h2 {
              color: #047857;
              margin-bottom: 15px;
              font-size: 1.8em;
            }
            .subtitle {
              color: #6b7280;
              margin-bottom: 30px;
              font-size: 1.1em;
            }
            .document-card {
              background: white;
              border: 2px solid #e5e7eb;
              border-radius: 12px;
              padding: 20px;
              margin-bottom: 15px;
              transition: all 0.3s ease;
            }
            .document-card.clickable {
              cursor: pointer;
            }
            .document-card.clickable:hover {
              border-color: #10b981;
              transform: translateY(-2px);
              box-shadow: 0 8px 20px rgba(16, 185, 129, 0.2);
            }
            .document-card.disabled {
              opacity: 0.6;
            }
            .doc-header {
              display: flex;
              align-items: center;
              gap: 15px;
            }
            .doc-icon {
              font-size: 2em;
            }
            .doc-info {
              flex: 1;
            }
            .doc-title {
              font-weight: 600;
              font-size: 1.1em;
              margin-bottom: 4px;
            }
            .doc-meta {
              font-size: 0.9em;
              color: #6b7280;
            }
            .page-count {
              text-align: right;
            }
            .page-num {
              font-weight: 600;
              color: #10b981;
              font-size: 1.1em;
            }
            .view-btn {
              background: #10b981;
              color: white;
              border: none;
              padding: 8px 16px;
              border-radius: 8px;
              font-weight: 600;
              font-size: 0.85em;
              cursor: pointer;
              margin-top: 8px;
              transition: all 0.3s ease;
            }
            .view-btn:hover {
              background: #059669;
              transform: scale(1.05);
            }
          </style>
        </head>
        <body>
          <h2>📋 All Documents from Transaction ${transaction.transaction_number}</h2>
          <p class="subtitle">
            Total: ${transaction.summary.total_documents} documents, ${transaction.summary.total_pages} pages
          </p>
          <div>
      `;
      
      transaction.documents.forEach((doc: any, index: number) => {
        const hasContent = doc.page_count > 0;
        const docIcon = getDocumentIcon(doc.document_type_label);
        const isCertificate = doc.document_type_label && doc.document_type_label.toLowerCase().includes('certificate');
        
        galleryHtml += `
          <div class="document-card ${hasContent ? 'clickable' : 'disabled'}">
            <div class="doc-header">
              <span class="doc-icon">${docIcon}</span>
              <div class="doc-info">
                <div class="doc-title">
                  ${index + 1}. ${doc.document_type_label}
                  ${isCertificate ? '<span style="background: rgba(16, 185, 129, 0.1); color: #047857; padding: 2px 8px; border-radius: 6px; font-size: 0.75em; margin-left: 8px;">C of O</span>' : ''}
                </div>
                <div class="doc-meta">
                  ID: ${doc.id}${doc.document_number ? ' • ' + doc.document_number : ''}
                  ${doc.date_issued ? ' • Issued: ' + new Date(doc.date_issued).toLocaleDateString() : ''}
                </div>
              </div>
              <div class="page-count">
                <div class="page-num">${doc.page_count || 0} page${(doc.page_count || 0) !== 1 ? 's' : ''}</div>
                ${hasContent ? `
                  <button class="view-btn" onclick="alert('View document: ${doc.document_number || doc.id}')">
                    👁️ View PDF
                  </button>
                ` : '<span style="color: #9ca3af; font-size: 0.85em;">No content</span>'}
              </div>
            </div>
          </div>
        `;
      });
      
      galleryHtml += `
          </div>
          <div style="margin-top: 30px; padding: 20px; background: white; border-radius: 12px; border: 2px solid #10b981; text-align: center;">
            <p style="color: #1f2937; margin-bottom: 10px;">
              <strong>💡 Summary:</strong> ${transaction.summary.total_documents} documents • 
              ${transaction.summary.total_pages} total pages • 
              ${transaction.summary.with_content} documents with content
            </p>
          </div>
        </body>
        </html>
      `;
      
      const blob = new Blob([galleryHtml], { type: 'text/html' });
      const url = URL.createObjectURL(blob);
      setPdfUrl(url);
      
    } catch (err: any) {
      console.error('❌ Error loading documents gallery:', err);
      setError(err.message);
      setModalTitle('Error Loading Documents');
    }
  }

  async function loadAllPages() {
    if (!transactionId) return;

    console.log('👁️ Viewing ALL PAGES as combined PDF for transaction:', transactionId);

    setModalTitle('Loading all images as one PDF...');
    setPdfUrl('');
    setError('');
    
    try {
      // First, get transaction details to show proper title
      const txnResponse = await apiRequest(`/transactions/${transactionId}`);
      if (!txnResponse.ok) {
        throw new Error('Failed to load transaction details');
      }
      
      const transaction = await txnResponse.json();
      const totalPages = transaction.summary.total_pages;
      const totalDocs = transaction.summary.total_documents;
      
      setModalTitle(`Loading all ${totalPages} pages from ${totalDocs} documents...`);
      
      // Fetch the combined PDF with ALL images from ALL documents in one multipage PDF
      // This endpoint combines all images regardless of document_id or document_type
      const endpoint = `/transactions/${transactionId}/all-pages-pdf`;
      
      console.log('📥 Fetching combined multipage PDF from:', `${getApiBaseUrl()}${endpoint}`);
      console.log(`   Expected: ${totalPages} pages from ${totalDocs} documents combined into one PDF`);
      
      const response = await apiRequest(endpoint);
      
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`API returned ${response.status}: ${errorText}`);
      }

      // Get the combined PDF blob (should contain all 62 images as one PDF)
      const blob = await response.blob();
      const pdfUrl = URL.createObjectURL(blob);
      
      console.log(`✅ Combined multipage PDF loaded successfully (${(blob.size / 1024 / 1024).toFixed(2)} MB)`);
      console.log(`   All ${totalPages} images from ${totalDocs} documents in one PDF file`);
      
      setModalTitle(`📄 All ${totalPages} Pages - Transaction ${transaction.transaction_number}`);
      setPdfUrl(pdfUrl);
      
    } catch (err: any) {
      console.error('❌ Error loading combined PDF:', err);
      setError(
        err.message || 
        'Failed to load combined multipage PDF. ' +
        'The backend endpoint /transactions/{id}/all-pages-pdf may not be available yet. ' +
        'This endpoint should combine all images from all documents into one PDF file.'
      );
      setModalTitle('Error Loading Combined PDF');
    }
  }

  if (!isOpen) return null;

  return (
    <div className="modal" style={{ display: 'flex' }} onClick={(e) => {
      if (e.target === e.currentTarget) onClose();
    }}>
      <div className="modal-content">
        <div className="modal-header">
          <div>
            <div style={{ fontSize: '1.5em', fontWeight: 600 }}>{modalTitle}</div>
            {mode === 'allPages' && !error && pdfUrl && (
              <div style={{ fontSize: '0.85em', opacity: 0.9, marginTop: '5px' }}>
                📄 Combined multipage PDF with all images in sequential order
              </div>
            )}
          </div>
          <button className="modal-close" onClick={onClose}>✕</button>
        </div>
        <div className="modal-body" style={{ flex: 1, minHeight: '700px', position: 'relative', padding: 0 }}>
          {error ? (
            <div style={{ 
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              justifyContent: 'center',
              padding: '80px',
              color: '#991b1b',
              textAlign: 'center'
            }}>
              <div style={{ fontSize: '4em', marginBottom: '25px' }}>⚠️</div>
              <h3 style={{ fontSize: '1.5em', fontWeight: 600, marginBottom: '15px' }}>Failed to Load Document</h3>
              <p style={{ fontSize: '1.1em', color: '#6c757d', maxWidth: '600px', lineHeight: 1.6 }}>{error}</p>
              <button 
                className="btn btn-secondary" 
                onClick={onClose}
                style={{ marginTop: '30px', padding: '12px 30px' }}
              >
                Close
              </button>
            </div>
          ) : pdfUrl ? (
            <>
              {mode === 'allPages' && (
                <div style={{
                  background: 'linear-gradient(135deg, #10b981, #059669)',
                  color: 'white',
                  padding: '12px 20px',
                  textAlign: 'center',
                  fontSize: '0.9em',
                  fontWeight: 500
                }}>
                  🖼️ Viewing all images combined - Scroll through the PDF to see all pages in order
                </div>
              )}
              <iframe 
                src={pdfUrl}
                // type="application/pdf"
                style={{ 
                  width: '100%', 
                  height: '100%', 
                  minHeight: '700px',
                  border: 'none' 
                }}
                title="Document Viewer"
              />
            </>
          ) : (
            <div style={{ 
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              justifyContent: 'center',
              padding: '80px',
              color: '#6c757d'
            }}>
              <div className="spinner" style={{ 
                width: '60px',
                height: '60px',
                border: '6px solid #f3f3f3',
                borderTop: '6px solid #10b981',
                borderRadius: '50%',
                animation: 'spin 1s linear infinite',
                marginBottom: '25px'
              }} />
              <div style={{ fontSize: '1.2em', fontWeight: 600, marginBottom: '10px' }}>
                {mode === 'allPages' ? 'Combining all images into one PDF...' : 'Loading document...'}
              </div>
              {mode === 'allPages' && (
                <div style={{ fontSize: '0.95em', color: '#9ca3af' }}>
                  This may take a moment for large documents
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

