import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'
import { supabase } from '@/lib/supabase'
import { LogoutButton } from '@/components/logout-button'
import { ArrowLeft } from 'lucide-react'
import Link from 'next/link'
import { StuntingChart } from './StuntingChart'

const START_YEAR = 2026

export default async function UserTrendStuntingPage() {
    const cookieStore = await cookies()
    const sessionCookie = cookieStore.get('user_session')
    if (!sessionCookie) redirect('/')

    const session = JSON.parse(sessionCookie.value)
    if (session.role !== 'user' && session.role !== 'admin') redirect('/dashboard')

    // Fetch all stunting data (all posyandu) for the community trend
    const { data: rawData, error } = await supabase
        .from('hasil_stunting_balita')
        .select('status_stunting, tanggal_upload, nama_posyandu')
        .not('tanggal_upload', 'is', null)
        .order('tanggal_upload', { ascending: true })

    if (error) {
        return (
            <div className="min-h-screen flex items-center justify-center text-red-500 font-semibold">
                Gagal memuat data stunting.
            </div>
        )
    }

    const currentYear = new Date().getFullYear()
    const dataYears = Array.from(
        new Set((rawData ?? []).map(d => new Date(d.tanggal_upload).getFullYear()))
    )
    const allYears = Array.from(
        new Set([
            ...Array.from({ length: Math.max(currentYear, ...dataYears) - START_YEAR + 1 }, (_, i) => START_YEAR + i),
            ...dataYears,
        ])
    ).filter(y => y >= START_YEAR).sort((a, b) => a - b)

    return (
        <div className="min-h-screen bg-white font-sans text-black flex flex-col">
            {/* Header */}
            <header className="flex justify-between items-center px-8 py-6 border-b border-gray-100">
                <div className="flex items-center gap-4">
                    <Link href="/user-dashboard" className="group flex items-center gap-2 text-sm font-bold hover:text-gray-600 transition-colors">
                        <div className="p-2 rounded-full border border-black flex items-center justify-center group-hover:bg-black group-hover:text-white transition-all">
                            <ArrowLeft className="h-5 w-5" />
                        </div>
                        <span className="hidden md:block">Kembali</span>
                    </Link>
                    <div className="h-8 w-px bg-gray-200 mx-2 hidden md:block"></div>
                    <div className="flex flex-col justify-center">
                        <h1 className="text-xl font-bold leading-none">Trend stunting Daerah</h1>
                        <p className="text-[10px] text-gray-500 tracking-widest uppercase mt-0.5">Analisis Data Semua Posyandu</p>
                    </div>
                </div>
                <LogoutButton />
            </header>

            <main className="p-8 max-w-6xl mx-auto flex-1 w-full">
                <div className="bg-white rounded-xl border border-black shadow-[8px_8px_0px_0px_rgba(0,0,0,1)] p-8">
                    <StuntingChart
                        data={rawData ?? []}
                        availableYears={allYears}
                    />
                </div>
            </main>
        </div>
    )
}
