import React from 'react';
import Link from 'next/link';
import { notFound } from 'next/navigation';
import { getBidangBySlug, getProkerByBidang, getPengurusByDivisi, getAllPengurus } from '@/lib/data';
import { ChevronLeft, Compass, Target, Sparkles, FolderOpen, Clock, Users, CheckCircle2, Circle, Timer, Instagram, Linkedin } from 'lucide-react';

export const dynamic = 'force-dynamic';

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
    const { slug } = await params;
    const category = await getBidangBySlug(slug);
    if (!category) return { title: 'Program Kerja Tidak Ditemukan' };

    return {
        title: `${category.name} | Program Kerja HMF FPMIPA UPI`,
        description: category.desc,
    };
}

const statusConfig = {
    PLANNING: { label: 'Perencanaan', icon: Circle, color: 'text-amber-400 bg-amber-500/10 border-amber-500/20' },
    ONGOING: { label: 'Sedang Berjalan', icon: Timer, color: 'text-blue-400 bg-blue-500/10 border-blue-500/20' },
    COMPLETED: { label: 'Selesai', icon: CheckCircle2, color: 'text-emerald-400 bg-emerald-500/10 border-emerald-500/20' },
};

export default async function DetailProgramKerjaPage({ params }: { params: Promise<{ slug: string }> }) {
    const { slug } = await params;
    const category = await getBidangBySlug(slug);

    if (!category) {
        notFound();
    }

    // Ambil pengurus & proker dari DB via data.ts
    const [pengurus, programs, allPengurus] = await Promise.all([
        getPengurusByDivisi(category.name),
        getProkerByBidang(slug),
        getAllPengurus(),
    ]);

    const allPengurusList = allPengurus || [];

    const isLembaga = category.name.toLowerCase().includes("lembaga");
    const roleSuffix = isLembaga ? "Lembaga" : "Bidang";
    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>";

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

    const displayPengurus: any[] = [];

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

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

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

    return (
        <div data-theme="dark" className="min-h-screen bg-[#07090f] flex flex-col pt-24 pb-24 font-sans selection:bg-[#E63946] selection:text-white">

            {/* Background elements */}
            <div className="fixed inset-0 z-0 pointer-events-none">
            </div>

            {/* Minimalist Top Navigation */}
            <div className="container px-4 md:px-8 mx-auto mb-10 relative z-10">
                <Link
                    href="/program-kerja"
                    className="inline-flex items-center gap-2 text-sm font-semibold tracking-wide text-gray-400 hover:text-white transition-colors bg-white/5 border border-white/10 px-4 py-2 rounded-full backdrop-blur-md hover:bg-white/10"
                >
                    <ChevronLeft className="w-4 h-4" />
                    Kembali ke Program Kerja
                </Link>
            </div>

            {/* Editorial Hero Section */}
            <section className="container px-4 md:px-8 mx-auto mb-20 relative z-10">
                <div className="max-w-4xl relative space-y-6">

                    {/* Decorative background typography */}
                    <div className="absolute -top-16 -left-8 text-[120px] lg:text-[180px] font-bold text-white/5 pointer-events-none tracking-tighter leading-none select-none -z-10">
                        {category.shortName.toUpperCase()}
                    </div>

                    <div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-white/10 border border-white/20 backdrop-blur-md shadow-sm text-blue-400 text-xs font-bold tracking-widest uppercase relative z-10">
                        <Compass className="w-3.5 h-3.5" />
                        Ruang Lingkup
                    </div>

                    <h1 className="text-4xl sm:text-5xl md:text-6xl font-sans font-black text-white leading-[1.1] tracking-tight relative z-10 pb-4">
                        {category.name}
                    </h1>

                    {/* Intro Block (Description) */}
                    <div className="relative z-10">
                        <div className="pl-6 border-l-4 border-blue-500/50 py-2">
                            <p className="text-xl md:text-2xl text-gray-300 font-medium leading-relaxed">
                                {category.desc}
                            </p>
                        </div>
                    </div>

                </div>
            </section>

            {/* Section: Pengurus Bidang */}
            <section className="container px-4 md:px-8 mx-auto relative z-10 mb-20">
                <div className="flex items-center gap-3 mb-10">
                    <div className="p-2 bg-blue-500/20 rounded-lg text-blue-400 border border-blue-500/20">
                        <Users className="w-5 h-5" />
                    </div>
                    <h2 className="text-2xl font-bold text-white tracking-tight">Pimpinan & Staff</h2>
                    <div className="h-px flex-1 bg-gradient-to-r from-white/10 to-transparent ml-4"></div>
                </div>

                <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
                    {displayPengurus.map((p: any, idx: number) => (
                        <div key={p.id || idx} className="bg-white/5 backdrop-blur-md rounded-2xl overflow-hidden border border-white/10 shadow-[0_8px_32px_0_rgba(0,0,0,0.2)] hover:border-white/30 hover:-translate-y-2 transition-all duration-300 flex flex-col group relative">
                            <div className="w-full aspect-[3/4] bg-white/5 relative overflow-hidden">
                                <img 
                                    src={p.fotoUrl} 
                                    alt={p.nama} 
                                    className={`w-full h-full object-cover transition-transform duration-500 ${p.id && p.id.startsWith('placeholder') ? 'p-8 opacity-40 object-contain filter invert' : ''}`} 
                                />
                                {/* Hover overlay with Name, Position and Social Links */}
                                {!p.id?.startsWith('placeholder') && (
                                    <div className="absolute inset-0 bg-[#07090f]/80 opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex flex-col items-center justify-center p-3 text-center select-none z-20 backdrop-blur-sm">
                                        <h4 className="text-white font-bold text-xs leading-tight mb-1 line-clamp-2">{p.nama}</h4>
                                        <p className="text-gray-300 text-[10px] leading-snug mb-3 line-clamp-2">{p.jabatan}</p>
                                        <div className="flex gap-2">
                                            {p.instagramUrl && (
                                                <a 
                                                    href={p.instagramUrl.startsWith('http') ? p.instagramUrl : `https://instagram.com/${p.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-200"
                                                >
                                                    <Instagram className="w-3.5 h-3.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-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-200"
                                                >
                                                    <Linkedin className="w-3.5 h-3.5" />
                                                </a>
                                            )}
                                        </div>
                                    </div>
                                )}
                            </div>
                        </div>
                    ))}
                </div>
            </section>

            {/* Section: Daftar Program Kerja dari Database */}
            <section className="container px-4 md:px-8 mx-auto relative z-10">
                <div className="flex items-center gap-3 mb-10">
                    <div className="p-2 bg-indigo-500/20 rounded-lg text-indigo-400 border border-indigo-500/20">
                        <FolderOpen className="w-5 h-5" />
                    </div>
                    <h2 className="text-2xl font-bold text-white tracking-tight">Daftar Program Kerja</h2>
                    <div className="h-px flex-1 bg-gradient-to-r from-white/10 to-transparent ml-4"></div>
                </div>

                {programs.length > 0 ? (
                    <div className="grid grid-cols-1 gap-8 max-w-4xl mx-auto">
                        {programs.map((prog: any, idx: number) => {
                            const status = statusConfig[prog.status as keyof typeof statusConfig] || statusConfig.PLANNING;
                            const StatusIcon = status.icon;

                            // Parse Penanggung Jawab (PIC)
                            let picList: any[] = [];
                            if (prog.penanggungJawab) {
                                try {
                                    const picIds = JSON.parse(prog.penanggungJawab);
                                    if (Array.isArray(picIds)) {
                                        picList = picIds
                                            .map((id: string) => allPengurusList.find((p: any) => p.id === id))
                                            .filter(Boolean);
                                    }
                                } catch (e) {
                                    // Ignore parsing errors
                                }
                            }

                            return (
                                <div
                                    key={prog.id}
                                    className="group relative bg-white/5 backdrop-blur-xl border border-white/10 rounded-[2rem] p-8 md:p-10 hover:shadow-[0_8px_32px_0_rgba(0,0,0,0.3)] hover:border-white/30 hover:-translate-y-1 transition-all duration-500 flex flex-col gap-6 overflow-hidden"
                                >
                                    {/* Background glow hover */}
                                    <div className={`absolute top-0 right-0 w-64 h-64 bg-blue-500/10 rounded-full blur-3xl opacity-0 group-hover:opacity-100 transition-opacity duration-700 pointer-events-none`}></div>

                                    <div className="relative z-10 flex flex-col md:flex-row gap-6 md:gap-8 justify-between items-start">
                                        {/* Left part: Icon & Content */}
                                        <div className="flex-1 space-y-4">
                                            <div className="flex items-center gap-4">
                                                <div className="w-12 h-12 rounded-2xl flex items-center justify-center shadow-[0_4px_16px_rgba(0,0,0,0.2)] bg-white/10 border border-white/20 text-white group-hover:bg-blue-600 group-hover:border-blue-500 transition-colors duration-300">
                                                    <Target className="w-6 h-6" />
                                                </div>
                                                <div>
                                                    <span className="text-xs font-bold text-gray-400 uppercase tracking-widest">Program Kerja {(idx + 1).toString().padStart(2, '0')}</span>
                                                    <h3 className="text-2xl font-bold leading-tight text-white group-hover:text-blue-400 transition-colors">
                                                        {prog.nama}
                                                    </h3>
                                                </div>
                                            </div>

                                            <p className="text-gray-300 leading-relaxed text-base whitespace-pre-line text-justify font-medium">
                                                {prog.deskripsi}
                                            </p>
                                        </div>

                                        {/* Right part: Status */}
                                        <div className="flex-shrink-0">
                                            <span className={`inline-flex items-center gap-1.5 px-4 py-1.5 rounded-full text-xs font-bold border uppercase tracking-wider backdrop-blur-md ${status.color}`}>
                                                <StatusIcon className="w-4 h-4" />
                                                {status.label}
                                            </span>
                                        </div>
                                    </div>

                                    {/* PIC Section */}
                                    {picList.length > 0 && (
                                        <div className="relative z-10 pt-6 border-t border-white/10 flex flex-col gap-4">
                                            <span className="text-[10px] font-bold text-gray-400 uppercase tracking-widest">Penanggung Jawab (PIC)</span>
                                            <div className="flex flex-wrap gap-4">
                                                {picList.map((pic) => (
                                                    <div key={pic.id} className="relative w-24 md:w-32 aspect-[3/4] rounded-xl bg-white/5 border border-white/20 shadow-md overflow-hidden group/pic hover:-translate-y-1 hover:border-white/40 transition-all duration-300">
                                                        <img
                                                            className="w-full h-full object-cover transition-transform duration-500 group-hover/pic:scale-110"
                                                            src={pic.fotoUrl}
                                                            alt={pic.nama}
                                                        />
                                                        <div className="absolute inset-0 bg-[#07090f]/80 opacity-0 group-hover/pic: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">{pic.jabatan.includes('Staf') ? 'Staf' : 'Ketua'}</span>
                                                            <span className="text-xs md:text-sm font-bold text-white line-clamp-2 leading-tight">{pic.nama.split(' ')[0]}</span>
                                                        </div>
                                                    </div>
                                                ))}
                                            </div>
                                        </div>
                                    )}

                                    {/* Decorative bottom line */}
                                    <div className="h-1 w-1/4 rounded-full mt-2 opacity-0 group-hover:opacity-100 group-hover:w-full transition-all duration-700 bg-gradient-to-r from-blue-500 to-indigo-500"></div>
                                </div>
                            );
                        })}
                    </div>
                ) : (
                    <div className="text-center py-20 bg-white/5 rounded-3xl border border-dashed border-white/10 backdrop-blur-md">
                        <Sparkles className="w-10 h-10 text-gray-500 mx-auto mb-4" />
                        <p className="text-gray-400 font-medium">Belum ada program kerja yang ditambahkan untuk bidang ini.</p>
                        <p className="text-gray-500 text-sm mt-1">Admin dapat menambahkannya melalui dashboard.</p>
                    </div>
                )}
            </section>
        </div>
    );
}
