import React from 'react';
import Link from 'next/link';
import { notFound } from 'next/navigation';
import { ChevronLeft, Calendar } from 'lucide-react';
import { prisma } from '@/lib/prisma';
import ReactMarkdown from 'react-markdown';
import AcaraTabs from '@/components/public/acara-tabs';

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
    const { slug } = await params;
    let acara: any = null;
    
    if (prisma.acara && typeof prisma.acara.findUnique === 'function') {
        try {
            acara = await prisma.acara.findUnique({ where: { slug } });
        } catch (e) {
            console.error(e);
        }
    } else {
        try {
            const res: any[] = await prisma.$queryRaw`SELECT * FROM Acara WHERE slug = ${slug} LIMIT 1`;
            if (res.length > 0) acara = res[0];
        } catch (e) {}
    }
    
    if (!acara) return { title: 'Acara Tidak Ditemukan' };

    return {
        title: `${acara.nama} | Acara HMF FPMIPA UPI`,
        description: (acara.deskripsi || '').substring(0, 150) + '...',
    };
}

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 DetailAcaraPage({ params }: { params: Promise<{ slug: string }> }) {
    const { slug } = await params;
    let acara: any = null;

    if (prisma.acara && typeof prisma.acara.findUnique === 'function') {
        try {
            acara = await prisma.acara.findUnique({ 
                where: { slug },
                include: { tabs: { orderBy: { urutan: 'asc' } } }
            });
        } catch (e) {
            console.error("Prisma error:", e);
            // Fallback to basic fetch if include fails due to outdated client
            try {
                acara = await prisma.acara.findUnique({ where: { slug } });
                if (acara) {
                    try {
                        const tabsRes: any[] = await prisma.$queryRaw`SELECT * FROM AcaraTab WHERE acaraId = ${acara.id} ORDER BY urutan ASC`;
                        acara.tabs = tabsRes;
                    } catch (err) {}
                }
            } catch (err2) {}
        }
    } else {
        try {
            const res: any[] = await prisma.$queryRaw`SELECT * FROM Acara WHERE slug = ${slug} LIMIT 1`;
            if (res.length > 0) {
                acara = res[0];
                const tabsRes: any[] = await prisma.$queryRaw`SELECT * FROM AcaraTab WHERE acaraId = ${acara.id} ORDER BY urutan ASC`;
                acara.tabs = tabsRes;
            }
        } catch (e) {}
    }

    if (!acara) {
        notFound();
    }

    return (
        <div data-theme="dark" className="min-h-screen bg-[#07090f] flex flex-col font-sans selection:bg-[#E63946] selection:text-white">
            {/* 1. 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">
                    
                    <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 mb-6 animate-in fade-in slide-in-from-bottom-4 duration-700">
                        <Calendar className="w-3.5 h-3.5" />
                        Status: {acara.status}
                    </div>

                    <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">
                            {acara.nama}
                        </span>
                    </h1>

                    <p className="animate-in fade-in slide-in-from-bottom-8 duration-700 delay-200 text-white text-lg md:text-xl max-w-2xl text-center leading-relaxed font-light mb-12">
                        {acara.deskripsi ? (acara.deskripsi.substring(0, 150) + (acara.deskripsi.length > 150 ? '...' : '')) : 'Ikuti keseruan acara ini bersama Himpunan Mahasiswa Fisika FPMIPA UPI.'}
                    </p>

                    <Link
                        href="/acara"
                        className="animate-in fade-in slide-in-from-bottom-10 duration-700 delay-300 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-5 py-2.5 rounded-full backdrop-blur-md hover:bg-white/10 mt-2"
                    >
                        <ChevronLeft className="w-4 h-4" />
                        Kembali ke Daftar Acara
                    </Link>

                </div>
            </main>

            {/* 2. Interactive Tabs Section */}
            <section className="w-full pb-24">
                {acara.tabs && acara.tabs.length > 0 ? (
                    <React.Suspense fallback={<div className="container px-4 text-center py-20 text-gray-500">Memuat tab...</div>}>
                        <AcaraTabs tabs={acara.tabs} />
                    </React.Suspense>
                ) : (
                    <div className="w-full relative z-20 -mt-10 md:-mt-16 container px-4 flex flex-col items-center">
                        <div className="bg-white/5 backdrop-blur-2xl rounded-2xl w-full max-w-5xl p-8 md:p-12 border border-white/20 shadow-[0_8px_32px_0_rgba(0,0,0,0.37)] relative z-10">
                            {acara.fotoUrl && (
                                <div className="w-full mb-10 rounded-2xl overflow-hidden bg-black/40 border border-white/10 shadow-[0_8px_32px_rgba(0,0,0,0.4)]">
                                    {/* eslint-disable-next-line @next/next/no-img-element */}
                                    <img src={acara.fotoUrl} alt={acara.nama} className="w-full h-auto object-cover max-h-[600px]" />
                                </div>
                            )}
                            <div className="text-white prose prose-lg prose-invert max-w-none prose-headings:text-white prose-p:text-white prose-li:text-white prose-a:text-blue-400 hover:prose-a:text-blue-300 prose-strong:text-white">
                                <ReactMarkdown>{acara.deskripsi || ''}</ReactMarkdown>
                            </div>
                        </div>
                    </div>
                )}
            </section>
        </div>
    );
}
