"use client";

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

type KabinetTabsProps = {
    groupedPengurus: Record<string, any[]>;
    visi: string;
    misiList: string[];
    unggulan: any[];
    lambangUrl?: string | null;
    filosofiLambang?: string | null;
    bidangLembagaList?: any[];
    organigramUrl?: 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 && ["visi-misi", "lambang", "profil", "organigram"].includes(tabParam)) {
            setActiveTab(tabParam);
        }
    }, [tabParam, setActiveTab]);

    return null;
}

export function KabinetTabs({ 
    groupedPengurus, 
    visi, 
    misiList, 
    unggulan, 
    lambangUrl, 
    filosofiLambang,
    bidangLembagaList = [],
    organigramUrl
}: KabinetTabsProps) {
    const [activeTab, setActiveTab] = useState("visi-misi");

    const tabs = [
        { id: "visi-misi", label: "Visi & Misi" },
        { id: "lambang", label: "Lambang Kabinet" },
        { id: "profil", label: "Profil Kabinet" },
        { id: "organigram", label: "Organigram PH" },
    ];

    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: VISI & MISI */}
                {activeTab === "visi-misi" && (
                    <div className="animate-in fade-in slide-in-from-bottom-4 duration-700">
                        <div className="max-w-4xl mx-auto">
                            <div className="relative z-10 space-y-10">
                                {/* Visi */}
                                <div>
                                    <h3 className="font-sans font-bold text-white text-3xl mb-4 tracking-tight flex items-center gap-3">
                                        <div className="w-2 h-8 bg-blue-500 rounded-full"></div>
                                        Visi
                                    </h3>
                                    <p className="text-gray-300 text-lg md:text-xl leading-relaxed font-medium pl-5 italic border-l border-white/10 ml-1">
                                        "{visi}"
                                    </p>
                                </div>

                                <div className="w-full border-t border-white/10"></div>

                                {/* Misi */}
                                <div>
                                    <h3 className="font-sans font-bold text-white text-3xl mb-6 tracking-tight flex items-center gap-3">
                                        <div className="w-2 h-8 bg-indigo-500 rounded-full"></div>
                                        Misi
                                    </h3>
                                    <ul className="text-gray-300 text-base md:text-lg leading-relaxed space-y-4 pl-5">
                                        {misiList.map((misiItem, idx) => (
                                            <li key={idx} className="flex gap-4 items-start">
                                                <span className="text-blue-400 font-bold text-xl leading-tight">&bull;</span>
                                                <span>{misiItem}</span>
                                            </li>
                                        ))}
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                )}


                {/* TAB EXTRA: LAMBANG KABINET */}
                {activeTab === "lambang" && (
                    <div className="animate-in fade-in slide-in-from-left-8 duration-700 max-w-4xl mx-auto flex flex-col items-center text-center">
                        
                        {/* 1. JUDUL */}
                        <div className="space-y-4 relative mb-12">
                            <h2 className="text-4xl md:text-5xl font-sans font-bold text-white leading-tight">
                                Filosofi <span className="text-transparent bg-clip-text bg-gradient-to-r from-blue-400 to-indigo-500">Lambang</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>

                        {/* 2. GAMBAR LAMBANG (Tampil langsung, tanpa shape/card) */}
                        <div className="mb-12 relative w-full max-w-md mx-auto">
                            {lambangUrl ? (
                                // eslint-disable-next-line @next/next/no-img-element
                                <img
                                    src={lambangUrl}
                                    alt="Lambang Kabinet"
                                    className="w-full h-auto object-contain drop-shadow-2xl hover:scale-105 transition-transform duration-500 z-10 relative"
                                />
                            ) : (
                                <div className="flex flex-col items-center justify-center text-gray-400 z-10 py-10">
                                    <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">Bentuk Lambang Belum Diunggah</p>
                                </div>
                            )}
                        </div>

                        {/* 3. TEKS FILOSOFI */}
                        <div className="prose prose-lg prose-invert max-w-none text-gray-300 leading-relaxed text-justify">
                            {filosofiLambang ? (
                                filosofiLambang.split('\n').map((paragraph, idx) => (
                                    paragraph.trim() && (
                                        <p key={idx} className="mb-4">
                                            {paragraph}
                                        </p>
                                    )
                                ))
                            ) : (
                                <p className="italic text-gray-400 bg-white/5 p-6 rounded-2xl border border-white/10 backdrop-blur-md text-center">
                                    Penjelasan mengenai nilai, makna, dan filosofi lambang kabinet ini belum dicantumkan.
                                </p>
                            )}
                        </div>

                    </div>
                )}

                {/* TAB 3: PROFIL KABINET (STRUKTUR ORGANISASI) */}
                {activeTab === "profil" && (() => {
                    const pimpinan = groupedPengurus["Pimpinan"] || [];
                    const DEFAULT_FOTO = "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23cccccc'><path d='M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z'/></svg>";

                    // Kahim & Wakahim
                    const kahim = pimpinan.find(p => p.jabatan.toLowerCase() === "ketua himpunan");
                    const wakahim = pimpinan.find(p => p.jabatan.toLowerCase() === "wakil ketua himpunan");

                    const displayPimpinan = [
                        kahim || { id: "placeholder-kahim", nama: "Belum Diisi", jabatan: "Ketua Himpunan", fotoUrl: DEFAULT_FOTO, angkatan: "-" },
                        wakahim || { id: "placeholder-wakahim", nama: "Belum Diisi", jabatan: "Wakil Ketua Himpunan", fotoUrl: DEFAULT_FOTO, angkatan: "-" }
                    ];

                    const order = [
                        "Lembaga Kesekretariatan",
                        "Lembaga Keuangan",
                        "Bidang Akademik",
                        "Bidang Ekonomi dan Bisnis",
                        "Bidang Kaderisasi",
                        "Bidang Kerohanian",
                        "Bidang Komunikasi dan Media Informasi",
                        "Bidang Penelitian dan Pengembangan",
                        "Bidang Pengembangan Minat dan Bakat",
                        "Bidang Sosial dan Politik"
                    ];

                    // Sort dynamically based on bidangLembagaList if available
                    const sortedDivisions = bidangLembagaList && bidangLembagaList.length > 0
                        ? [...bidangLembagaList].sort((a, b) => {
                            const idxA = order.indexOf(a.name);
                            const idxB = order.indexOf(b.name);
                            if (idxA !== -1 && idxB !== -1) return idxA - idxB;
                            if (idxA !== -1) return -1;
                            if (idxB !== -1) return 1;
                            return a.name.localeCompare(b.name);
                          })
                        : order.map(name => ({ name, slug: name.toLowerCase().replace(/\s+/g, '-') }));

                    return (
                        <div className="animate-in fade-in slide-in-from-bottom-8 duration-700 min-h-screen">
                            <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</span>
                                <h2 className="text-4xl md:text-5xl font-sans font-black text-white">Niskala Cakra</h2>
                                <p className="text-gray-300 text-lg leading-relaxed pt-2 font-medium">
                                    Mengenal lebih dekat para fungsionaris yang menggerakkan roda organisasi 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>

                            {/* Pimpinan Section */}
                            <div className="mb-24 relative">
                                <div className="text-center mb-12 relative z-10">
                                    <h3 className="text-3xl font-sans font-bold text-white inline-block relative">
                                        Pimpinan
                                        <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">
                                    {displayPimpinan.map(person => (
                                        <div key={person.id} 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={person.fotoUrl} 
                                                    alt={person.nama} 
                                                    className={`w-full h-full object-cover transition-transform duration-500 ${person.id.startsWith('placeholder') ? 'p-10 opacity-35 object-contain filter invert' : ''}`} 
                                                />
                                                {/* Hover Social Overlay */}
                                                {!person.id.startsWith('placeholder') && (
                                                    <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">
                                                        {person.instagramUrl && (
                                                            <a 
                                                                href={person.instagramUrl.startsWith('http') ? person.instagramUrl : `https://instagram.com/${person.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>
                                                        )}
                                                        {person.linkedinUrl && (
                                                            <a 
                                                                href={person.linkedinUrl.startsWith('http') ? person.linkedinUrl : `https://linkedin.com/in/${person.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>
                                    ))}
                                </div>
                            </div>

                            {/* Divisions Section */}
                            <div className="space-y-24">
                                {sortedDivisions.map(div => {
                                    const members = groupedPengurus[div.name] || [];
                                    const isLembaga = div.name.toLowerCase().includes("lembaga");
                                    const roleSuffix = isLembaga ? "Lembaga" : "Bidang";

                                    const ketua = members.find((p: any) => p.jabatan.toLowerCase().includes("ketua") && !p.jabatan.toLowerCase().includes("wakil"));
                                    const wakil = members.find((p: any) => p.jabatan.toLowerCase().includes("wakil"));
                                    const stafList = members.filter((p: any) => !p.jabatan.toLowerCase().includes("ketua") && !p.jabatan.toLowerCase().includes("wakil"));

                                    const displayMembers = [];

                                    // Ketua
                                    if (ketua) {
                                        displayMembers.push(ketua);
                                    } else {
                                        displayMembers.push({
                                            id: `placeholder-ketua-${div.slug}`,
                                            nama: "Belum Diisi",
                                            jabatan: `Ketua ${roleSuffix}`,
                                            fotoUrl: DEFAULT_FOTO,
                                            angkatan: "-"
                                        });
                                    }

                                    // Wakil
                                    if (wakil) {
                                        displayMembers.push(wakil);
                                    } else {
                                        displayMembers.push({
                                            id: `placeholder-wakil-${div.slug}`,
                                            nama: "Belum Diisi",
                                            jabatan: `Wakil Ketua ${roleSuffix}`,
                                            fotoUrl: DEFAULT_FOTO,
                                            angkatan: "-"
                                        });
                                    }

                                    // Staf
                                    if (stafList.length > 0) {
                                        displayMembers.push(...stafList);
                                    } else {
                                        displayMembers.push({
                                            id: `placeholder-staf-${div.slug}`,
                                            nama: "Belum Diisi",
                                            jabatan: `Staf ${roleSuffix}`,
                                            fotoUrl: DEFAULT_FOTO,
                                            angkatan: "-"
                                        });
                                    }

                                    return (
                                        <section key={div.name} className="relative">
                                            <div className="flex flex-col items-center mb-16 text-center">
                                                <h4 className="text-2xl md:text-3xl font-sans font-bold text-white">{div.name}</h4>
                                                <div className="w-12 h-1.5 bg-gradient-to-r from-blue-500 to-indigo-500 rounded-full mt-4"></div>
                                            </div>

                                            <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-x-4 gap-y-10 p-2 max-w-6xl mx-auto">
                                                {displayMembers.map(person => (
                                                    <div key={person.id} className="w-full flex flex-col items-center">
                                                        <div className="relative w-full aspect-[3/4] max-w-[180px] bg-white/5 rounded-xl 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">
                                                            {/* eslint-disable-next-line @next/next/no-img-element */}
                                                            <img 
                                                                src={person.fotoUrl} 
                                                                alt={person.nama} 
                                                                className={`w-full h-full object-cover transition-transform duration-500 ${person.id.startsWith('placeholder') ? 'p-6 opacity-35 object-contain filter invert' : ''}`} 
                                                            />
                                                            {/* Hover Social Overlay */}
                                                            {!person.id.startsWith('placeholder') && (
                                                                <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-2">
                                                                    {person.instagramUrl && (
                                                                        <a 
                                                                            href={person.instagramUrl.startsWith('http') ? person.instagramUrl : `https://instagram.com/${person.instagramUrl.replace(/^@/, '')}`} 
                                                                            target="_blank" 
                                                                            rel="noopener noreferrer" 
                                                                            className="w-8 h-8 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-4 h-4" />
                                                                        </a>
                                                                    )}
                                                                    {person.linkedinUrl && (
                                                                        <a 
                                                                            href={person.linkedinUrl.startsWith('http') ? person.linkedinUrl : `https://linkedin.com/in/${person.linkedinUrl}`} 
                                                                            target="_blank" 
                                                                            rel="noopener noreferrer" 
                                                                            className="w-8 h-8 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-4 h-4" />
                                                                        </a>
                                                                    )}
                                                                </div>
                                                            )}
                                                        </div>


                                                    </div>
                                                ))}
                                            </div>
                                        </section>
                                    );
                                })}
                            </div>

                        </div>
                    );
                })()}

                {/* TAB EXTRA: ORGANIGRAM */}
                {activeTab === "organigram" && (
                    <div className="animate-in fade-in slide-in-from-bottom-8 duration-700 mx-auto flex flex-col items-center">
                        <div className="space-y-4 relative mb-12 text-center">
                            <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">PH</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>

                        {organigramUrl ? (
                            <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={organigramUrl}
                                    alt="Organigram PH"
                                    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">
                                <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 belum diunggah</p>
                            </div>
                        )}
                    </div>
                )}
            </div>
        </div>
    );
}
