import { useEffect, useState } from 'react';
import { useFileService } from '../hooks/useFileService';
import { generateFilePreview } from '../utils/filePreview';
import type { FileServiceConfig, FileMetadata, FilePreview } from '../types';

interface FileViewerProps {
  fileId: string;
  config?: FileServiceConfig;
  className?: string;
  showPreview?: boolean;
}

export function FileViewer({ fileId, config, className = '', showPreview = true }: FileViewerProps) {
  const { getFileMetadata, getFile, loading, error } = useFileService(config);
  const [fileUrl, setFileUrl] = useState<string | null>(null);
  const [fileBlob, setFileBlob] = useState<Blob | null>(null);
  const [fileMetadata, setFileMetadata] = useState<FileMetadata | null>(null);
  const [preview, setPreview] = useState<FilePreview | null>(null);

  useEffect(() => {
    const loadFile = async () => {
      try {
        const metadata = await getFileMetadata(fileId);
        if (metadata) {
          setFileMetadata(metadata);
          
          // Backend returns presigned URL in storagePath field
          if (metadata.storagePath && metadata.storagePath.startsWith('http')) {
            // Use presigned URL directly for preview
            setFileUrl(metadata.storagePath);
            
            // Try to get blob for preview metadata generation
            if (showPreview) {
              try {
                const blob = await getFile(fileId);
                if (blob) {
                  setFileBlob(blob);
                  const file = new File([blob], metadata.fileName, {
                    type: `application/${metadata.fileExtension.replace('.', '')}`,
                  });
                  const previewData = await generateFilePreview(file);
                  setPreview(previewData);
                }
              } catch (blobError) {
                // If blob download fails, still show preview using presigned URL
                console.warn('Could not generate preview metadata:', blobError);
              }
            }
          } else {
            // Fallback: try to get blob if presigned URL not available
            const blob = await getFile(fileId);
            if (blob) {
              const objectUrl = URL.createObjectURL(blob);
              setFileUrl(objectUrl);
              
              if (showPreview) {
                const file = new File([blob], metadata.fileName, {
                  type: `application/${metadata.fileExtension.replace('.', '')}`,
                });
                const previewData = await generateFilePreview(file);
                setPreview(previewData);
              }
            }
          }
        }
      } catch (error) {
        console.error('Error loading file:', error);
      }
    };

    if (fileId) {
      loadFile();
    }

    return () => {
      if (fileUrl && fileUrl.startsWith('blob:')) {
        URL.revokeObjectURL(fileUrl);
      }
    };
  }, [fileId, getFileMetadata, getFile, showPreview]);

  if (loading) {
    return <div className={`file-viewer loading ${className}`}>Loading file...</div>;
  }

  if (error) {
    return <div className={`file-viewer error ${className}`}>Error: {error}</div>;
  }

  if (!fileUrl || !fileMetadata) {
    return <div className={`file-viewer empty ${className}`}>No file to display</div>;
  }

  const fileExtension = fileMetadata.fileExtension.toLowerCase();
  const isPdf = fileExtension === '.pdf';
  const isImage = fileMetadata.fileExtension.match(/\.(jpg|jpeg|png|gif|bmp|webp|svg)$/i);
  const isText = fileMetadata.fileExtension.match(/\.(txt|md|json|xml|html|css|js|ts|tsx|jsx)$/i);
  const isWord = fileExtension.match(/\.(doc|docx)$/i);
  const isExcel = fileExtension.match(/\.(xls|xlsx)$/i);
  const isCsv = fileExtension === '.csv';

  return (
    <div className={`file-viewer ${className}`}>
      <div className="file-viewer-header">
        <h4>{fileMetadata.fileName}</h4>
        <div className="file-info">
          <span>Size: {(fileMetadata.size / 1024).toFixed(2)} KB</span>
          <span>Type: {fileMetadata.fileExtension}</span>
          {preview?.pages && <span>Pages: {preview.pages}</span>}
          {preview?.sheets && preview.sheets.length > 0 && (
            <span>Sheets: {preview.sheets.join(', ')}</span>
          )}
        </div>
      </div>
      
      <div className="file-content">
        {isPdf && fileUrl && (
          <div className="pdf-viewer">
            <iframe
              src={fileUrl || undefined}
              title={fileMetadata.fileName}
              style={{
                width: '100%',
                height: '700px',
                border: '1px solid #ddd',
                borderRadius: '4px',
              }}
            />
          </div>
        )}
        
        {isImage && fileUrl && (
          <div className="image-viewer">
            <img
              src={fileUrl || undefined}
              alt={fileMetadata.fileName}
              style={{
                maxWidth: '100%',
                maxHeight: '800px',
                border: '1px solid #ddd',
                borderRadius: '4px',
                objectFit: 'contain',
              }}
            />
          </div>
        )}
        
        {isText && fileUrl && (
          <div className="text-viewer">
            <iframe
              src={fileUrl || undefined}
              title={fileMetadata.fileName}
              style={{
                width: '100%',
                height: '600px',
                border: '1px solid #ddd',
                borderRadius: '4px',
              }}
            />
          </div>
        )}
        
        {isWord && fileUrl && (
          <div className="word-viewer">
            <iframe
              src={`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(fileUrl)}`}
              title={fileMetadata.fileName}
              style={{
                width: '100%',
                height: '700px',
                border: '1px solid #ddd',
                borderRadius: '4px',
              }}
            />
          </div>
        )}
        
        {isExcel && (
          <div className="spreadsheet-viewer">
            {preview?.sheets && preview.sheets.length > 0 && (
              <div style={{ padding: '10px', backgroundColor: '#f5f5f5', marginBottom: '10px' }}>
                <strong>Available Sheets:</strong> {preview.sheets.join(', ')}
              </div>
            )}
            {preview?.metadata && (
              <div style={{ padding: '10px', backgroundColor: '#f5f5f5', marginBottom: '10px' }}>
                {preview.metadata.rows && <p>Rows: {preview.metadata.rows}</p>}
                {preview.metadata.columns && <p>Columns: {preview.metadata.columns}</p>}
                {preview.metadata.headers && (
                  <p>Headers: {preview.metadata.headers.join(', ')}</p>
                )}
              </div>
            )}
            <div style={{ padding: '20px', textAlign: 'center' }}>
              <p>Download the file to view spreadsheet content</p>
              <a
                href={fileUrl}
                download={fileMetadata.fileName}
                style={{
                  padding: '10px 20px',
                  backgroundColor: '#007bff',
                  color: 'white',
                  textDecoration: 'none',
                  borderRadius: '4px',
                  display: 'inline-block',
                  marginTop: '10px',
                }}
              >
                Download File
              </a>
            </div>
          </div>
        )}

        {isCsv && (
          <div className="csv-viewer">
            {preview?.metadata && (
              <div style={{ padding: '10px', backgroundColor: '#f5f5f5', marginBottom: '10px', borderRadius: '4px' }}>
                <div style={{ display: 'flex', gap: '20px', flexWrap: 'wrap' }}>
                  {preview.metadata.rows && <span><strong>Total Rows:</strong> {preview.metadata.rows}</span>}
                  {preview.metadata.columns && <span><strong>Columns:</strong> {preview.metadata.columns}</span>}
                  {preview.metadata.rows && preview.metadata.rows > 100 && (
                    <span style={{ color: '#666', fontSize: '14px' }}>
                      Showing first 100 rows (of {preview.metadata.rows} total)
                    </span>
                  )}
                </div>
              </div>
            )}
            {preview?.csvData && preview.csvData.length > 0 ? (
              <div style={{ 
                overflowX: 'auto', 
                overflowY: 'auto', 
                maxHeight: '600px',
                border: '1px solid #ddd',
                borderRadius: '4px',
              }}>
                <table style={{
                  width: '100%',
                  borderCollapse: 'collapse',
                  fontSize: '14px',
                }}>
                  <thead>
                    <tr style={{ backgroundColor: '#f8f9fa', position: 'sticky', top: 0 }}>
                      {preview.csvData[0]?.map((header: string, colIndex: number) => (
                        <th
                          key={colIndex}
                          style={{
                            padding: '12px',
                            textAlign: 'left',
                            borderBottom: '2px solid #dee2e6',
                            borderRight: '1px solid #dee2e6',
                            fontWeight: '600',
                          }}
                        >
                          {header || `Column ${colIndex + 1}`}
                        </th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {preview.csvData.slice(1).map((row: string[], rowIndex: number) => (
                      <tr
                        key={rowIndex}
                        style={{
                          backgroundColor: rowIndex % 2 === 0 ? '#ffffff' : '#f8f9fa',
                        }}
                      >
                        {row.map((cell: string, colIndex: number) => (
                          <td
                            key={colIndex}
                            style={{
                              padding: '10px 12px',
                              borderBottom: '1px solid #dee2e6',
                              borderRight: '1px solid #dee2e6',
                              maxWidth: '200px',
                              overflow: 'hidden',
                              textOverflow: 'ellipsis',
                              whiteSpace: 'nowrap',
                            }}
                            title={cell}
                          >
                            {cell || ''}
                          </td>
                        ))}
                        {/* Fill empty cells if row has fewer columns than header */}
                        {Array.from({ length: Math.max(0, (preview.csvData[0]?.length || 0) - row.length) }).map((_, idx) => (
                          <td
                            key={`empty-${idx}`}
                            style={{
                              padding: '10px 12px',
                              borderBottom: '1px solid #dee2e6',
                              borderRight: '1px solid #dee2e6',
                            }}
                          />
                        ))}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : (
              <div style={{ padding: '20px', textAlign: 'center', backgroundColor: '#f5f5f5', borderRadius: '4px' }}>
                <p>No data available to preview</p>
                <a
                  href={fileUrl}
                  download={fileMetadata.fileName}
                  style={{
                    padding: '10px 20px',
                    backgroundColor: '#007bff',
                    color: 'white',
                    textDecoration: 'none',
                    borderRadius: '4px',
                    display: 'inline-block',
                    marginTop: '10px',
                  }}
                >
                  Download File
                </a>
              </div>
            )}
          </div>
        )}
        
        {!isPdf && !isImage && !isText && !isWord && !isExcel && !isCsv && (
          <div className="generic-viewer">
            <div style={{ padding: '40px', textAlign: 'center' }}>
              <p>Preview not available for this file type</p>
              <a
                href={fileUrl}
                download={fileMetadata.fileName}
                style={{
                  padding: '10px 20px',
                  backgroundColor: '#007bff',
                  color: 'white',
                  textDecoration: 'none',
                  borderRadius: '4px',
                  display: 'inline-block',
                  marginTop: '20px',
                }}
              >
                Download File
              </a>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

