import { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Download, X, Eye, ZoomIn, ZoomOut, RotateCw, Loader2 } from 'lucide-react';
import './FilePreview.css';

interface FilePreviewProps {
  fileName: string;
  fileType: string;
  fileUrl?: string;
  fileSize?: number;
  attachmentId?: string;
  onDownload?: (attachmentId: string) => Promise<void>;
  open: boolean;
  onClose: () => void;
}

export function FilePreview({
  fileName,
  fileType,
  fileUrl,
  fileSize,
  attachmentId,
  onDownload,
  open,
  onClose
}: FilePreviewProps) {
  const [zoom, setZoom] = useState(100);
  const [rotation, setRotation] = useState(0);
  const [blobUrl, setBlobUrl] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const isImage = fileType.toLowerCase().includes('image') || 
                  fileType.toLowerCase().includes('png') || 
                  fileType.toLowerCase().includes('jpg') || 
                  fileType.toLowerCase().includes('jpeg') ||
                  fileType.toLowerCase().includes('gif') ||
                  fileType.toLowerCase().includes('webp');

  const isPDF = fileType.toLowerCase().includes('pdf');
  
  const canPreview = isImage || isPDF;

  // Fetch file as blob for authenticated preview
  useEffect(() => {
    if (!open || !canPreview || !fileUrl) {
      setBlobUrl(null);
      return;
    }

    const fetchFile = async () => {
      setLoading(true);
      setError(null);
      
      try {
        const isProduction = import.meta.env.PROD || import.meta.env.MODE === 'production';
        const token = isProduction ? null : localStorage.getItem('accessToken');
        
        // Ensure we have a valid URL - handle relative URLs when served from same origin
        let urlToFetch = fileUrl;
        if (fileUrl.startsWith('/') && !fileUrl.startsWith('//')) {
          // Relative URL - construct absolute URL using current origin
          urlToFetch = `${window.location.origin}${fileUrl}`;
        }
        
        // Build headers - in production, rely on httpOnly cookies
        const headers: HeadersInit = {
          'Accept': isPDF ? 'application/pdf' : '*/*'
        };
        
        // Only add Authorization header in development mode
        if (!isProduction && token) {
          headers['Authorization'] = `Bearer ${token}`;
        }
        
        const response = await fetch(urlToFetch, {
          headers,
          credentials: 'include', // Always include credentials for cookie-based auth
          mode: 'cors'
        });

        if (!response.ok) {
          const errorText = await response.text().catch(() => '');
          throw new Error(`Failed to load file: ${response.status} ${response.statusText}. ${errorText}`);
        }

        const blob = await response.blob();
        
        // Check if blob is valid
        if (blob.size === 0) {
          throw new Error('File is empty or could not be loaded');
        }
        
        // Verify blob type matches expected type
        if (isPDF && !blob.type.includes('pdf') && blob.type !== 'application/octet-stream') {
          console.warn(`Expected PDF but got ${blob.type}`);
        }
        
        const url = window.URL.createObjectURL(blob);
        setBlobUrl(url);
      } catch (err) {
        console.error('Failed to load file for preview:', err);
        setError(err instanceof Error ? err.message : 'Failed to load file for preview');
      } finally {
        setLoading(false);
      }
    };

    fetchFile();

    // Cleanup blob URL when modal closes
    return () => {
      if (blobUrl) {
        window.URL.revokeObjectURL(blobUrl);
        setBlobUrl(null);
      }
    };
  }, [open, fileUrl, canPreview, isPDF]);

  const handleDownload = async () => {
    if (onDownload && attachmentId) {
      try {
        await onDownload(attachmentId);
      } catch (error) {
        alert('Failed to download file');
      }
    }
  };

  const handleZoomIn = () => setZoom(prev => Math.min(prev + 25, 200));
  const handleZoomOut = () => setZoom(prev => Math.max(prev - 25, 50));
  const handleRotate = () => setRotation(prev => (prev + 90) % 360);

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="file-preview-dialog p-3 sm:p-6">
        <div className="file-preview-content">
        <DialogHeader className="pb-4 flex-shrink-0 pr-8">
          <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
            <div className="flex items-center gap-3 flex-1 min-w-0">
              <Eye className="w-5 h-5 text-blue-600 flex-shrink-0" />
              <div className="flex-1 min-w-0">
                <DialogTitle className="text-base sm:text-lg font-bold text-gray-900 truncate pr-2">
                  {fileName}
                </DialogTitle>
                <p className="text-xs sm:text-sm text-gray-500">
                  {fileType} {fileSize && `• ${(fileSize / 1024).toFixed(1)} KB`}
                </p>
              </div>
            </div>
            
            <div className="flex items-center gap-2 flex-wrap mr-2">
              {isImage && (
                <div className="flex items-center gap-1 mr-2">
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={handleZoomOut}
                    disabled={zoom <= 50}
                    title="Zoom out"
                    className="h-8 w-8 p-0"
                  >
                    <ZoomOut className="h-4 w-4" />
                  </Button>
                  <span className="text-xs sm:text-sm text-gray-600 min-w-[3rem] text-center">{zoom}%</span>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={handleZoomIn}
                    disabled={zoom >= 200}
                    title="Zoom in"
                    className="h-8 w-8 p-0"
                  >
                    <ZoomIn className="h-4 w-4" />
                  </Button>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={handleRotate}
                    title="Rotate"
                    className="h-8 w-8 p-0"
                  >
                    <RotateCw className="h-4 w-4" />
                  </Button>
                </div>
              )}
              
              {onDownload && attachmentId && (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleDownload}
                  className="gap-2 h-9"
                >
                  <Download className="h-4 w-4" />
                  <span className="hidden sm:inline">Download</span>
                </Button>
              )}
            </div>
          </div>
        </DialogHeader>

        <div className="file-preview-body bg-gray-100 rounded-lg p-2 sm:p-4">
          {loading ? (
            <div className="flex flex-col items-center justify-center h-full">
              <Loader2 className="w-12 h-12 text-blue-600 animate-spin mb-4" />
              <p className="text-sm text-gray-600">Loading preview...</p>
            </div>
          ) : error ? (
            <div className="flex flex-col items-center justify-center h-full text-center">
              <div className="w-20 h-20 bg-red-100 rounded-full flex items-center justify-center mb-4">
                <X className="w-10 h-10 text-red-600" />
              </div>
              <h3 className="text-lg font-semibold text-gray-900 mb-2">Preview Failed</h3>
              <p className="text-sm text-gray-600 mb-6">{error}</p>
              {onDownload && attachmentId && (
                <Button onClick={handleDownload} className="gap-2">
                  <Download className="h-4 w-4" />
                  Download {fileName}
                </Button>
              )}
            </div>
          ) : canPreview && blobUrl ? (
            <>
              {isImage && (
                <div className="flex items-center justify-center h-full">
                  <img
                    src={blobUrl}
                    alt={fileName}
                    style={{
                      transform: `scale(${zoom / 100}) rotate(${rotation}deg)`,
                      transition: 'transform 0.2s ease-in-out',
                      maxWidth: '100%',
                      maxHeight: '100%',
                      objectFit: 'contain'
                    }}
                    className="rounded-lg shadow-lg"
                  />
                </div>
              )}
              
              {isPDF && (
                <div className="w-full h-full flex items-center justify-center">
                  <iframe
                    src={blobUrl}
                    className="w-full h-full rounded-lg border-0"
                    title={fileName}
                    style={{ 
                      minHeight: '70vh',
                      height: '100%'
                    }}
                    onError={() => {
                      setError('Failed to load PDF preview');
                    }}
                  />
                </div>
              )}
            </>
          ) : (
            <div className="flex flex-col items-center justify-center h-full text-center">
              <div className="w-20 h-20 bg-gray-200 rounded-full flex items-center justify-center mb-4">
                <Eye className="w-10 h-10 text-gray-400" />
              </div>
              <h3 className="text-lg font-semibold text-gray-900 mb-2">Preview Not Available</h3>
              <p className="text-sm text-gray-600 mb-6">
                This file type cannot be previewed. Please download to view.
              </p>
              {onDownload && attachmentId && (
                <Button onClick={handleDownload} className="gap-2">
                  <Download className="h-4 w-4" />
                  Download {fileName}
                </Button>
              )}
            </div>
          )}
        </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}

