import { useState, useEffect, useMemo, useCallback } from 'react';
import { Head, router } from '@inertiajs/react';
import {
    FolderIcon, ArrowDownTrayIcon, EyeIcon,
    Squares2X2Icon, ListBulletIcon, MagnifyingGlassIcon,
    ChevronRightIcon, LockClosedIcon, XMarkIcon,
    ChevronLeftIcon, PhotoIcon, VideoCameraIcon,
    DocumentIcon, DocumentTextIcon, ArrowPathIcon,
    ArrowsPointingOutIcon, ArrowsPointingInIcon
} from '@heroicons/react/24/outline';
import { CheckIcon } from '@heroicons/react/24/solid';

interface SharedFile {
    id: number | string;
    name: string;
    url: string;
    file_size?: number;
    mime_type?: string;
    created_at?: string;
    is_image?: boolean;
    is_video?: boolean;
    is_pdf?: boolean;
}

interface SharedFolderItem {
    id: number | string;
    name: string;
    type: string;
    file_count?: number;
    dok_key?: string;
    kegiatan_id?: number;
    sub_id?: number;
    narasumber_id?: number;
    narasumber_field?: string;
    honor_id?: number;
    icon_type?: 'folder' | 'photo' | 'video' | 'doc';
    preview_urls?: string[];
    tanggal?: string;
}

interface BreadcrumbItem {
    id: number | string | null;
    name: string;
    dok_key?: string;
    kegiatan_id?: number;
    sub_id?: number;
}

interface ShareData {
    token: string;
    name: string;
    folder_type: string;
    is_enabled: boolean;
    created_at?: string;
}

interface ShareFolderProps {
    share: ShareData;
    current: {
        id?: number | string | null;
        name: string;
        type: string;
        dok_key?: string;
        kegiatan_id?: number;
        sub_id?: number;
        narasumber_id?: number;
        narasumber_field?: string;
        honor_id?: number;
        surat_type?: string;
        parent_name?: string;
    };
    breadcrumbs: BreadcrumbItem[];
    folders: SharedFolderItem[];
    files: SharedFile[];
    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 ShareFolder({ share, current, breadcrumbs, folders, files, error }: ShareFolderProps) {
    const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
    const [searchQuery, setSearchQuery] = useState('');
    const [navigating, setNavigating] = useState(false);

    // Lightbox state for photos
    const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);
    const [zoomLevel, setZoomLevel] = useState<number>(1);

    // Video modal state
    const [previewVideo, setPreviewVideo] = useState<SharedFile | null>(null);

    // PDF modal state
    const [previewPdf, setPreviewPdf] = useState<SharedFile | null>(null);

    // Filter files and folders by search query
    const filteredFolders = useMemo(() => {
        if (!searchQuery.trim()) return folders;
        const q = searchQuery.toLowerCase();
        return folders.filter(f => f.name.toLowerCase().includes(q));
    }, [folders, searchQuery]);

    const filteredFiles = useMemo(() => {
        if (!searchQuery.trim()) return files;
        const q = searchQuery.toLowerCase();
        return files.filter(f => f.name.toLowerCase().includes(q));
    }, [files, searchQuery]);

    // List of images for lightbox gallery navigation
    const imageFiles = useMemo(() => {
        return filteredFiles.filter(f => f.is_image && f.url);
    }, [filteredFiles]);

    const activeImage = lightboxIndex !== null && imageFiles[lightboxIndex] ? imageFiles[lightboxIndex] : null;

    const openLightbox = (file: SharedFile) => {
        const idx = imageFiles.findIndex(f => f.id === file.id);
        if (idx !== -1) {
            setLightboxIndex(idx);
            setZoomLevel(1);
        }
    };

    const closeLightbox = () => {
        setLightboxIndex(null);
        setZoomLevel(1);
    };

    const nextImage = useCallback(() => {
        if (lightboxIndex !== null && imageFiles.length > 0) {
            setLightboxIndex((lightboxIndex + 1) % imageFiles.length);
            setZoomLevel(1);
        }
    }, [lightboxIndex, imageFiles.length]);

    const prevImage = useCallback(() => {
        if (lightboxIndex !== null && imageFiles.length > 0) {
            setLightboxIndex((lightboxIndex - 1 + imageFiles.length) % imageFiles.length);
            setZoomLevel(1);
        }
    }, [lightboxIndex, imageFiles.length]);

    // Keyboard listener for lightbox
    useEffect(() => {
        const handleKeyDown = (e: KeyboardEvent) => {
            if (lightboxIndex !== null) {
                if (e.key === 'ArrowRight') nextImage();
                if (e.key === 'ArrowLeft') prevImage();
                if (e.key === 'Escape') closeLightbox();
            } else if (previewVideo) {
                if (e.key === 'Escape') setPreviewVideo(null);
            } else if (previewPdf) {
                if (e.key === 'Escape') setPreviewPdf(null);
            }
        };

        window.addEventListener('keydown', handleKeyDown);
        return () => window.removeEventListener('keydown', handleKeyDown);
    }, [lightboxIndex, nextImage, prevImage, previewVideo, previewPdf]);

    // Navigation handler
    const navigateTo = (params: Record<string, any>) => {
        setNavigating(true);
        router.get(`/share/${share.token}`, params, {
            preserveState: true,
            preserveScroll: false,
            onFinish: () => setNavigating(false),
        });
    };

    const handleBreadcrumbClick = (item: BreadcrumbItem) => {
        if (item.id === null) {
            navigateTo({});
        } else if (item.dok_key) {
            navigateTo({ dok: item.dok_key, ...(item.kegiatan_id ? { kegiatan_id: item.kegiatan_id } : {}) });
        } else if (item.sub_id) {
            navigateTo({ sub_id: item.sub_id });
        } else if (item.kegiatan_id) {
            navigateTo({ kegiatan_id: item.kegiatan_id });
        }
    };

    const handleFolderClick = (folder: SharedFolderItem) => {
        if (folder.type === 'kegiatan_dok_folder') {
            navigateTo({ dok: folder.dok_key, ...(folder.kegiatan_id ? { kegiatan_id: folder.kegiatan_id } : {}) });
        } else if (folder.type === 'kegiatan_folder') {
            navigateTo({ kegiatan_id: folder.kegiatan_id });
        } else if (folder.sub_id || folder.type === 'folder') {
            navigateTo({ sub_id: folder.sub_id || folder.id });
        } else if (folder.type === 'narasumber_dok_folder') {
            navigateTo({ narasumber_id: folder.narasumber_id, narasumber_field: folder.narasumber_field });
        } else if (folder.type === 'narasumber_folder') {
            navigateTo({ narasumber_id: folder.narasumber_id });
        } else if (folder.type === 'honor_folder') {
            navigateTo({ honor_id: folder.honor_id });
        }
    };

    // Download URL for the current folder (zip)
    const downloadZipUrl = useMemo(() => {
        const url = new URL(`/share/${share.token}/download`, window.location.origin);
        if (current?.dok_key) url.searchParams.set('dok', current.dok_key);
        if (current?.kegiatan_id) url.searchParams.set('kegiatan_id', String(current.kegiatan_id));
        if (current?.sub_id) url.searchParams.set('sub_id', String(current.sub_id));
        if (current?.narasumber_id) url.searchParams.set('narasumber_id', String(current.narasumber_id));
        if (current?.narasumber_field) url.searchParams.set('narasumber_field', String(current.narasumber_field));
        if (current?.honor_id) url.searchParams.set('honor_id', String(current.honor_id));
        if (current?.surat_type) url.searchParams.set('surat_type', String(current.surat_type));
        return url.toString();
    }, [share.token, current]);

    // Direct binary download URL for individual files (triggers browser save dialog instead of opening in tab)
    const getDownloadFileUrl = (file: SharedFile) => {
        const url = new URL(`/share/${share.token}/file-download`, window.location.origin);
        url.searchParams.set('url', file.url);
        url.searchParams.set('name', file.name);
        return url.toString();
    };

    if (error || !share) {
        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 folder ini tidak aktif, telah kedaluwarsa, atau dinonaktifkan oleh pemilik.'}
                    </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>
        );
    }

    const totalItems = folders.length + files.length;
    const photoCount = files.filter(f => f.is_image).length;

    return (
        <div className="min-h-screen bg-slate-50 flex flex-col selection:bg-sky-500 selection:text-white">
            <Head title={`Folder Dibagikan: ${current.name || share.name}`} />

            {/* Top Navigation Bar */}
            <header className="bg-white border-b border-gray-200/90 sticky top-0 z-30 shadow-2xs">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-3.5 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
                    <div className="flex items-center gap-3 min-w-0">
                        <div className="w-10 h-10 rounded-xl bg-sky-600 text-white flex items-center justify-center shrink-0 shadow-sm shadow-sky-600/20">
                            <FolderIcon className="w-6 h-6" />
                        </div>
                        <div className="min-w-0">
                            <div className="flex items-center gap-2">
                                <h1 className="text-base sm:text-lg font-bold text-gray-900 truncate">
                                    {current.name || share.name}
                                </h1>
                                <span className="shrink-0 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/80">
                                    <CheckIcon className="w-3 h-3 text-emerald-600" /> Hanya Lihat
                                </span>
                            </div>
                            <p className="text-xs text-gray-500 flex items-center gap-2 mt-0.5">
                                <span>SIM-NATAGARA</span>
                                {totalItems > 0 && (
                                    <>
                                        <span>&bull;</span>
                                        <span>{folders.length > 0 ? `${folders.length} folder` : ''} {files.length > 0 ? `${files.length} berkas ${photoCount > 0 ? `(${photoCount} foto)` : ''}` : ''}</span>
                                    </>
                                )}
                            </p>
                        </div>
                    </div>

                    {/* Top Action Buttons */}
                    <div className="flex items-center gap-2 shrink-0 self-end sm:self-center">
                        {/* Download All as ZIP button */}
                        {(files.length > 0 || folders.length > 0) && (
                            <a
                                href={downloadZipUrl}
                                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-all shadow-xs hover:shadow-md cursor-pointer"
                                title="Unduh semua berkas di dalam folder ini sebagai file ZIP"
                            >
                                <ArrowDownTrayIcon className="w-4 h-4" />
                                <span>Unduh Folder (.ZIP)</span>
                            </a>
                        )}
                    </div>
                </div>

                {/* Breadcrumbs Sub-bar */}
                <div className="bg-slate-50 border-t border-gray-200/80 shadow-2xs">
                    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-3 flex flex-col md:flex-row md:items-center md:justify-between text-sm gap-3 sm:gap-4">
                        <nav className="flex items-center gap-2 min-w-0 text-gray-600 flex-wrap sm:flex-nowrap">
                        {breadcrumbs.map((b, idx) => {
                            const isLast = idx === breadcrumbs.length - 1;
                            return (
                                <div key={idx} className="flex items-center gap-2 shrink-0">
                                    {idx > 0 && <ChevronRightIcon className="w-4 h-4 text-gray-400 shrink-0" />}
                                    {isLast ? (
                                        <span className="font-bold text-gray-900 text-sm sm:text-base truncate max-w-[240px] sm:max-w-md bg-white px-2.5 py-1 rounded-lg border border-gray-200/90 shadow-2xs">
                                            {b.name}
                                        </span>
                                    ) : (
                                        <button
                                            type="button"
                                            onClick={() => handleBreadcrumbClick(b)}
                                            className="text-sky-600 hover:text-sky-800 font-semibold hover:underline transition-colors cursor-pointer text-sm truncate max-w-[180px] sm:max-w-xs"
                                        >
                                            {b.name}
                                        </button>
                                    )}
                                </div>
                            );
                        })}
                    </nav>

                    {/* View Controls & Quick Filter */}
                    <div className="flex items-center gap-3 shrink-0 self-stretch sm:self-auto justify-between sm:justify-end">
                        {/* Search input (Bigger, more prominent) */}
                        <div className="relative flex-1 sm:flex-initial">
                            <MagnifyingGlassIcon className="w-4 h-4 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none" />
                            <input
                                type="text"
                                value={searchQuery}
                                onChange={(e) => setSearchQuery(e.target.value)}
                                placeholder="Cari dalam folder..."
                                className="w-full sm:w-64 md:w-72 pl-9 pr-8 py-2 text-sm bg-white border border-gray-300 rounded-xl focus:outline-hidden focus:ring-2 focus:ring-sky-500/40 focus:border-sky-500 text-gray-800 shadow-2xs placeholder:text-gray-400 font-medium transition-all"
                            />
                            {searchQuery && (
                                <button
                                    onClick={() => setSearchQuery('')}
                                    className="absolute right-2.5 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 p-0.5 rounded-full hover:bg-gray-100"
                                >
                                    <XMarkIcon className="w-3.5 h-3.5" />
                                </button>
                            )}
                        </div>

                        {/* View mode toggle */}
                        <div className="flex items-center bg-gray-200/80 p-1 rounded-xl shrink-0">
                            <button
                                type="button"
                                onClick={() => setViewMode('grid')}
                                className={`px-2.5 py-1.5 rounded-lg transition-colors flex items-center gap-1 cursor-pointer ${
                                    viewMode === 'grid' ? 'bg-white text-gray-900 shadow-xs font-semibold' : 'text-gray-600 hover:text-gray-900'
                                }`}
                                title="Tampilan Kisi Foto"
                            >
                                <Squares2X2Icon className="w-4 h-4" />
                            </button>
                            <button
                                type="button"
                                onClick={() => setViewMode('list')}
                                className={`px-2.5 py-1.5 rounded-lg transition-colors flex items-center gap-1 cursor-pointer ${
                                    viewMode === 'list' ? 'bg-white text-gray-900 shadow-xs font-semibold' : 'text-gray-600 hover:text-gray-900'
                                }`}
                                title="Tampilan Daftar"
                            >
                                <ListBulletIcon className="w-4 h-4" />
                            </button>
                        </div>
                    </div>
                    </div>
                </div>
            </header>

            {/* Main Content Body */}
            <main className="flex-1 max-w-7xl w-full mx-auto p-4 sm:p-6 lg:p-8 space-y-8">
                {navigating && (
                    <div className="flex items-center justify-center py-5 text-sky-600 gap-2.5 text-sm font-semibold animate-pulse bg-sky-50/60 rounded-xl border border-sky-100">
                        <ArrowPathIcon className="w-5 h-5 animate-spin text-sky-600" />
                        <span>Memuat isi folder...</span>
                    </div>
                )}

                {/* Subfolders Section */}
                {filteredFolders.length > 0 && (
                    <section className="space-y-4">
                        <div className="flex items-center justify-between">
                            <h2 className="text-sm sm:text-base font-bold text-gray-700 uppercase tracking-wider flex items-center gap-2">
                                <FolderIcon className="w-5 h-5 text-sky-600" />
                                <span>Folder & Kategori ({filteredFolders.length})</span>
                            </h2>
                        </div>

                        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 sm:gap-5">
                            {filteredFolders.map((folder) => {
                                const isPhotoCategory = folder.icon_type === 'photo' || folder.name.toLowerCase().includes('foto');
                                const isVideoCategory = folder.icon_type === 'video' || folder.name.toLowerCase().includes('video');

                                return (
                                    <div
                                        key={String(folder.id)}
                                        onClick={() => handleFolderClick(folder)}
                                        className="group relative bg-white hover:bg-sky-50/50 rounded-2xl border border-gray-200 hover:border-sky-400 p-5 transition-all duration-200 shadow-2xs hover:shadow-md cursor-pointer flex flex-col justify-between min-h-[130px]"
                                    >
                                        <div className="flex items-start gap-3.5">
                                            <div className={`w-12 h-12 rounded-xl flex items-center justify-center shrink-0 transition-transform group-hover:scale-105 shadow-xs ${
                                                isPhotoCategory
                                                    ? 'bg-amber-100 text-amber-600'
                                                    : isVideoCategory
                                                    ? 'bg-sky-100 text-sky-700'
                                                    : 'bg-sky-100 text-sky-600'
                                            }`}>
                                                {isPhotoCategory ? (
                                                    <PhotoIcon className="w-6 h-6" />
                                                ) : isVideoCategory ? (
                                                    <VideoCameraIcon className="w-6 h-6" />
                                                ) : (
                                                    <FolderIcon className="w-6 h-6" />
                                                )}
                                            </div>

                                            <div className="min-w-0 flex-1">
                                                <h3 className="font-bold text-sm sm:text-base text-gray-900 group-hover:text-sky-600 transition-colors line-clamp-2 leading-tight">
                                                    {folder.name}
                                                </h3>
                                                <p className="text-xs sm:text-sm text-gray-500 mt-1 font-medium">
                                                    {folder.file_count !== undefined ? `${folder.file_count} berkas` : folder.tanggal || 'Folder'}
                                                </p>
                                            </div>
                                        </div>

                                        {/* Preview Thumbnail Strip if available */}
                                        {folder.preview_urls && folder.preview_urls.length > 0 && (
                                            <div className="mt-3.5 pt-3 border-t border-gray-100 flex items-center gap-2 overflow-hidden">
                                                {folder.preview_urls.slice(0, 4).map((pUrl, pIdx) => (
                                                    <img
                                                        key={pIdx}
                                                        src={pUrl}
                                                        alt=""
                                                        className="w-8 h-8 rounded-lg object-cover border border-gray-200 bg-gray-100 shrink-0"
                                                        loading="lazy"
                                                    />
                                                ))}
                                                <span className="text-xs text-sky-600 ml-auto font-semibold group-hover:translate-x-0.5 transition-transform flex items-center gap-0.5">
                                                    Buka &rarr;
                                                </span>
                                            </div>
                                        )}
                                    </div>
                                );
                            })}
                        </div>
                    </section>
                )}

                {/* Files / Photos Section */}
                <section className="space-y-4">
                    <div className="flex items-center justify-between">
                        <h2 className="text-sm sm:text-base font-bold text-gray-700 uppercase tracking-wider flex items-center gap-2">
                            <PhotoIcon className="w-5 h-5 text-sky-600" />
                            <span>Berkas & Foto ({filteredFiles.length})</span>
                        </h2>
                    </div>

                    {filteredFiles.length === 0 ? (
                        filteredFolders.length === 0 ? (
                            <div className="py-20 text-center bg-white rounded-3xl border border-dashed border-gray-300 p-8 shadow-xs">
                                <DocumentIcon className="w-16 h-16 text-gray-300 mx-auto mb-3" />
                                <p className="text-base font-bold text-gray-800">Folder ini kosong</p>
                                <p className="text-sm text-gray-500 mt-1">Belum ada foto atau berkas yang diunggah ke dalam folder ini.</p>
                            </div>
                        ) : null
                    ) : viewMode === 'grid' ? (
                        /* GRID VIEW: Bigger, high-impact photo cards */
                        <div className="grid grid-cols-2 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-4 gap-4 sm:gap-6">
                            {filteredFiles.map((file) => {
                                return (
                                    <div
                                        key={String(file.id)}
                                        onClick={() => {
                                            if (file.is_image) openLightbox(file);
                                            else if (file.is_video) setPreviewVideo(file);
                                            else if (file.is_pdf) setPreviewPdf(file);
                                            else window.open(file.url, '_blank');
                                        }}
                                        className="group relative bg-white rounded-2xl border border-gray-200/90 hover:border-sky-400 overflow-hidden shadow-xs hover:shadow-xl transition-all duration-300 cursor-pointer flex flex-col"
                                    >
                                        {/* Thumbnail Container - Larger Aspect Ratio */}
                                        <div className="relative aspect-4/3 w-full bg-slate-100 overflow-hidden flex items-center justify-center">
                                            {file.is_image ? (
                                                <img
                                                    src={file.url}
                                                    alt={file.name}
                                                    loading="lazy"
                                                    className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                                                />
                                            ) : file.is_video ? (
                                                <div className="flex flex-col items-center gap-2 text-sky-600">
                                                    <div className="w-14 h-14 rounded-2xl bg-sky-100 flex items-center justify-center group-hover:scale-110 transition-transform shadow-xs">
                                                        <VideoCameraIcon className="w-8 h-8" />
                                                    </div>
                                                    <span className="text-xs font-bold text-sky-700">Video</span>
                                                </div>
                                            ) : file.is_pdf ? (
                                                <div className="flex flex-col items-center gap-2 text-rose-600">
                                                    <div className="w-14 h-14 rounded-2xl bg-rose-100 flex items-center justify-center group-hover:scale-110 transition-transform shadow-xs">
                                                        <DocumentTextIcon className="w-8 h-8" />
                                                    </div>
                                                    <span className="text-xs font-bold text-rose-700">PDF Dokumen</span>
                                                </div>
                                            ) : (
                                                <div className="flex flex-col items-center gap-2 text-gray-500">
                                                    <div className="w-14 h-14 rounded-2xl bg-gray-100 flex items-center justify-center">
                                                        <DocumentIcon className="w-8 h-8 text-gray-400" />
                                                    </div>
                                                    <span className="text-xs font-bold text-gray-600 uppercase">
                                                        {file.name.split('.').pop() || 'File'}
                                                    </span>
                                                </div>
                                            )}

                                            {/* Hover Quick Overlay Action */}
                                            <div className="absolute inset-0 bg-black/45 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-3 p-3">
                                                <button
                                                    type="button"
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        if (file.is_image) openLightbox(file);
                                                        else if (file.is_video) setPreviewVideo(file);
                                                        else if (file.is_pdf) setPreviewPdf(file);
                                                        else window.open(file.url, '_blank');
                                                    }}
                                                    className="p-2.5 rounded-xl bg-white/95 hover:bg-white text-gray-800 shadow-md transition-transform hover:scale-110 cursor-pointer"
                                                    title="Lihat Pratinjau Foto"
                                                >
                                                    <EyeIcon className="w-5 h-5" />
                                                </button>
                                                <a
                                                    href={getDownloadFileUrl(file)}
                                                    download
                                                    onClick={(e) => e.stopPropagation()}
                                                    className="p-2.5 rounded-xl bg-sky-600 hover:bg-sky-700 text-white shadow-md transition-transform hover:scale-110 cursor-pointer"
                                                    title="Unduh Berkas"
                                                >
                                                    <ArrowDownTrayIcon className="w-5 h-5" />
                                                </a>
                                            </div>
                                        </div>

                                        {/* File Metadata Caption (Bigger & Clearer) */}
                                        <div className="p-3.5 flex-1 flex flex-col justify-between bg-white border-t border-gray-100">
                                            <p className="text-sm font-semibold text-gray-900 line-clamp-1 group-hover:text-sky-600 transition-colors" title={file.name}>
                                                {file.name}
                                            </p>
                                            <div className="flex items-center justify-between text-xs text-gray-400 mt-2">
                                                <span className="font-medium text-gray-500">{formatBytes(file.file_size)}</span>
                                                <a
                                                    href={getDownloadFileUrl(file)}
                                                    download
                                                    onClick={(e) => e.stopPropagation()}
                                                    className="text-gray-400 hover:text-sky-600 transition-colors p-1 hover:bg-sky-50 rounded-lg"
                                                    title="Unduh"
                                                >
                                                    <ArrowDownTrayIcon className="w-4 h-4" />
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                );
                            })}
                        </div>
                    ) : (
                        /* LIST VIEW: Detailed table view */
                        <div className="bg-white rounded-2xl border border-gray-200/90 overflow-hidden shadow-2xs">
                            <div className="overflow-x-auto">
                                <table className="w-full text-left text-xs text-gray-600">
                                    <thead className="bg-gray-50/80 text-gray-400 uppercase text-[10px] font-bold border-b border-gray-100">
                                        <tr>
                                            <th className="py-3 px-4">Nama Berkas</th>
                                            <th className="py-3 px-4">Ukuran</th>
                                            <th className="py-3 px-4 hidden sm:table-cell">Waktu Unggah</th>
                                            <th className="py-3 px-4 text-right">Aksi</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-gray-100">
                                        {filteredFiles.map((file) => (
                                            <tr
                                                key={String(file.id)}
                                                onClick={() => {
                                                    if (file.is_image) openLightbox(file);
                                                    else if (file.is_video) setPreviewVideo(file);
                                                    else if (file.is_pdf) setPreviewPdf(file);
                                                    else window.open(file.url, '_blank');
                                                }}
                                                className="hover:bg-sky-50/50 transition-colors cursor-pointer group"
                                            >
                                                <td className="py-2.5 px-4 font-medium text-gray-900 flex items-center gap-2.5 min-w-[200px]">
                                                    {file.is_image ? (
                                                        <PhotoIcon className="w-4 h-4 text-amber-500 shrink-0" />
                                                    ) : file.is_video ? (
                                                        <VideoCameraIcon className="w-4 h-4 text-sky-600 shrink-0" />
                                                    ) : (
                                                        <DocumentIcon className="w-4 h-4 text-sky-500 shrink-0" />
                                                    )}
                                                    <span className="truncate group-hover:text-sky-600 transition-colors">
                                                        {file.name}
                                                    </span>
                                                </td>
                                                <td className="py-2.5 px-4 text-gray-500 whitespace-nowrap">
                                                    {formatBytes(file.file_size)}
                                                </td>
                                                <td className="py-2.5 px-4 text-gray-400 whitespace-nowrap hidden sm:table-cell">
                                                    {file.created_at || '-'}
                                                </td>
                                                <td className="py-2.5 px-4 text-right whitespace-nowrap" onClick={(e) => e.stopPropagation()}>
                                                    <a
                                                        href={getDownloadFileUrl(file)}
                                                        download
                                                        className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg bg-gray-100 hover:bg-sky-600 hover:text-white text-gray-700 font-semibold transition-colors text-[11px]"
                                                    >
                                                        <ArrowDownTrayIcon className="w-3.5 h-3.5" />
                                                        <span>Unduh</span>
                                                    </a>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    )}
                </section>
            </main>

            {/* LIGHTBOX MODAL: High-resolution photo gallery viewer */}
            {activeImage && (
                <div
                    className="fixed inset-0 z-50 bg-black/95 backdrop-blur-sm flex flex-col animate-in fade-in duration-150"
                    onClick={closeLightbox}
                >
                    {/* Top Controls Bar */}
                    <div
                        className="flex items-center justify-between px-4 sm:px-6 py-3.5 bg-black/40 text-white border-b border-white/10 shrink-0"
                        onClick={(e) => e.stopPropagation()}
                    >
                        <div className="min-w-0 flex items-center gap-3">
                            <span className="text-xs font-semibold px-2.5 py-1 rounded-full bg-white/15 text-white/90">
                                {lightboxIndex! + 1} / {imageFiles.length}
                            </span>
                            <span className="text-xs sm:text-sm font-medium text-white/90 truncate max-w-xs sm:max-w-md">
                                {activeImage.name}
                            </span>
                            <span className="text-xs text-white/50 hidden sm:inline">
                                ({formatBytes(activeImage.file_size)})
                            </span>
                        </div>

                        <div className="flex items-center gap-2 shrink-0">
                            {/* Zoom controls */}
                            <button
                                type="button"
                                onClick={() => setZoomLevel(prev => Math.min(prev + 0.25, 3))}
                                className="p-2 text-white/80 hover:text-white hover:bg-white/15 rounded-lg transition-colors cursor-pointer text-xs font-bold"
                                title="Perbesar"
                            >
                                +
                            </button>
                            <button
                                type="button"
                                onClick={() => setZoomLevel(1)}
                                className="p-2 text-white/80 hover:text-white hover:bg-white/15 rounded-lg transition-colors cursor-pointer text-xs"
                                title="Reset Ukuran"
                            >
                                100%
                            </button>
                            <button
                                type="button"
                                onClick={() => setZoomLevel(prev => Math.max(prev - 0.25, 0.5))}
                                className="p-2 text-white/80 hover:text-white hover:bg-white/15 rounded-lg transition-colors cursor-pointer text-xs font-bold"
                                title="Perkecil"
                            >
                                -
                            </button>

                            {/* Download Button */}
                            <a
                                href={getDownloadFileUrl(activeImage)}
                                download
                                className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-sky-600 hover:bg-sky-500 text-white text-xs font-semibold transition-colors shadow-sm ml-2"
                                title="Unduh Foto Resolusi Penuh"
                            >
                                <ArrowDownTrayIcon className="w-3.5 h-3.5" />
                                <span className="hidden sm:inline">Unduh</span>
                            </a>

                            {/* Close Button */}
                            <button
                                type="button"
                                onClick={closeLightbox}
                                className="p-2 text-white/80 hover:text-white hover:bg-white/15 rounded-lg transition-colors cursor-pointer ml-1"
                                title="Tutup (Esc)"
                            >
                                <XMarkIcon className="w-5 h-5" />
                            </button>
                        </div>
                    </div>

                    {/* Main Image Viewer Area */}
                    <div
                        className="flex-1 relative flex items-center justify-center p-4 overflow-auto select-none"
                        onClick={closeLightbox}
                    >
                        <img
                            src={activeImage.url}
                            alt={activeImage.name}
                            style={{ transform: `scale(${zoomLevel})` }}
                            className="max-h-[85vh] max-w-[90vw] object-contain transition-transform duration-150 rounded-lg shadow-2xl pointer-events-auto"
                            onClick={(e) => e.stopPropagation()}
                        />

                        {/* Navigation Arrows */}
                        {imageFiles.length > 1 && (
                            <>
                                <button
                                    type="button"
                                    onClick={(e) => {
                                        e.stopPropagation();
                                        prevImage();
                                    }}
                                    className="absolute left-4 top-1/2 -translate-y-1/2 p-3 text-white/80 hover:text-white bg-black/50 hover:bg-black/80 rounded-full transition-all cursor-pointer backdrop-blur-md border border-white/10"
                                    title="Foto Sebelumnya (Panah Kiri)"
                                >
                                    <ChevronLeftIcon className="w-6 h-6" />
                                </button>
                                <button
                                    type="button"
                                    onClick={(e) => {
                                        e.stopPropagation();
                                        nextImage();
                                    }}
                                    className="absolute right-4 top-1/2 -translate-y-1/2 p-3 text-white/80 hover:text-white bg-black/50 hover:bg-black/80 rounded-full transition-all cursor-pointer backdrop-blur-md border border-white/10"
                                    title="Foto Berikutnya (Panah Kanan)"
                                >
                                    <ChevronRightIcon className="w-6 h-6" />
                                </button>
                            </>
                        )}
                    </div>
                </div>
            )}

            {/* VIDEO PLAYER MODAL */}
            {previewVideo && (
                <div
                    className="fixed inset-0 z-50 bg-black/90 backdrop-blur-sm flex items-center justify-center p-4 animate-in fade-in"
                    onClick={() => setPreviewVideo(null)}
                >
                    <div
                        className="bg-black rounded-2xl overflow-hidden max-w-4xl w-full border border-white/10 shadow-2xl relative"
                        onClick={(e) => e.stopPropagation()}
                    >
                        <div className="flex items-center justify-between p-3 bg-neutral-900 text-white text-xs border-b border-white/10">
                            <span className="font-semibold truncate">{previewVideo.name}</span>
                            <div className="flex items-center gap-2">
                                <a
                                    href={previewVideo.url}
                                    download
                                    className="p-1.5 text-white/80 hover:text-white hover:bg-white/10 rounded-md"
                                    title="Unduh Video"
                                >
                                    <ArrowDownTrayIcon className="w-4 h-4" />
                                </a>
                                <button
                                    type="button"
                                    onClick={() => setPreviewVideo(null)}
                                    className="p-1.5 text-white/80 hover:text-white hover:bg-white/10 rounded-md"
                                >
                                    <XMarkIcon className="w-4 h-4" />
                                </button>
                            </div>
                        </div>
                        <video
                            src={previewVideo.url}
                            controls
                            autoPlay
                            className="w-full max-h-[75vh] bg-black"
                        />
                    </div>
                </div>
            )}

            {/* PDF VIEWER MODAL */}
            {previewPdf && (
                <div
                    className="fixed inset-0 z-50 bg-black/80 backdrop-blur-sm flex items-center justify-center p-4 animate-in fade-in"
                    onClick={() => setPreviewPdf(null)}
                >
                    <div
                        className="bg-white rounded-2xl overflow-hidden max-w-4xl w-full h-[85vh] border border-gray-200 shadow-2xl flex flex-col"
                        onClick={(e) => e.stopPropagation()}
                    >
                        <div className="flex items-center justify-between p-3 bg-gray-50 border-b border-gray-200 text-xs">
                            <span className="font-semibold text-gray-800 truncate">{previewPdf.name}</span>
                            <div className="flex items-center gap-2">
                                <a
                                    href={previewPdf.url}
                                    download
                                    className="p-1.5 text-gray-600 hover:text-gray-900 hover:bg-gray-200 rounded-md"
                                    title="Unduh PDF"
                                >
                                    <ArrowDownTrayIcon className="w-4 h-4" />
                                </a>
                                <button
                                    type="button"
                                    onClick={() => setPreviewPdf(null)}
                                    className="p-1.5 text-gray-600 hover:text-gray-900 hover:bg-gray-200 rounded-md"
                                >
                                    <XMarkIcon className="w-4 h-4" />
                                </button>
                            </div>
                        </div>
                        <iframe
                            src={previewPdf.url}
                            title={previewPdf.name}
                            className="w-full flex-1 border-none"
                        />
                    </div>
                </div>
            )}

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