import { useState, useRef, useEffect } from 'react';
import { Button, Modal } from '@heroui/react';
import {
    ArrowDownTrayIcon,
    ArrowsPointingOutIcon,
    ArrowsPointingInIcon,
    EyeIcon,
    DocumentIcon,
    UserIcon,
    ClockIcon,
    ArrowPathIcon,
    ArrowTopRightOnSquareIcon,
} from '@heroicons/react/24/solid';

interface FilePreviewProps {
    url: string;
    size?: number;
    name?: string;
    fileSize?: number;
    uploader?: string;
    uploadedAt?: string;
    updatedAt?: string;
}

const isImage = (url: string) => /\.(png|jpe?g|gif|webp|svg)(\?.*)?$/i.test(url);
const isPdf = (url: string) => /\.pdf(\?.*)?$/i.test(url);
const isVideo = (url: string) => /\.(mp4|webm|ogg|mov)(\?.*)?$/i.test(url);

const formatBytes = (bytes?: number) => {
    if (!bytes || bytes === 0) return '-';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
};

const getFileName = (url: string, name?: string) => {
    if (name) return name;
    try {
        return decodeURIComponent(url.split('?')[0].split('/').pop() ?? '');
    } catch {
        return url.split('/').pop() ?? 'Berkas';
    }
};

export function FilePreview({
    url,
    size = 40,
    name,
    fileSize,
    uploader,
    uploadedAt,
    updatedAt,
}: FilePreviewProps) {
    const [open, setOpen] = useState(false);
    const containerRef = useRef<HTMLDivElement>(null);
    const [isFullScreen, setIsFullScreen] = useState(false);

    const displayName = getFileName(url, name);
    const hasDetails = !!(uploader || uploadedAt || updatedAt || fileSize || name);

    useEffect(() => {
        const handleFullscreenChange = () => {
            setIsFullScreen(!!document.fullscreenElement);
        };
        document.addEventListener('fullscreenchange', handleFullscreenChange);
        return () => document.removeEventListener('fullscreenchange', handleFullscreenChange);
    }, []);

    const toggleFullScreen = () => {
        if (!document.fullscreenElement) {
            if (containerRef.current?.requestFullscreen) {
                containerRef.current.requestFullscreen().catch(() => {
                    setIsFullScreen(true);
                });
            } else {
                setIsFullScreen(true);
            }
        } else {
            if (document.exitFullscreen) {
                document.exitFullscreen();
            } else {
                setIsFullScreen(false);
            }
        }
    };

    return (
        <>
            <button
                type="button"
                onClick={() => setOpen(true)}
                className="group relative block shrink-0 overflow-hidden rounded-lg border border-gray-200 bg-gray-50 cursor-pointer"
                style={{ width: size, height: size }}
                aria-label="Lihat berkas"
            >
                {isImage(url) ? (
                    <img src={url} alt={displayName} className="w-full h-full object-cover" />
                ) : isVideo(url) ? (
                    <video src={url} className="w-full h-full object-cover" />
                ) : (
                    <div className="flex w-full h-full items-center justify-center text-gray-400">
                        <DocumentIcon style={{ width: size * 0.5, height: size * 0.5 }} />
                    </div>
                )}
                <span className="absolute inset-0 flex items-center justify-center bg-black/0 opacity-0 transition-all group-hover:bg-black/40 group-hover:opacity-100">
                    <ArrowsPointingOutIcon className="w-1/2 h-1/2 text-white" />
                </span>
            </button>

            <Modal isOpen={open} onOpenChange={setOpen}>
                <Modal.Backdrop>
                    <Modal.Container>
                        <Modal.Dialog className={hasDetails ? 'max-w-5xl w-full bg-white' : isPdf(url) || isVideo(url) ? 'max-w-4xl w-full bg-gray-50' : 'max-w-2xl w-full bg-gray-50'}>
                            <Modal.Header className="flex-row! items-center gap-3 pb-3 mb-1 border-b border-gray-100">
                                <Modal.Icon className="bg-sky-100 text-sky-600 shrink-0">
                                    <EyeIcon className="w-5 h-5" />
                                </Modal.Icon>
                                <div className="min-w-0 flex-1">
                                    <Modal.Heading className="text-base font-bold text-gray-900 truncate" title={displayName}>
                                        {displayName}
                                    </Modal.Heading>
                                    <p className="text-xs text-gray-500">{hasDetails ? 'Pratinjau & Detail Berkas' : 'Pratinjau Berkas'}</p>
                                </div>
                            </Modal.Header>
                            <Modal.CloseTrigger />
                            <Modal.Body className="py-3">
                                <div className={hasDetails ? 'grid grid-cols-1 lg:grid-cols-12 gap-5 items-start' : ''}>
                                    {/* Media Viewer */}
                                    <div className={hasDetails ? 'lg:col-span-7 xl:col-span-8 w-full' : 'w-full'}>
                                        <div
                                            ref={containerRef}
                                            className={`relative flex items-center justify-center overflow-hidden rounded-xl border border-gray-200 bg-gray-950 group ${
                                                isFullScreen ? 'fixed inset-0 z-50 w-screen h-screen max-h-screen rounded-none border-none bg-black' : 'min-h-[320px] max-h-[68vh] w-full'
                                            }`}
                                        >
                                            {/* Floating Overlay Actions inside the preview container */}
                                            <div className="absolute top-3 right-3 z-30 flex items-center gap-1.5 bg-black/60 backdrop-blur-md p-1.5 rounded-xl shadow-lg border border-white/10">
                                                <button
                                                    type="button"
                                                    onClick={toggleFullScreen}
                                                    title={isFullScreen ? "Keluar Layar Penuh" : "Layar Penuh"}
                                                    className="p-1.5 text-white/90 hover:text-white hover:bg-white/20 rounded-lg transition-colors cursor-pointer"
                                                >
                                                    {isFullScreen ? (
                                                        <ArrowsPointingInIcon className="w-4 h-4" />
                                                    ) : (
                                                        <ArrowsPointingOutIcon className="w-4 h-4" />
                                                    )}
                                                </button>
                                                <a
                                                    href={url}
                                                    target="_blank"
                                                    rel="noreferrer"
                                                    download
                                                    title="Unduh Berkas"
                                                    className="p-1.5 text-white/90 hover:text-white hover:bg-white/20 rounded-lg transition-colors cursor-pointer"
                                                >
                                                    <ArrowDownTrayIcon className="w-4 h-4" />
                                                </a>
                                            </div>

                                            {isImage(url) ? (
                                                <img
                                                    src={url}
                                                    alt={displayName}
                                                    className={isFullScreen ? "max-h-screen max-w-screen object-contain" : "max-h-[64vh] w-full object-contain"}
                                                />
                                            ) : isPdf(url) ? (
                                                <iframe
                                                    src={url}
                                                    title={displayName}
                                                    className={isFullScreen ? "w-screen h-screen border-none" : "h-[64vh] w-full border-none rounded-lg"}
                                                />
                                            ) : isVideo(url) ? (
                                                <video
                                                    src={url}
                                                    controls
                                                    autoPlay
                                                    className={isFullScreen ? "max-h-screen w-full" : "max-h-[64vh] w-full rounded-lg"}
                                                />
                                            ) : (
                                                <div className="flex flex-col items-center gap-2 py-16 text-gray-400">
                                                    <DocumentIcon className="w-16 h-16 text-gray-500" />
                                                    <span className="text-sm font-medium text-gray-300">Format tidak mendukung pratinjau langsung</span>
                                                    <a
                                                        href={url}
                                                        target="_blank"
                                                        rel="noreferrer"
                                                        download
                                                        className="mt-2 inline-flex items-center gap-1.5 px-3.5 py-2 bg-sky-600 text-white text-xs font-semibold rounded-lg hover:bg-sky-700 transition-colors"
                                                        title="Unduh Berkas"
                                                    >
                                                        <ArrowDownTrayIcon className="w-4 h-4" /> Unduh Berkas
                                                    </a>
                                                </div>
                                            )}
                                        </div>
                                    </div>

                                    {/* Sidebar Detail (jika ada metadata) */}
                                    {hasDetails && (
                                        <div className="lg:col-span-5 xl:col-span-4 flex flex-col justify-between self-stretch gap-4">
                                            <div className="space-y-4">
                                                <div>
                                                    <p className="text-[11px] font-bold uppercase tracking-wider text-gray-400 mb-1">
                                                        Detail Berkas
                                                    </p>
                                                    <h3 className="text-sm font-semibold text-gray-900 break-all select-all leading-snug" title={displayName}>
                                                        {displayName}
                                                    </h3>
                                                </div>

                                                <div className="divide-y divide-gray-100 text-xs">
                                                    {fileSize ? (
                                                        <div className="py-2.5 flex items-center justify-between gap-3">
                                                            <span className="text-gray-500 font-medium">Ukuran</span>
                                                            <span className="text-gray-900 font-semibold">{formatBytes(fileSize)}</span>
                                                        </div>
                                                    ) : null}

                                                    {uploader && (
                                                        <div className="py-2.5 flex items-center justify-between gap-3">
                                                            <span className="text-gray-500 font-medium">Ditambahkan Oleh</span>
                                                            <div className="flex items-center gap-1.5 min-w-0">
                                                                <span className="w-5 h-5 rounded-full bg-sky-100 text-sky-700 flex items-center justify-center shrink-0">
                                                                    <UserIcon className="w-3 h-3" />
                                                                </span>
                                                                <span className="text-gray-900 font-semibold truncate max-w-[140px]">{uploader}</span>
                                                            </div>
                                                        </div>
                                                    )}

                                                    {uploadedAt && (
                                                        <div className="py-2.5 flex items-center justify-between gap-3">
                                                            <span className="text-gray-500 font-medium">Waktu Unggah</span>
                                                            <div className="flex items-center gap-1.5 text-gray-700 font-medium">
                                                                <ClockIcon className="w-3.5 h-3.5 text-gray-400 shrink-0" />
                                                                <span>{uploadedAt}</span>
                                                            </div>
                                                        </div>
                                                    )}

                                                    {updatedAt && (
                                                        <div className="py-2.5 flex items-center justify-between gap-3">
                                                            <span className="text-gray-500 font-medium">Terakhir Diupdate</span>
                                                            <div className="flex items-center gap-1.5 text-gray-700 font-medium">
                                                                <ArrowPathIcon className="w-3.5 h-3.5 text-gray-400 shrink-0" />
                                                                <span>{updatedAt}</span>
                                                            </div>
                                                        </div>
                                                    )}
                                                </div>
                                            </div>

                                            <div className="flex gap-2 pt-2 border-t border-gray-100">
                                                <a
                                                    href={url}
                                                    target="_blank"
                                                    rel="noreferrer"
                                                    download
                                                    className="flex-1 inline-flex items-center justify-center gap-1.5 px-3 py-2 bg-sky-600 hover:bg-sky-700 text-white text-xs font-semibold rounded-lg transition-colors cursor-pointer shadow-xs"
                                                >
                                                    <ArrowDownTrayIcon className="w-4 h-4" /> Unduh Berkas
                                                </a>
                                                <a
                                                    href={url}
                                                    target="_blank"
                                                    rel="noreferrer"
                                                    className="inline-flex items-center justify-center gap-1 px-3 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 text-xs font-medium rounded-lg transition-colors cursor-pointer"
                                                    title="Buka di tab baru"
                                                >
                                                    <ArrowTopRightOnSquareIcon className="w-4 h-4" />
                                                </a>
                                            </div>
                                        </div>
                                    )}
                                </div>
                            </Modal.Body>
                            <Modal.Footer className="border-t border-gray-200 pt-3 flex justify-end">
                                <Button variant="outline" onPress={() => setOpen(false)}>
                                    Tutup
                                </Button>
                            </Modal.Footer>
                        </Modal.Dialog>
                    </Modal.Container>
                </Modal.Backdrop>
            </Modal>
        </>
    );
}
