'use client';

import { useState } from 'react';
import { BookOpen, Database, Smartphone, MessageCircle, BookMarked, ExternalLink, FileText, ChevronRight, Zap, FolderOpen, ClipboardList, Eye, X, Maximize2, Minimize2, Folder } from 'lucide-react';
import type { BearrLink, BearrKategori } from '@/lib/data';

// Konfigurasi tiap Kategori
const KATEGORI_CONFIG: Record<BearrKategori, {
    label: string;
    desc: string;
    color: string;
    bgColor: string;
    borderColor: string;
    hoverBorder: string;
    icon: React.ElementType;
    accentBg: string;
}> = {
    bank_soal: {
        label: 'Bank Soal',
        desc: 'Kumpulan soal ujian & latihan dari berbagai mata kuliah Fisika UPI.',
        color: 'text-blue-400',
        bgColor: 'bg-blue-500/10',
        borderColor: 'border-blue-500/20',
        hoverBorder: 'hover:border-blue-400',
        icon: BookOpen,
        accentBg: 'bg-blue-600',
    },
    referensi: {
        label: 'Referensi Belajar',
        desc: 'Catatan & materi belajar sumbangan sukarela dari mahasiswa Fisika UPI.',
        color: 'text-blue-400',
        bgColor: 'bg-blue-500/10',
        borderColor: 'border-blue-500/20',
        hoverBorder: 'hover:border-blue-400',
        icon: BookMarked,
        accentBg: 'bg-blue-600',
    },
    ebook: {
        label: 'E-Book',
        desc: 'Perpustakaan digital untuk mahasiswa. Ajukan e-book baru lewat formulir.',
        color: 'text-blue-400',
        bgColor: 'bg-blue-500/10',
        borderColor: 'border-blue-500/20',
        hoverBorder: 'hover:border-blue-400',
        icon: FileText,
        accentBg: 'bg-blue-600',
    },
    aplikasi: {
        label: 'Aplikasi',
        desc: 'Rekomendasi aplikasi & tools berguna untuk mahasiswa Fisika. Ajukan juga rekomendasimu!',
        color: 'text-blue-400',
        bgColor: 'bg-blue-500/10',
        borderColor: 'border-blue-500/20',
        hoverBorder: 'hover:border-blue-400',
        icon: Smartphone,
        accentBg: 'bg-blue-600',
    },
    responsi: {
        label: 'Responsi',
        desc: 'Layanan belajar bersama dan tanya jawab langsung bersama kakak tingkat.',
        color: 'text-blue-400',
        bgColor: 'bg-blue-500/10',
        borderColor: 'border-blue-500/20',
        hoverBorder: 'hover:border-blue-400',
        icon: MessageCircle,
        accentBg: 'bg-blue-600',
    },
};

const TIPE_ICON: Record<string, React.ElementType> = {
    drive: FolderOpen,
    form: ClipboardList,
    list: Database,
    wa: MessageCircle,
    lainnya: ExternalLink,
};

const TIPE_LABEL: Record<string, string> = {
    drive: 'Buka Google Drive',
    form: 'Isi Formulir',
    list: 'Lihat Daftar',
    wa: 'Hubungi via WhatsApp',
    lainnya: 'Buka Tautan',
};

const KATEGORI_ORDER: BearrKategori[] = ['bank_soal', 'referensi', 'ebook', 'aplikasi', 'responsi'];

/**
 * Mengkonversi berbagai format URL Google Drive menjadi embed info.
 * Mengembalikan { url, type } atau null jika bukan Drive.
 */
function toDriveEmbedInfo(url: string): { url: string; type: 'file' | 'folder' } | null {
    if (!url) return null;

    // Folder: https://drive.google.com/drive/folders/FOLDER_ID
    const folderMatch = url.match(/drive\.google\.com\/drive\/folders\/([a-zA-Z0-9_-]+)/);
    if (folderMatch) {
        return {
            url: `https://drive.google.com/embeddedfolderview?id=${folderMatch[1]}#list`,
            type: 'folder',
        };
    }

    // File: https://drive.google.com/file/d/FILE_ID/...
    const fileMatch = url.match(/drive\.google\.com\/file\/d\/([a-zA-Z0-9_-]+)/);
    if (fileMatch) {
        return {
            url: `https://drive.google.com/file/d/${fileMatch[1]}/preview`,
            type: 'file',
        };
    }

    // Shared link: https://drive.google.com/open?id=FILE_ID
    const openMatch = url.match(/drive\.google\.com\/open\?id=([a-zA-Z0-9_-]+)/);
    if (openMatch) {
        return {
            url: `https://drive.google.com/file/d/${openMatch[1]}/preview`,
            type: 'file',
        };
    }

    // Google Docs/Sheets/Slides
    const docsMatch = url.match(/docs\.google\.com\/(?:document|spreadsheets|presentation)\/d\/([a-zA-Z0-9_-]+)/);
    if (docsMatch) {
        return {
            url: `${url.split('/edit')[0]}/preview`,
            type: 'file',
        };
    }

    return null;
}

// ============================================================
//  Google Drive Viewer Modal (File PDF & Folder)
// ============================================================
function DriveModal({
    url,
    title,
    type,
    originalUrl,
    onClose,
    accentBg,
}: {
    url: string;
    title: string;
    type: 'file' | 'folder';
    originalUrl: string;
    onClose: () => void;
    accentBg: string;
}) {
    const [isExpanded, setIsExpanded] = useState(false);
    const isFolder = type === 'folder';
    return (
        <div
            className="fixed inset-0 z-[999] flex items-center justify-center p-4 md:p-8"
            aria-modal="true"
        >
            {/* Backdrop */}
            <div
                className="absolute inset-0 bg-black/80 backdrop-blur-sm"
                onClick={onClose}
            />

            {/* Modal Container */}
            <div
                className={`relative z-10 w-full bg-white/5 backdrop-blur-md border border-white/10 rounded-3xl shadow-2xl overflow-hidden flex flex-col transition-all duration-300 ${isExpanded
                    ? 'h-[98vh] max-w-[98vw]'
                    : 'max-w-5xl h-[88vh]'
                    }`}
            >
                {/* Modal Header */}
                <div className={`flex items-center justify-between px-5 py-4 ${accentBg} text-white shrink-0`}>
                    <div className="flex items-center gap-3 min-w-0">
                        <div className="p-2 bg-white/5 backdrop-blur-md border border-white/10 rounded-xl shrink-0">
                            {isFolder ? <Folder className="w-5 h-5" /> : <FileText className="w-5 h-5" />}
                        </div>
                        <div className="min-w-0">
                            <p className="text-xs font-semibold opacity-75 uppercase tracking-widest">
                                {isFolder ? 'Jelajah Isi Folder' : 'Pratinjau Dokumen'}
                            </p>
                            <h3 className="font-bold text-lg leading-tight truncate">{title}</h3>
                        </div>
                    </div>
                    <div className="flex items-center gap-2 shrink-0 ml-4">
                        {/* Expand/Shrink */}
                        <button
                            onClick={() => setIsExpanded(v => !v)}
                            className="p-2 rounded-xl bg-white/5 backdrop-blur-md border border-white/10 hover:bg-white/5 backdrop-blur-md border border-white/10/30 transition-colors"
                            title={isExpanded ? 'Perkecil' : 'Perluas layar'}
                        >
                            {isExpanded
                                ? <Minimize2 className="w-4 h-4" />
                                : <Maximize2 className="w-4 h-4" />
                            }
                        </button>
                        {/* Open in new tab */}
                        <a
                            href={originalUrl}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="p-2 rounded-xl bg-white/5 backdrop-blur-md border border-white/10 hover:bg-white/5 backdrop-blur-md border border-white/10/30 transition-colors"
                            title={isFolder ? 'Buka folder di Drive' : 'Buka file di Drive'}
                        >
                            <ExternalLink className="w-4 h-4" />
                        </a>
                        {/* Close */}
                        <button
                            onClick={onClose}
                            className="p-2 rounded-xl bg-white/5 backdrop-blur-md border border-white/10 hover:bg-red-500/100/60 transition-colors"
                            title="Tutup"
                        >
                            <X className="w-4 h-4" />
                        </button>
                    </div>
                </div>

                {/* Info banner untuk Folder */}
                {isFolder && (
                    <div className="shrink-0 px-5 py-2.5 bg-blue-500/100/10 border-b border-blue-100 flex items-center gap-2 text-blue-400 text-xs font-medium">
                        <Folder className="w-3.5 h-3.5 shrink-0" />
                        Klik file PDF di bawah untuk membukanya. Klik tombol ↗ di kanan atas untuk membuka folder di Google Drive.
                    </div>
                )}

                {/* iFrame */}
                <div className="flex-1 min-h-0 bg-white/5 relative">
                    {/* Loading skeleton */}
                    <div className="absolute inset-0 flex items-center justify-center">
                        <div className="text-center space-y-3">
                            <div className="w-16 h-16 border-4 border-white/10 border-t-blue-500 rounded-full animate-spin mx-auto" />
                            <p className="text-sm text-gray-400">
                                {isFolder ? 'Memuat isi folder...' : 'Memuat dokumen...'}
                            </p>
                        </div>
                    </div>
                    <iframe
                        src={url}
                        className="w-full h-full relative z-10"
                        allow="autoplay"
                        style={{ border: 'none' }}
                        title={title}
                    />
                </div>

                {/* Modal Footer */}
                <div className="shrink-0 px-5 py-3 bg-white/5 border-t border-white/10 flex items-center justify-between text-xs text-gray-400">
                    <span>{isFolder ? '📁 Isi folder ditampilkan via Google Drive' : '📄 Dokumen ditampilkan via Google Drive Viewer'}</span>
                    <span>Pastikan file/folder telah dibagikan secara publik</span>
                </div>
            </div>
        </div>
    );
}

// ============================================================
//  Main BEARR Client Component
// ============================================================
export default function BearrClient({ initialData }: { initialData: BearrLink[] }) {
    const [activeTab, setActiveTab] = useState<BearrKategori>('bank_soal');
    const [driveModal, setDriveModal] = useState<{
        url: string;
        title: string;
        type: 'file' | 'folder';
        originalUrl: string;
    } | null>(null);

    const activeConfig = KATEGORI_CONFIG[activeTab];
    const activeLinks = initialData.filter(l => l.kategori === activeTab);
    const Icon = activeConfig.icon;

    const handleOpenDrive = (rawUrl: string, title: string) => {
        const embedInfo = toDriveEmbedInfo(rawUrl);
        if (embedInfo) {
            setDriveModal({ url: embedInfo.url, title, type: embedInfo.type, originalUrl: rawUrl });
        } else {
            window.open(rawUrl, '_blank', 'noopener,noreferrer');
        }
    };

    return (
        <>
            <div data-theme="dark" className="min-h-screen bg-[#07090f] flex flex-col font-sans selection:bg-[#2563EB] selection:text-white pb-24">
            {/* Hero Section */}
            <main className="w-full min-h-[60vh] pt-32 pb-32 bg-[#07090f] overflow-hidden relative flex flex-col items-center justify-center">
                {/* Background: bg-hero.png + dark overlay */}
                <div className="absolute inset-0 z-0">
                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    <img src="/bg-hero.png" alt="" className="w-full h-full object-cover object-center opacity-80 mix-blend-luminosity" />
                    <div className="absolute inset-0 bg-[#07090f]/85"></div>
                </div>

                {/* Bottom Fade Gradient for blending */}
                <div className="absolute bottom-0 left-0 w-full h-40 bg-gradient-to-t from-[#07090f] to-transparent z-10 pointer-events-none"></div>

                {/* Subtle grid */}
                <div className="absolute inset-0 z-[1] pointer-events-none">
                    <div className="absolute inset-0 opacity-[0.04]" style={{backgroundImage: 'linear-gradient(#fff 1px, transparent 1px), linear-gradient(90deg, #fff 1px, transparent 1px)', backgroundSize: '60px 60px'}}></div>
                </div>

                <div className="container px-4 md:px-8 relative z-20 w-full flex flex-col items-center text-center">
                    <h1 className="animate-in fade-in slide-in-from-bottom-6 duration-700 delay-100 font-sans leading-[1.05] tracking-tight mb-6">
                        <span className="block text-4xl sm:text-5xl md:text-6xl lg:text-7xl font-black text-white">
                            BEARR
                        </span>
                        <span className="block text-4xl sm:text-5xl md:text-6xl lg:text-7xl font-black text-white/30 mt-2">
                            Pusat Pembelajaran
                        </span>
                    </h1>

                    <p className="animate-in fade-in slide-in-from-bottom-8 duration-700 delay-200 text-gray-400 text-lg md:text-xl font-light max-w-3xl leading-relaxed mb-4">
                        Bank soal, E-book, Aplikasi, Responsi, dan Referensi Belajar digital mahasiswa Fisika UPI — dikurasi oleh HMF FPMIPA UPI.
                    </p>
                </div>
            </main>

            {/* Tab Navigation */}
            <section className="container px-4 md:px-8 mx-auto relative z-10 -mt-8 mb-12">
                <div className="flex flex-wrap justify-center gap-3">
                    {KATEGORI_ORDER.map((kat) => {
                        const cfg = KATEGORI_CONFIG[kat];
                        const TabIcon = cfg.icon;
                        const count = initialData.filter(l => l.kategori === kat).length;
                        return (
                            <button
                                key={kat}
                                onClick={() => setActiveTab(kat)}
                                className={`flex items-center gap-2 px-6 py-3 rounded-full text-sm font-semibold transition-all duration-300 backdrop-blur-md border ${
                                    activeTab === kat
                                        ? 'bg-blue-600/20 text-white border-blue-500/50 shadow-[0_0_20px_rgba(37,99,235,0.2)]'
                                        : 'bg-white/5 text-gray-400 border-white/10 hover:bg-white/10 hover:text-gray-200'
                                }`}
                            >
                                <TabIcon className="w-4 h-4" />
                                {cfg.label}
                                {count > 0 && (
                                    <span className={`text-[10px] font-bold px-1.5 py-0.5 rounded-full ${activeTab === kat ? 'bg-blue-500 text-white' : 'bg-white/10 text-gray-400'}`}>
                                        {count}
                                    </span>
                                )}
                            </button>
                        );
                    })}
                </div>
            </section>

            {/* Main Content Area */}
                <div className="container px-4 md:px-8 py-8 mx-auto max-w-6xl">
                    <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 items-start">

                        {/* LEFT: Info Sidebar */}
                        <div className="lg:col-span-4 lg:sticky lg:top-[120px] space-y-5">
                            {/* Kategori Card */}
                            <div className={`bg-white/[0.03] backdrop-blur-xl border border-white/[0.05] p-8 rounded-[2rem] shadow-[0_8px_32px_0_rgba(0,0,0,0.3)] relative overflow-hidden group hover:bg-white/[0.04] transition-all duration-500`}>
                                <div className={`absolute -top-20 -right-20 w-48 h-48 ${activeConfig.accentBg} blur-[70px] opacity-20 group-hover:opacity-30 transition-opacity`}></div>
                                
                                <div className="relative z-10">
                                    <div className={`inline-flex items-center justify-center w-14 h-14 bg-white/[0.05] border border-white/10 rounded-2xl mb-6 shadow-xl`}>
                                        <Icon className="w-6 h-6 text-white" />
                                    </div>
                                    <h2 className="text-2xl font-bold mb-2">{activeConfig.label}</h2>
                                    <p className="text-white/80 text-sm leading-relaxed">{activeConfig.desc}</p>
                                </div>
                            </div>

                            {/* Navigasi Cepat ke Kategori Lain */}
                            <div className="bg-white/[0.02] backdrop-blur-lg border border-white/[0.05] rounded-[1.5rem] shadow-xl p-5">
                                <p className="text-xs font-bold text-gray-400 uppercase tracking-widest mb-3 px-2">Kategori Lain</p>
                                <div className="space-y-1">
                                    {KATEGORI_ORDER.filter(k => k !== activeTab).map(kat => {
                                        const cfg = KATEGORI_CONFIG[kat];
                                        const OtherIcon = cfg.icon;
                                        return (
                                            <button
                                                key={kat}
                                                onClick={() => setActiveTab(kat)}
                                                className="w-full flex items-center gap-3 px-3 py-3 rounded-xl hover:bg-white/[0.05] hover:shadow-[0_4px_12px_rgba(0,0,0,0.1)] text-left transition-all duration-300 group"
                                            >
                                                <div className={`w-10 h-10 rounded-xl ${cfg.bgColor} border border-white/[0.05] flex items-center justify-center flex-shrink-0 group-hover:scale-105 transition-transform duration-300`}>
                                                    <OtherIcon className={`w-4 h-4 ${cfg.color}`} />
                                                </div>
                                                <span className="text-sm font-medium text-gray-300 group-hover:text-white">{cfg.label}</span>
                                                <ChevronRight className="w-4 h-4 text-gray-300 ml-auto group-hover:text-gray-400" />
                                            </button>
                                        );
                                    })}
                                </div>
                            </div>
                        </div>

                        {/* RIGHT: Link Cards */}
                        <div className="lg:col-span-8 space-y-4">
                            {activeLinks.length === 0 ? (
                                <div className="bg-white/[0.02] backdrop-blur-lg border border-white/[0.05] rounded-[2rem] p-20 text-center flex flex-col items-center justify-center">
                                    <div className="w-20 h-20 bg-white/[0.05] rounded-3xl rotate-3 flex items-center justify-center mx-auto mb-6 shadow-xl border border-white/10">
                                        <Icon className="w-7 h-7 text-gray-300" />
                                    </div>
                                    <p className="text-gray-400 font-semibold">Belum ada konten untuk kategori ini.</p>
                                    <p className="text-gray-400 text-sm mt-1">Konten sedang disiapkan oleh pengurus HMF.</p>
                                </div>
                            ) : (
                                activeLinks.map((link, idx) => {
                                    const TipeIcon = TIPE_ICON[link.tipe_url] || ExternalLink;
                                    const tipeLabel = TIPE_LABEL[link.tipe_url] || 'Buka Tautan';
                                    const embedInfo = link.url ? toDriveEmbedInfo(link.url) : null;
                                    const isDrive = !!embedInfo;
                                    const isFolder = embedInfo?.type === 'folder';

                                    return (
                                        <div
                                            key={link.id}
                                            className={`bg-white/[0.02] backdrop-blur-xl border border-white/[0.05] rounded-[1.5rem] shadow-[0_8px_32px_0_rgba(0,0,0,0.2)] p-6 hover:bg-white/[0.04] hover:border-white/10 hover:shadow-[0_16px_48px_0_rgba(0,0,0,0.4)] hover:-translate-y-1 transition-all duration-500 group relative overflow-hidden`}
                                        >
                                            <div className={`absolute inset-0 bg-gradient-to-r from-transparent via-white/[0.01] to-transparent -translate-x-full group-hover:translate-x-full duration-[1.5s] transition-transform ease-in-out`}></div>
                                            <div className="flex items-start gap-4">
                                                <div className={`w-12 h-12 rounded-xl ${activeConfig.bgColor} border ${activeConfig.borderColor} flex items-center justify-center flex-shrink-0 mt-0.5`}>
                                                    <TipeIcon className={`w-5 h-5 ${activeConfig.color}`} />
                                                </div>
                                                <div className="flex-1 min-w-0">
                                                    <div className="flex items-start justify-between gap-3 flex-wrap">
                                                        <div>
                                                            <h3 className="font-bold text-white group-hover:text-white transition-colors leading-tight">{link.judul}</h3>
                                                            <span className={`inline-block text-[10px] font-bold uppercase tracking-wider px-2 py-0.5 rounded mt-1 ${activeConfig.bgColor} ${activeConfig.color}`}>
                                                                {link.tipe_url === 'drive' ? 'Google Drive' : link.tipe_url === 'form' ? 'Formulir Google' : link.tipe_url === 'list' ? 'Daftar Dokumen' : link.tipe_url === 'wa' ? 'WhatsApp' : 'Tautan Eksternal'}
                                                            </span>
                                                        </div>
                                                    </div>
                                                    {link.deskripsi && (
                                                        <p className="text-sm text-gray-400 mt-2 leading-relaxed">{link.deskripsi}</p>
                                                    )}
                                                    {/* Action Buttons */}
                                                    <div className="mt-4 flex flex-wrap gap-2">
                                                        {/* Open Viewer — untuk file PDF atau folder Drive */}
                                                        {isDrive && (
                                                            <button
                                                                onClick={() => handleOpenDrive(link.url!, link.judul)}
                                                                className={`inline-flex items-center gap-2 px-6 py-3 rounded-xl text-sm font-bold transition-all duration-300 ${activeConfig.accentBg} text-white shadow-[0_4px_20px_rgba(0,0,0,0.2)] hover:shadow-[0_8px_30px_rgba(255,255,255,0.1)] hover:-translate-y-0.5 active:translate-y-0`}
                                                            >
                                                                {isFolder
                                                                    ? <Folder className="w-4 h-4" />
                                                                    : <Eye className="w-4 h-4" />
                                                                }
                                                                {isFolder ? 'Jelajah Isi Folder' : 'Pratinjau PDF'}
                                                            </button>
                                                        )}

                                                        {/* Open in Drive / External Link Button */}
                                                        {link.url && link.url !== 'https://wa.me/' ? (
                                                            <a
                                                                href={link.url}
                                                                target="_blank"
                                                                rel="noopener noreferrer"
                                                                className={`inline-flex items-center gap-2 px-6 py-3 rounded-xl text-sm font-bold transition-all duration-300 ${isDrive ? 'bg-white/[0.05] border border-white/10 text-gray-300 hover:bg-white/10 hover:text-white hover:-translate-y-0.5' : `${activeConfig.accentBg} text-white shadow-[0_4px_20px_rgba(0,0,0,0.2)] hover:shadow-[0_8px_30px_rgba(255,255,255,0.1)] hover:-translate-y-0.5 active:translate-y-0`}`}
                                                            >
                                                                <TipeIcon className="w-4 h-4" />
                                                                {isDrive ? (isFolder ? 'Buka Folder di Drive' : 'Buka File di Drive') : tipeLabel}
                                                                <ExternalLink className="w-3.5 h-3.5 opacity-70" />
                                                            </a>
                                                        ) : (
                                                            <span className="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold bg-white/5 text-gray-400 cursor-not-allowed border border-white/10">
                                                                <TipeIcon className="w-4 h-4" />
                                                                Segera Hadir
                                                            </span>
                                                        )}
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    );
                                })
                            )}
                        </div>
                    </div>
                </div>
            </div>

            {/* Drive Modal Viewer (File PDF & Folder) */}
            {driveModal && (
                <DriveModal
                    url={driveModal.url}
                    title={driveModal.title}
                    type={driveModal.type}
                    originalUrl={driveModal.originalUrl}
                    onClose={() => setDriveModal(null)}
                    accentBg={activeConfig.accentBg}
                />
            )}
        </>
    );
}
