import { useEffect, useState } from "react";
import { Modal, Button, Spinner, Alert } from "react-bootstrap";
import { MdClose, MdDownload, MdOpenInNew } from "react-icons/md";
import Doctype from "./doctype";

interface FilePreviewProps {
    show: boolean;
    onHide: () => void;
    filePath: string;
    fileName: string;
    fileSize?: number;
    className?: string;
}

export default function FilePreview({
    show,
    onHide,
    filePath,
    fileName,
    fileSize,
    className = ""
}: FilePreviewProps) {
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string>("");
    const [fileUrl, setFileUrl] = useState<string>("");

    const getFileExtension = (filename: string): string => {
        return filename.split('.').pop()?.toLowerCase() || '';
    };

    const isImage = (filename: string): boolean => {
        const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'webp', 'ico'];
        return imageExtensions.includes(getFileExtension(filename));
    };

    const isPDF = (filename: string): boolean => {
        return getFileExtension(filename) === 'pdf';
    };

    const isVideo = (filename: string): boolean => {
        const videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm', 'mkv'];
        return videoExtensions.includes(getFileExtension(filename));
    };

    const isAudio = (filename: string): boolean => {
        const audioExtensions = ['mp3', 'wav', 'ogg', 'flac', 'aac', 'm4a'];
        return audioExtensions.includes(getFileExtension(filename));
    };

    const isText = (filename: string): boolean => {
        const textExtensions = ['txt', 'csv', 'json', 'xml', 'log'];
        return textExtensions.includes(getFileExtension(filename));
    };

    const formatFileSize = (bytes: number): string => {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    };

    useEffect(() => {
        if (show && filePath) {
            setLoading(true);
            setError("");

            // Construct the file URL (assuming files are stored in storage/app/public)
            const fullUrl = filePath;
            setFileUrl(fullUrl);
            setLoading(false);
        }
    }, [show, filePath]);

    const handleDownload = () => {
        if (fileUrl) {
            const link = document.createElement('a');
            link.href = fileUrl;
            link.download = fileName;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    };

    const handleOpenInNewTab = () => {
        if (fileUrl) {
            window.open(fileUrl, '_blank');
        }
    };

    const renderPreviewContent = () => {
        if (loading) {
            return (
                <div className="text-center py-5">
                    <Spinner animation="border" variant="primary" />
                    <div className="mt-2">Loading preview...</div>
                </div>
            );
        }

        if (error) {
            return (
                <Alert variant="danger" className="mb-0">
                    <h6>Preview Error</h6>
                    <p className="mb-0">{error}</p>
                </Alert>
            );
        }

        if (isImage(fileName)) {
            return (
                <div className="text-center">
                    <img
                        src={fileUrl}
                        alt={fileName}
                        className="img-fluid rounded"
                        style={{ maxHeight: '70vh', maxWidth: '100%' }}
                        onError={() => setError('Failed to load image')}
                    />
                </div>
            );
        }

        if (isPDF(fileName)) {
            return (
                <div className="ratio ratio-16x9">
                    <iframe
                        src={fileUrl}
                        title={fileName}
                        className="border rounded"
                        onError={() => setError('Failed to load PDF')}
                    >
                        <p>Your browser does not support iframe. <a href={fileUrl} target="_blank">Open PDF</a></p>
                    </iframe>
                </div>
            );
        }

        if (isVideo(fileName)) {
            return (
                <div className="text-center">
                    <video
                        controls
                        className="w-100 rounded"
                        style={{ maxHeight: '70vh' }}
                        onError={() => setError('Failed to load video')}
                    >
                        <source src={fileUrl} type={`video/${getFileExtension(fileName)}`} />
                        Your browser does not support the video tag.
                    </video>
                </div>
            );
        }

        if (isAudio(fileName)) {
            return (
                <div className="text-center py-4">
                    <div className="mb-4">
                        <Doctype fileName={fileName} iconSize={80} />
                    </div>
                    <audio
                        controls
                        className="w-100"
                        style={{ maxWidth: '400px' }}
                        onError={() => setError('Failed to load audio')}
                    >
                        <source src={fileUrl} type={`audio/${getFileExtension(fileName)}`} />
                        Your browser does not support the audio tag.
                    </audio>
                </div>
            );
        }

        if (isText(fileName)) {
            return (
                <div className="ratio ratio-16x9">
                    <iframe
                        src={fileUrl}
                        title={fileName}
                        className="border rounded"
                        onError={() => setError('Failed to load text file')}
                    >
                        <p>Your browser does not support iframe. <a href={fileUrl} target="_blank">Open file</a></p>
                    </iframe>
                </div>
            );
        }

        // Default preview for other file types
        return (
            <div className="text-center py-5">
                <div className="mb-4">
                    <Doctype fileName={fileName} iconSize={80} />
                </div>
                <h5 className="mb-2">{fileName}</h5>
                {fileSize && (
                    <p className="text-muted mb-3">{formatFileSize(fileSize)}</p>
                )}
                <Alert variant="info" className="mb-0">
                    <h6>Preview not available</h6>
                    <p className="mb-0">This file type cannot be previewed. You can download it to view the contents.</p>
                </Alert>
            </div>
        );
    };

    return (
        <Modal
            show={show}
            onHide={onHide}
            size="xl"
            centered
            className={`file-preview-modal ${className}`}
        >
            <Modal.Header closeButton>
                <Modal.Title className="d-flex align-items-center gap-2 text-truncate">
                    <Doctype fileName={fileName} iconSize={24} />
                    <span className="text-truncate">{fileName}</span>
                </Modal.Title>
            </Modal.Header>
            <Modal.Body className="p-0">
                <div className="p-4">
                    {renderPreviewContent()}
                </div>
            </Modal.Body>
            <Modal.Footer>
                <div className="d-flex gap-2">
                    <Button
                        variant="success"
                        size="sm"
                        className="btn-icon-label"
                        onClick={handleDownload}
                        disabled={!fileUrl}
                    >
                        <MdDownload />
                        <span>Download</span>
                    </Button>
                    <Button
                        variant="outline-secondary"
                        size="sm"
                        className="btn-icon-label"
                        onClick={handleOpenInNewTab}
                        disabled={!fileUrl}
                    >
                        <MdOpenInNew />
                        <span>Open in New Tab</span>
                    </Button>
                </div>
                <Button variant="light" size="sm" onClick={onHide}>
                    Close
                </Button>
            </Modal.Footer>
        </Modal>
    );
}