"use client";

import { useState, useEffect, Suspense } from "react";
import { useSearchParams } from "next/navigation";
import { Instagram, Linkedin, FileText, Calendar } from "lucide-react";

type ParlemenTabsProps = {
    anggotaParlemen: any[];
    produkMumas: any[];
    organigramDpmUrl?: string | null;
};

// Sub-component to handle search params safely within Suspense
function TabHandler({ setActiveTab }: { setActiveTab: (tab: string) => void }) {
    const searchParams = useSearchParams();
    const tabParam = searchParams.get("tab");

    useEffect(() => {
        if (tabParam && ["profil-parlemen", "produk-mumas", "organigram"].includes(tabParam)) {
            setActiveTab(tabParam);
        }
    }, [tabParam, setActiveTab]);

    return null;
}

export function ParlemenTabs({ anggotaParlemen, produkMumas, organigramDpmUrl }: ParlemenTabsProps) {
    const [activeTab, setActiveTab] = useState("profil-parlemen");

    const tabs = [
        { id: "profil-parlemen", label: "Profil Parlemen" },
        { id: "produk-mumas", label: "Produk Mumas" },
        { id: "organigram", label: "Organigram DPM" },
    ];

    // Grouping Anggota Parlemen by komisi
    const groupedAnggota = anggotaParlemen.reduce((acc: Record<string, any[]>, current: any) => {
        const komisi = current.komisi || "Lainnya";
        if (!acc[komisi]) acc[komisi] = [];
        acc[komisi].push(current);
        return acc;
    }, {});

    const sortedKomisi = Object.keys(groupedAnggota).sort((a, b) => {
        if (a.toLowerCase().includes("pimpinan") || a.toLowerCase().includes("ketua")) return -1;
        if (b.toLowerCase().includes("pimpinan") || b.toLowerCase().includes("ketua")) return 1;
        return a.localeCompare(b);
    });

    return (
        <div className="w-full relative z-20 -mt-10 md:-mt-16 container px-4 flex flex-col items-center">
            <Suspense fallback={null}>
                <TabHandler setActiveTab={setActiveTab} />
            </Suspense>
            {/* Tab Navigation */}
            <div className="flex flex-wrap bg-white/5 backdrop-blur-md rounded-t-2xl overflow-hidden border-b border-white/10 justify-center w-full max-w-5xl shadow-[0_8px_32px_0_rgba(0,0,0,0.1)]">
                {tabs.map((tab) => (
                    <button
                        key={tab.id}
                        onClick={() => setActiveTab(tab.id)}
                        className={`px-4 sm:px-6 md:px-10 py-5 font-bold text-sm transition-colors flex-1 md:flex-none text-center relative ${activeTab === tab.id
                            ? "bg-white/10 text-white"
                            : "text-gray-400 hover:text-white hover:bg-white/10"
                            }`}
                    >
                        {activeTab === tab.id && <div className="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-blue-500 to-indigo-500"></div>}
                        {tab.label}
                    </button>
                ))}
            </div>

            {/* Tab Content Container */}
            <div className="bg-white/5 border border-white/20 w-full max-w-5xl rounded-b-2xl md:rounded-tr-none shadow-[0_8px_32px_0_rgba(0,0,0,0.37)] p-6 md:p-12 min-h-[50vh] backdrop-blur-xl relative overflow-hidden">

                {/* TAB 1: PROFIL PARLEMEN */}
                {activeTab === "profil-parlemen" && (
                    <div className="animate-in fade-in slide-in-from-bottom-8 duration-700 min-h-screen pt-4">
                        <div className="text-center space-y-4 mb-20 mx-auto max-w-2xl relative">
                            <span className="inline-block py-1.5 px-4 rounded-full bg-white/10 text-gray-300 text-xs font-bold tracking-widest uppercase mb-4 border border-white/20 backdrop-blur-md">Struktur Organisasi Parlemen</span>
                            <h2 className="text-4xl md:text-5xl font-sans font-black text-white">Anggota Parlemen</h2>
                            <p className="text-gray-300 text-lg leading-relaxed pt-2 font-medium">
                                Mengenal lebih dekat para anggota yang menggerakkan Parlemen Himpunan Mahasiswa Fisika periode ini.
                            </p>
                            <div className="absolute top-0 right-10 w-20 h-20 bg-blue-600/20 rounded-full blur-2xl"></div>
                        </div>

                        {sortedKomisi.length > 0 ? (
                            <div className="space-y-24">
                                {sortedKomisi.map((komisi, index) => (
                                    <div key={index} className="animate-in fade-in slide-in-from-bottom-8 duration-700">
                                        <div className="text-center mb-12 relative">
                                            <h3 className="text-3xl font-sans font-bold text-white inline-block relative">
                                                {komisi}
                                                <div className="absolute -bottom-3 left-1/2 -translate-x-1/2 w-12 h-1.5 bg-gradient-to-r from-blue-500 to-indigo-500 rounded-full"></div>
                                            </h3>
                                        </div>
                                        <div className="flex flex-wrap justify-center gap-8 md:gap-12 relative z-10 w-full px-4 md:px-0">
                                            {groupedAnggota[komisi].map((p: any, idx: number) => (
                                                <div key={idx} className="w-full max-w-[260px] sm:max-w-[300px] flex flex-col items-center">
                                                    <div className="relative w-full aspect-[3/4] bg-white/5 rounded-2xl shadow-[0_8px_32px_0_rgba(0,0,0,0.2)] border border-white/20 overflow-hidden group hover:-translate-y-2 hover:border-white/30 backdrop-blur-md transition-all duration-300">
                                                        <img 
                                                            src={p.fotoUrl || '/placeholder-user.jpg'} 
                                                            alt={p.nama} 
                                                            className="w-full h-full object-cover transition-transform duration-500" 
                                                        />
                                                        {/* Hover Social Overlay */}
                                                        <div className="absolute inset-0 bg-blue-900/60 opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex items-center justify-center gap-3">
                                                            {p.instagramUrl && (
                                                                <a 
                                                                    href={p.instagramUrl.startsWith('http') ? p.instagramUrl : `https://instagram.com/${p.instagramUrl.replace(/^@/, '')}`} 
                                                                    target="_blank" 
                                                                    rel="noopener noreferrer" 
                                                                    className="w-10 h-10 rounded-full bg-white/20 hover:bg-white/40 text-white flex items-center justify-center backdrop-blur-sm transition-all duration-300 hover:scale-110"
                                                                >
                                                                    <Instagram className="w-5 h-5" />
                                                                </a>
                                                            )}
                                                            {p.linkedinUrl && (
                                                                <a 
                                                                    href={p.linkedinUrl.startsWith('http') ? p.linkedinUrl : `https://linkedin.com/in/${p.linkedinUrl}`} 
                                                                    target="_blank" 
                                                                    rel="noopener noreferrer" 
                                                                    className="w-10 h-10 rounded-full bg-white/20 hover:bg-white/40 text-white flex items-center justify-center backdrop-blur-sm transition-all duration-300 hover:scale-110"
                                                                >
                                                                    <Linkedin className="w-5 h-5" />
                                                                </a>
                                                            )}
                                                        </div>
                                                    </div>

                                                    <div className="text-center mt-5 px-3">
                                                        <h4 className="text-base sm:text-lg font-bold text-white leading-tight">{p.jabatan}</h4>
                                                        <p className="text-sm font-semibold text-gray-300 mt-2">{p.nama}</p>
                                                        <span className="inline-block mt-2 px-3 py-1 bg-white/10 border border-white/10 text-gray-400 rounded-full text-[10px] font-bold">Angkatan {p.angkatan}</span>
                                                    </div>
                                                </div>
                                            ))}
                                        </div>
                                    </div>
                                ))}
                            </div>
                        ) : (
                            <div className="text-center py-20 bg-white/5 border border-white/10 rounded-3xl backdrop-blur-md max-w-2xl mx-auto">
                                <p className="text-gray-400 text-lg">Belum ada data anggota parlemen.</p>
                            </div>
                        )}
                    </div>
                )}

                {/* TAB 2: PRODUK MUMAS */}
                {activeTab === "produk-mumas" && (
                    <div className="animate-in fade-in slide-in-from-left-8 duration-700">
                        <div className="text-center space-y-4 mb-16 mx-auto max-w-2xl relative">
                            <h2 className="text-4xl md:text-5xl font-sans font-bold text-white leading-tight">
                                Ketetapan <span className="text-transparent bg-clip-text bg-gradient-to-r from-blue-400 to-indigo-500">Parlemen</span>
                            </h2>
                            <div className="w-20 h-1.5 bg-gradient-to-r from-blue-500 to-indigo-500 rounded-full mx-auto"></div>
                        </div>

                        <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                            {produkMumas.length > 0 ? (
                                produkMumas.map((item, idx) => (
                                    <div key={item.id} className={`bg-white/5 backdrop-blur-md rounded-2xl border border-white/10 overflow-hidden shadow-lg animate-in fade-in slide-in-from-bottom-8 duration-700`} style={{animationDelay: `${idx * 150}ms`}}>
                                        <div className="p-6 border-b border-white/10 flex items-start gap-4">
                                            <div className="w-12 h-12 bg-blue-500/10 rounded-xl flex items-center justify-center flex-shrink-0 border border-blue-500/20">
                                                <FileText className="w-6 h-6 text-blue-400" />
                                            </div>
                                            <div>
                                                <h3 className="text-white font-bold text-lg leading-tight mb-2">{item.judul}</h3>
                                                <div className="flex items-center gap-3 text-sm text-gray-400">
                                                    <span className="flex items-center gap-1 bg-white/5 px-2 py-1 rounded-md text-xs">{item.kategori}</span>
                                                    <span className="flex items-center gap-1">
                                                        <Calendar className="w-3.5 h-3.5" />
                                                        {new Date(item.createdAt).toLocaleDateString('id-ID', { year: 'numeric', month: 'long', day: 'numeric' })}
                                                    </span>
                                                </div>
                                            </div>
                                        </div>
                                        <div className="w-full h-[450px] bg-black/40 p-2 relative group">
                                            <div className="absolute inset-0 flex items-center justify-center bg-black/50 z-0 text-gray-400 text-sm">
                                                Memuat Dokumen...
                                            </div>
                                            <iframe 
                                                src={item.fileUrl.includes('google.com') ? item.fileUrl.replace('/view', '/preview') : item.fileUrl} 
                                                className="w-full h-full rounded-xl bg-white relative z-10" 
                                                title={item.judul}
                                                allow="autoplay"
                                            />
                                        </div>
                                    </div>
                                ))
                            ) : (
                                <div className="col-span-full py-20 text-center bg-white/5 border border-white/10 rounded-3xl backdrop-blur-md">
                                    <div className="w-20 h-20 bg-white/5 rounded-full flex items-center justify-center mx-auto mb-4 border border-white/10">
                                        <FileText className="w-8 h-8 text-gray-400" />
                                    </div>
                                    <h3 className="text-xl font-bold text-white mb-2">Belum ada Produk Mumas</h3>
                                    <p className="text-gray-400">Dokumen ketetapan parlemen akan ditampilkan di sini.</p>
                                </div>
                            )}
                        </div>
                    </div>
                )}

                {/* TAB 3: ORGANIGRAM DPM */}
                {activeTab === "organigram" && (
                    <div className="animate-in fade-in slide-in-from-bottom-8 duration-700 mx-auto flex flex-col items-center pt-4">
                        <div className="space-y-4 relative mb-12 text-center">
                            <span className="inline-block py-1.5 px-4 rounded-full bg-white/10 text-gray-300 text-xs font-bold tracking-widest uppercase mb-4 border border-white/20 backdrop-blur-md">Struktur Organisasi Parlemen</span>
                            <h2 className="text-4xl md:text-5xl font-sans font-bold text-white leading-tight">
                                Organigram <span className="text-transparent bg-clip-text bg-gradient-to-r from-blue-400 to-indigo-500">DPM</span>
                            </h2>
                            <div className="w-20 h-1.5 bg-gradient-to-r from-blue-500 to-indigo-500 rounded-full mx-auto mt-4"></div>
                        </div>

                        {organigramDpmUrl ? (
                            <div className="w-full relative bg-white/5 rounded-2xl border border-white/20 p-2 overflow-hidden shadow-2xl backdrop-blur-md">
                                {/* eslint-disable-next-line @next/next/no-img-element */}
                                <img
                                    src={organigramDpmUrl}
                                    alt="Organigram DPM"
                                    className="w-full h-auto max-w-[1920px] object-contain drop-shadow-2xl mx-auto"
                                />
                            </div>
                        ) : (
                            <div className="flex flex-col items-center justify-center text-gray-400 py-20 bg-white/5 rounded-2xl border border-white/10 w-full max-w-4xl mx-auto">
                                <div className="w-20 h-20 bg-white/5 rounded-full flex items-center justify-center mb-4 border-2 border-dashed border-white/20">
                                    <svg className="w-8 h-8 text-white/40" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
                                    </svg>
                                </div>
                                <p className="text-sm font-medium text-gray-300">Gambar Organigram DPM belum diunggah.</p>
                            </div>
                        )}
                    </div>
                )}
            </div>
        </div>
    );
}
