import { useState, useEffect } from 'react';

import { IoIosDownload, IoIosCopy } from 'react-icons/io';

import { Popup, PopupAction } from '../UiComponents/Popup/Popup';
import { useLanguage } from '../../providers/language/LanguageContext';
import { useFileOperations } from '../../hooks/useFiles';
import { 
  JsonRenderer, 
  ImageRenderer, 
  TextRenderer, 
  PdfRenderer, 
  HtmlRenderer,
  ApplicationRenderer, 
  UnsupportedRenderer, 
  LoadingRenderer, 
  ErrorRenderer 
} from './renderers';
import styles from './ContentPreview.module.css';

export interface ContentPreviewProps {
  isOpen: boolean;
  onClose: () => void;
  fileId: string;
  fileName: string;
  mimeType?: string;
}

export function ContentPreview({ 
  isOpen, 
  onClose, 
  fileId, 
  fileName, 
  mimeType 
}: ContentPreviewProps) {
  const { t } = useLanguage();
  const { handleFilePreview, handleFileDownload, previewingFiles, previewError, downloadingFiles } = useFileOperations();
  
  // Debug logging to see what data we're receiving
  useEffect(() => {
    if (isOpen && import.meta.env.DEV) {
      console.log('ContentPreview received:', { fileId, fileName, mimeType });
    }
  }, [isOpen, fileId, fileName, mimeType]);
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);
  const [previewContent, setPreviewContent] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [copySuccess, setCopySuccess] = useState<boolean>(false);

  // Clean up blob URL when component unmounts or preview changes
  useEffect(() => {
    return () => {
      if (previewUrl) {
        window.URL.revokeObjectURL(previewUrl);
      }
    };
  }, [previewUrl]);

  // Load preview when modal opens
  useEffect(() => {
    if (isOpen && fileId) {
      // Check if we have valid data
      if (!fileId || fileId === 'undefined' || fileId === 'null') {
        setError('Invalid file ID');
        return;
      }
      if (!fileName || fileName === 'Unknown Item') {
        setError('File name not available');
        return;
      }
      loadPreview();
    } else {
      // Clean up when modal closes
      if (previewUrl) {
        window.URL.revokeObjectURL(previewUrl);
        setPreviewUrl(null);
      }
      setError(null);
    }
  }, [isOpen, fileId, fileName]);


  const loadPreview = async () => {
    try {
      setError(null);
      setPreviewContent(null);
      const result = await handleFilePreview(fileId, fileName, mimeType);
      
      if (result.success) {
        if (result.previewUrl) {
          setPreviewUrl(result.previewUrl);
        }
        if (result.decodedContent) {
          setPreviewContent(result.decodedContent);
        }
        // If it's text content but MIME type says PDF, we'll handle it in renderPreview
      } else {
        setError(result.error || 'Failed to load preview');
      }
    } catch (err) {
      setError('An unexpected error occurred while loading the preview');
    }
  };

  const handleCopyContent = async () => {
    try {
      if (previewContent) {
        await navigator.clipboard.writeText(previewContent);
        setCopySuccess(true);
        setTimeout(() => setCopySuccess(false), 2000);
      } else {
        // Fallback: try to copy from preview URL if it's a text file
        if (previewUrl && mimeType?.startsWith('text/')) {
          const response = await fetch(previewUrl);
          const text = await response.text();
          await navigator.clipboard.writeText(text);
          setCopySuccess(true);
          setTimeout(() => setCopySuccess(false), 2000);
        }
      }
    } catch (err) {
      console.error('Failed to copy content:', err);
    }
  };

  const handleDownloadFile = async () => {
    try {
      await handleFileDownload(fileId, fileName);
    } catch (err) {
      console.error('Failed to download file:', err);
    }
  };

  const isPreviewing = previewingFiles.has(fileId);
  const hasError = error || previewError;

  // Check if this is a corrupted PDF (text content instead of PDF)
  const isCorruptedPdf = mimeType === 'application/pdf' && previewContent && !previewUrl;

  // Create action buttons for the popup header
  const actions: PopupAction[] = [
    // Copy Content Button - only show for text-based files (exclude PDFs and images) or corrupted PDFs
    ...(mimeType !== 'application/pdf' && !mimeType?.startsWith('image/') && (mimeType?.startsWith('text/') || mimeType === 'application/json' || previewContent) ? [{
      label: copySuccess ? t('files.preview.copied', 'Copied!') : t(''),
      icon: copySuccess ? '✓' : <IoIosCopy />,
      onClick: handleCopyContent,
      disabled: !previewContent && !previewUrl,
      variant: 'primary' as const
    }] : []),
    
    // Download Button - hide for corrupted PDFs
    ...(isCorruptedPdf ? [] : [{
      label: String(''),
      icon: downloadingFiles.has(fileId) ? undefined : <IoIosDownload />,
      onClick: handleDownloadFile,
      disabled: downloadingFiles.has(fileId),
      loading: downloadingFiles.has(fileId),
      variant: 'success' as const
    }])
  ];

  const renderPreview = () => {
    // Handle text content in PDF files (corrupted files) - check this first
    if (previewContent && !previewUrl && mimeType === 'application/pdf') {
      console.log('🔍 ContentPreview: Rendering corrupted PDF with text content');
      return (
        <PdfRenderer 
          previewUrl={undefined} 
          previewContent={previewContent}
          fileName={fileName} 
          onError={() => setError('Failed to load PDF preview')}
        />
      );
    }

    if (!previewUrl) {
      if (isPreviewing) {
        return <LoadingRenderer />;
      }
      
      if (hasError) {
        return <ErrorRenderer error={hasError} onRetry={loadPreview} />;
      }
      
      return null;
    }

    // For JSON files with decoded content, use JsonRenderer
    if (previewContent && mimeType === 'application/json') {
      return <JsonRenderer previewContent={previewContent} fileName={fileName} />;
    }

    if (mimeType === 'application/json') {
      return (
        <div className={styles.jsonContainer}>
          <div className={styles.jsonHeader}>
            <span className={styles.jsonTitle}>JSON Preview (Fallback)</span>
            <div className={styles.jsonHeaderRight}>
              <span className={styles.jsonSize}>Raw content</span>
            </div>
          </div>
          <pre className={styles.jsonPreview}>
            <code className={styles.jsonCode}>
              {previewContent || 'No content available'}
            </code>
          </pre>
        </div>
      );
    }

    // Determine preview type based on MIME type
    const mimePrefix = mimeType?.split('/')[0];

    
    
    switch (mimePrefix) {
      case 'image':
        return (
          <ImageRenderer 
            previewUrl={previewUrl} 
            fileName={fileName} 
            onError={() => setError('Failed to load image preview')}
          />
        );
      
      case 'text':
        // Special handling for HTML files
        if (mimeType === 'text/html') {
          return (
            <HtmlRenderer 
              previewUrl={previewUrl} 
              fileName={fileName} 
              onError={() => setError('Failed to load HTML preview')}
            />
          );
        }
        
        return (
          <TextRenderer 
            previewUrl={previewUrl} 
            fileName={fileName} 
            mimeType={mimeType}
            onError={() => setError('Failed to load text preview')}
          />
        );
      
      case 'application':
        if (mimeType === 'application/pdf') {
          console.log('🔍 ContentPreview passing normal PDF to PdfRenderer:', {
            previewUrl,
            previewContent: previewContent ? `${previewContent.substring(0, 50)}...` : null,
            fileName,
            mimeType
          });
          return (
            <PdfRenderer 
              previewUrl={previewUrl} 
              previewContent={previewContent || undefined}
              fileName={fileName} 
              onError={() => setError('Failed to load PDF preview')}
            />
          );
        }
        
        if (mimeType === 'application/html') {
          return (
            <HtmlRenderer 
              previewUrl={previewUrl} 
              fileName={fileName} 
              onError={() => setError('Failed to load HTML preview')}
            />
          );
        }
        

        
        return (
          <ApplicationRenderer 
            previewUrl={previewUrl} 
            fileName={fileName} 
            mimeType={mimeType}
            onError={() => setError('Preview not supported for this file type')}
          />
        );
      
      default:
        return <UnsupportedRenderer previewUrl={previewUrl} fileName={fileName} />;
    }
  };

  return (
    <Popup
      isOpen={isOpen}
      onClose={onClose}
      title={`${t('files.preview.title', 'Content Preview')}: ${fileName}`}
      size="fullscreen"
      className={styles.contentPreviewPopup}
      actions={actions}
    >
      <div className={styles.previewContainer}>
        {renderPreview()}
      </div>
    </Popup>
  );
}

export default ContentPreview;

