import { useState, useRef, useEffect } from 'react';
import { Head } from '@inertiajs/react';
import {
    ArrowDownTrayIcon, ArrowsPointingOutIcon, ArrowsPointingInIcon,
    DocumentIcon, LockClosedIcon, CheckIcon, EyeIcon
} from '@heroicons/react/24/solid';

interface SharedFile {
    id: number;
    name: string;
    url: string;
    mime_type?: string;
    file_size?: number;
    created_at?: string;
}

interface SharePreviewProps {
    token?: string;
    file: SharedFile | null;
    error: string | null;
}

function formatBytes(bytes?: number) {
    if (!bytes || bytes === 0) return '0 B';
    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];
}

export default function SharePreview({ token, file, error }: SharePreviewProps) {
    const containerRef = useRef<HTMLDivElement>(null);
    const [isFullScreen, setIsFullScreen] = useState(false);

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

    const downloadFileUrl = () => {
        if (!file?.url) return '#';
        if (token) {
            const url = new URL(`/share/${token}/file-download`, window.location.origin);
            url.searchParams.set('url', file.url);
            url.searchParams.set('name', file.name);
            return url.toString();
        }
        return file.url;
    };

    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);
            }
        }
    };

    if (error || !file) {
        return (
            <div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
                <Head title="Tautan Tidak Aktif" />
                <div className="max-w-md w-full bg-white rounded-2xl border border-gray-200 p-8 text-center shadow-sm">
                    <div className="w-14 h-14 bg-rose-50 text-rose-600 rounded-2xl flex items-center justify-center mx-auto mb-4">
                        <LockClosedIcon className="w-7 h-7" />
                    </div>
                    <h1 className="text-lg font-bold text-gray-900 mb-2">Tautan Bagikan Tidak Tersedia</h1>
                    <p className="text-sm text-gray-500 leading-relaxed mb-6">
                        {error || 'Tautan ini tidak aktif, telah kedaluwarsa, atau ditutup oleh pemilik berkas.'}
                    </p>
                    <div className="pt-4 border-t border-gray-100">
                        <p className="text-xs text-gray-400">SIM-NATAGARA &bull; Sistem Informasi Manajemen</p>
                    </div>
                </div>
            </div>
        );
    }

    return (
        <div className="min-h-screen bg-slate-50 flex flex-col">
            <Head title={`Pratinjau: ${file.name}`} />

            {/* Top Bar */}
            <header className="bg-white border-b border-gray-200 px-4 sm:px-8 py-3.5 flex items-center justify-between sticky top-0 z-30 shadow-2xs">
                <div className="flex items-center gap-3 min-w-0">
                    <div className="w-9 h-9 rounded-xl bg-sky-100 text-sky-600 flex items-center justify-center shrink-0">
                        <EyeIcon className="w-5 h-5" />
                    </div>
                    <div className="min-w-0">
                        <h1 className="text-sm sm:text-base font-bold text-gray-900 truncate">
                            {file.name}
                        </h1>
                        <div className="flex items-center gap-2 text-xs text-gray-500">
                            <span>{formatBytes(file.file_size)}</span>
                            {file.created_at && (
                                <>
                                    <span>&bull;</span>
                                    <span>{file.created_at}</span>
                                </>
                            )}
                            <span className="hidden sm:inline-flex items-center gap-1 text-[11px] font-semibold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded-md border border-emerald-200/60">
                                <CheckIcon className="w-3 h-3" /> Hanya Lihat
                            </span>
                        </div>
                    </div>
                </div>

                <div className="flex items-center gap-2 shrink-0">
                    <a
                        href={downloadFileUrl()}
                        download
                        className="inline-flex items-center gap-2 px-3.5 py-2 bg-sky-600 hover:bg-sky-700 text-white rounded-xl text-xs sm:text-sm font-semibold transition-colors shadow-2xs cursor-pointer"
                    >
                        <ArrowDownTrayIcon className="w-4 h-4" />
                        <span>Unduh Berkas</span>
                    </a>
                </div>
            </header>

            {/* Main Content Area */}
            <main className="flex-1 p-4 sm:p-6 flex items-center justify-center">
                <div className="w-full max-w-5xl">
                    <div
                        ref={containerRef}
                        className={`relative flex items-center justify-center overflow-hidden rounded-2xl border border-gray-200/80 bg-black/5 shadow-sm group min-h-[450px] ${
                            isFullScreen ? 'w-screen h-screen bg-black border-none rounded-none fixed inset-0 z-50' : ''
                        }`}
                    >
                        {/* Floating Buttons inside preview */}
                        <div className="absolute top-4 right-4 z-40 flex items-center gap-2 bg-black/65 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-2 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={file.url}
                                target="_blank"
                                rel="noreferrer"
                                download
                                title="Unduh Berkas"
                                className="p-2 text-white/90 hover:text-white hover:bg-white/20 rounded-lg transition-colors"
                            >
                                <ArrowDownTrayIcon className="w-4 h-4" />
                            </a>
                        </div>

                        {/* Media rendering */}
                        {isImage ? (
                            <img
                                src={file.url}
                                alt={file.name}
                                className={isFullScreen ? "max-h-screen max-w-screen object-contain" : "max-h-[75vh] w-full object-contain"}
                            />
                        ) : isPdf ? (
                            <iframe
                                src={file.url}
                                title={file.name}
                                className={isFullScreen ? "w-screen h-screen border-none" : "h-[78vh] w-full border-none"}
                            />
                        ) : isVideo ? (
                            <video
                                src={file.url}
                                controls
                                autoPlay
                                className={isFullScreen ? "max-h-screen w-full" : "max-h-[75vh] w-full rounded-xl"}
                            />
                        ) : (
                            <div className="flex flex-col items-center gap-3 py-20 text-gray-400">
                                <DocumentIcon className="w-20 h-20 text-gray-300" />
                                <p className="text-base font-semibold text-gray-700">{file.name}</p>
                                <span className="text-xs text-gray-400">Format tidak mendukung pratinjau browser langsung</span>
                                <a
                                    href={file.url}
                                    target="_blank"
                                    rel="noreferrer"
                                    download
                                    className="mt-3 px-4 py-2 bg-sky-600 hover:bg-sky-700 text-white rounded-xl text-xs font-semibold inline-flex items-center gap-2 transition-colors"
                                >
                                    <ArrowDownTrayIcon className="w-4 h-4" />
                                    <span>Unduh Berkas</span>
                                </a>
                            </div>
                        )}
                    </div>
                </div>
            </main>

            {/* Footer */}
            <footer className="bg-white border-t border-gray-200/80 py-3 text-center text-xs text-gray-400">
                Dibagikan melalui SIM-NATAGARA &bull; Hanya dapat dilihat oleh publik dengan tautan ini
            </footer>
        </div>
    );
}
