import React from 'react';
import Link from 'next/link';
import { ArrowRight } from 'lucide-react';
import { getAllBidang } from '@/lib/data';
import { prisma } from '@/lib/prisma';

export const metadata = {
    title: 'Program Kerja | HMF FPMIPA UPI',
    description: 'Jelajahi berbagai pergerakan dan inovasi dari setiap bidang/lembaga di Himpunan Mahasiswa Fisika FPMIPA UPI.',
};

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>";

export default async function IndeksProgramKerjaPage() {
    const KATEGORI_PROGRAM = await getAllBidang();
    
    // Fetch all leaders (Ketua & Wakil) from database
    const leadersList = await prisma.pengurus.findMany({
        where: {
            OR: [
                { jabatan: { startsWith: 'Ketua' } },
                { jabatan: { startsWith: 'Wakil' } }
            ]
        }
    });

    // Group leaders by division
    const leadersByDivisi = leadersList.reduce((acc: Record<string, any[]>, p) => {
        if (!acc[p.divisi]) acc[p.divisi] = [];
        acc[p.divisi].push(p);
        return acc;
    }, {} as Record<string, any[]>);

    return (
        <div data-theme="dark" className="min-h-screen bg-[#07090f] flex flex-col font-sans selection:bg-[#E63946] selection:text-white pb-24 overflow-x-hidden">
            
            {/* 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" />
                    {/* Dark overlay */}
                    <div className="absolute inset-0 bg-[#07090f]/82"></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">
                            Program Kerja
                        </span>
                        <span className="block text-4xl sm:text-5xl md:text-6xl lg:text-7xl font-black text-white/30 mt-2">
                            Kabinet Niskala Cakra
                        </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">
                        Pilih bidang atau lembaga di bawah ini untuk menelusuri inovasi, gerakan nyata, dan agenda yang diusung oleh fungsionaris Kabinet Niskala Cakra.
                    </p>
                </div>

            </main>

            {/* Category Grid Display - Dark Glassmorphism */}
            <section className="container px-4 md:px-8 mx-auto relative z-10">
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 max-w-6xl mx-auto">
                    {KATEGORI_PROGRAM.map((cat, idx) => {
                        const isLembaga = cat.name.toLowerCase().includes("lembaga");
                        const roleSuffix = isLembaga ? "Lembaga" : "Bidang";
                        
                        const divLeaders = leadersByDivisi[cat.name] || [];
                        const ketua = divLeaders.find(p => p.jabatan.toLowerCase().includes("ketua") && !p.jabatan.toLowerCase().includes("wakil"));
                        const wakil = divLeaders.find(p => p.jabatan.toLowerCase().includes("wakil"));

                        const displayLeaders = [];
                        if (ketua) displayLeaders.push(ketua);
                        if (wakil) displayLeaders.push(wakil);

                        // If no leaders, add placeholders
                        if (displayLeaders.length === 0) {
                            displayLeaders.push(
                                { id: `placeholder-ketua-${cat.slug}`, nama: "Belum Diisi", jabatan: `Ketua ${roleSuffix}`, fotoUrl: DEFAULT_FOTO },
                                { id: `placeholder-wakil-${cat.slug}`, nama: "Belum Diisi", jabatan: `Wakil Ketua ${roleSuffix}`, fotoUrl: DEFAULT_FOTO }
                            );
                        }

                        return (
                            <Link href={`/program-kerja/${cat.slug}`} key={idx} className="group outline-none block h-full">
                                <div className="relative bg-white/5 backdrop-blur-xl rounded-[2rem] p-8 border border-white/10 shadow-[0_8px_32px_0_rgba(0,0,0,0.2)] hover:border-white/30 hover:shadow-[0_8px_40px_0_rgba(59,130,246,0.15)] transition-all duration-500 overflow-hidden flex flex-col gap-6 h-full group-focus-visible:ring-4 group-focus-visible:ring-blue-500/50">
                                    
                                    {/* Ambient Hover Glow (inside card) */}
                                    <div className={`absolute top-0 right-0 w-64 h-64 bg-blue-500/5 rounded-full blur-3xl opacity-0 group-hover:opacity-100 transition-opacity duration-700 pointer-events-none`}></div>

                                    {/* Text Content */}
                                    <div className="relative z-10 flex-grow">
                                        <div className="flex items-center justify-between mb-4">
                                            <h2 className="text-2xl md:text-3xl font-bold text-white leading-tight group-hover:text-blue-400 transition-colors">
                                                {cat.name}
                                            </h2>
                                            <div className="w-10 h-10 rounded-full bg-white/5 border border-white/10 flex items-center justify-center text-gray-400 group-hover:bg-blue-600 group-hover:text-white group-hover:border-blue-500 transition-all duration-300">
                                                <ArrowRight className="w-5 h-5 -rotate-45 group-hover:rotate-0 transition-transform duration-300" />
                                            </div>
                                        </div>
                                        <p className="text-gray-400 text-sm md:text-base leading-relaxed font-medium line-clamp-2">
                                            {cat.desc}
                                        </p>
                                    </div>

                                    {/* Divider */}
                                    <div className="w-full h-px bg-gradient-to-r from-transparent via-white/10 to-transparent my-2"></div>

                                    {/* Leaders Photos */}
                                    <div className="relative z-10 mt-auto">
                                        <div className="flex gap-4">
                                            {displayLeaders.map((leader, i) => (
                                                <div key={leader.id || i} className="relative w-24 md:w-32 aspect-[3/4] rounded-xl bg-white/5 border border-white/20 shadow-md overflow-hidden group/leader hover:-translate-y-1 hover:border-white/40 transition-all duration-300">
                                                    {/* eslint-disable-next-line @next/next/no-img-element */}
                                                    <img 
                                                        src={leader.fotoUrl} 
                                                        alt={leader.nama}
                                                        className={`w-full h-full object-cover transition-transform duration-500 group-hover/leader:scale-110 ${leader.id?.startsWith('placeholder') ? 'opacity-30 invert p-2 object-contain' : ''}`}
                                                    />
                                                    {!leader.id?.startsWith('placeholder') && (
                                                        <div className="absolute inset-0 bg-[#07090f]/80 opacity-0 group-hover/leader:opacity-100 transition-opacity duration-300 flex flex-col items-center justify-center p-2 text-center select-none z-20 backdrop-blur-[2px]">
                                                            <span className="text-[10px] md:text-xs font-bold text-blue-400 uppercase tracking-wider mb-1 line-clamp-1">{leader.jabatan.includes('Wakil') ? 'Wakil' : 'Ketua'}</span>
                                                            <span className="text-xs md:text-sm font-bold text-white line-clamp-2 leading-tight">{leader.nama.split(' ')[0]}</span>
                                                        </div>
                                                    )}
                                                </div>
                                            ))}
                                        </div>
                                    </div>

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