'use client'

import { useEffect, useState } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { useTranslation } from 'react-i18next'
import Header from '@/components/Header'
import Sidebar from '@/components/Sidebar'
import Footer from '@/components/Footer'
import { FiArrowLeft } from 'react-icons/fi'
import { formatDateTime } from '@/utils/formatDate'
import NoticeDetailSkeleton from '@/app/notices/_components/NoticeDetailSkeleton'

type NoticeItem = {
    id: string
    title: string
    content: string
    url: string
    category: string
    date: string
}

export default function NoticeDetailPage() {
    const { t } = useTranslation()
    const params = useParams<{ id: string }>()
    const router = useRouter()

    const [sidebarOpen, setSidebarOpen] = useState(false)
    const [notice, setNotice] = useState<NoticeItem | null>(null)
    const [loading, setLoading] = useState(true)
    const [error, setError] = useState<string | null>(null)

    useEffect(() => {
        let cancelled = false
        const fetchOne = async () => {
            if (!params?.id) return
            try {
                setLoading(true)
                setError(null)
                const res = await fetch('/api/notices')
                const data = await res.json().catch(() => null)
                if (!cancelled && data?.ok && Array.isArray(data.notices)) {
                    const found = data.notices.find((n: any) => String(n.id) === String(params.id))
                    if (found) {
                        setNotice({
                            id: String(found.id),
                            title: String(found.title ?? ''),
                            content: String(found.content ?? ''),
                            url: String(found.url ?? '#'),
                            category: String(found.category ?? 'general'),
                            date: String(found.date ?? ''),
                        })
                    } else {
                        setError(t('notices.detail.notFound'))
                    }
                } else if (!cancelled) {
                    setError(t('notices.detail.failed'))
                }
            } catch (e) {
                console.error('Failed to fetch single notice:', e)
                if (!cancelled) {
                    setError(t('notices.detail.failed'))
                }
            } finally {
                if (!cancelled) setLoading(false)
            }
        }

        fetchOne()
        return () => {
            cancelled = true
        }
    }, [params?.id, t])

    return (
        <div className="min-h-screen min-w-[375px] bg-white dark:bg-[#0c0d0e] text-[#17191c] dark:text-gray-50 flex overflow-x-auto transition-colors">
            <Sidebar mode="drawer" isOpen={sidebarOpen} onClose={() => setSidebarOpen(false)} />

            <div className="flex-1 min-h-screen w-full max-w-full overflow-x-hidden">
                <Header onMenuClick={() => setSidebarOpen(!sidebarOpen)} />

                <main className="pt-[65px] pb-8 bg-[#f5f6fa] dark:bg-[#050608]">
                    {loading ? (
                        <NoticeDetailSkeleton />
                    ) : error ? (
                        <section className="relative z-10 mx-auto px-6 my-20 max-w-4xl">
                            <div className="h-full flex flex-col items-center justify-center text-center gap-2 min-h-[400px]">
                                <p className="text-sm text-[#9ca3af] dark:text-gray-400">{error}</p>
                                <button
                                    type="button"
                                    onClick={() => router.push('/notices')}
                                    className="mt-1 inline-flex items-center gap-1.5 px-3.5 h-9 rounded-lg border border-[#d5d7dc] dark:border-gray-700 text-xs font-medium text-gray-900 dark:text-white bg-white dark:bg-[#0c0d0e] hover:bg-[rgba(145,150,161,0.1)] active:bg-[rgba(23,25,28,0.3)] transition-colors"
                                >
                                    <FiArrowLeft className="w-3.5 h-3.5" />
                                    <span>{t('notices.detail.backButton')}</span>
                                </button>
                            </div>
                        </section>
                    ) : !notice ? (
                        <section className="relative z-10 mx-auto px-6 my-20 max-w-4xl">
                            <div className="h-full flex items-center justify-center text-sm text-[#9ca3af] dark:text-gray-500 min-h-[400px]">
                                {t('notices.detail.empty')}
                            </div>
                        </section>
                    ) : (
                        <section className="relative z-10 mx-auto px-6 my-20 max-w-4xl">
                            {/* Back button and metadata */}
                            <div className="relative mb-8 flex flex-wrap items-center gap-4">
                                <button
                                    type="button"
                                    onClick={() => router.push('/notices')}
                                    className="inline-flex items-center gap-2 rounded-full bg-white/80 dark:bg-[#0c0d0e]/80 border border-white/70 dark:border-gray-700/70 px-5 py-2 text-sm font-semibold text-[#2563eb] dark:text-[#3b82f6] shadow-inner shadow-white/40 dark:shadow-black/40 backdrop-blur hover:-translate-y-0.5 hover:shadow-lg transition-all cursor-pointer"
                                >
                                    <FiArrowLeft className="w-4 h-4" />
                                    <span>{t('notices.detail.back')}</span>
                                </button>
                                <div className="flex flex-wrap items-center gap-3 text-sm">
                                    <span
                                        className={`inline-flex items-center gap-1 rounded-full px-3 py-1 font-semibold tracking-wide uppercase select-none ${(notice.category || 'general').toLowerCase() === 'system'
                                            ? 'bg-yellow-50 dark:bg-yellow-900/30 text-yellow-700 dark:text-yellow-400 ring-1 ring-yellow-200 dark:ring-yellow-800'
                                            : (notice.category || 'general').toLowerCase() === 'event'
                                                ? 'bg-green-50 dark:bg-green-900/30 text-green-700 dark:text-green-400 ring-1 ring-green-200 dark:ring-green-800'
                                                : 'bg-blue-50 dark:bg-blue-900/30 !text-blue-700 dark:!text-blue-400 ring-1 ring-blue-200 dark:ring-blue-800'
                                            }`}
                                    >
                                        {(notice.category || 'general').toLowerCase() === 'system'
                                            ? t('notices.category.system')
                                            : (notice.category || 'general').toLowerCase() === 'event'
                                                ? t('notices.category.event')
                                                : t('notices.category.general')}
                                    </span>
                                    <span className="text-gray-500 dark:text-gray-400">·</span>
                                    <span className="text-gray-600 dark:text-gray-300 font-semibold">
                                        {(() => {
                                            try {
                                                const date = new Date(notice.date)
                                                if (isNaN(date.getTime())) return notice.date
                                                const year = date.getFullYear()
                                                const month = String(date.getMonth() + 1).padStart(2, '0')
                                                const day = String(date.getDate()).padStart(2, '0')
                                                return `${year}-${month}-${day}`
                                            } catch {
                                                return notice.date
                                            }
                                        })()}
                                    </span>
                                    <span className="text-gray-400 dark:text-gray-500">#{notice.id}</span>
                                </div>
                            </div>

                            {/* Article card */}
                            <article className="relative overflow-hidden rounded-[32px] border border-white/70 dark:border-gray-700/70 bg-white/90 dark:bg-[#0c0d0e]/90 backdrop-blur-2xl shadow-[0_30px_80px_rgba(15,23,42,0.18)] dark:shadow-[0_30px_80px_rgba(0,0,0,0.3)] p-8 min-h-[498px]">
                                {/* Gradient background */}
                                <div className="absolute inset-0 bg-gradient-to-br from-blue-500/5 via-transparent to-violet-500/10 opacity-60 dark:opacity-40 pointer-events-none" />

                                <div className="relative space-y-6">
                                    {/* Title section */}
                                    <div className="space-y-2">
                                        <p className="text-sm uppercase tracking-[0.3em] text-gray-400 dark:text-gray-500">
                                            {t('notices.detail.announcement')}
                                        </p>
                                        <h1 className="text-3xl md:text-4xl font-black leading-tight text-slate-900 dark:text-gray-50">
                                            {notice.title}
                                        </h1>
                                    </div>

                                    {/* Content section */}
                                    <div className="relative mt-3 pt-3 border-t border-white/60 dark:border-gray-700/60">
                                        <div
                                            className="prose prose-neutral max-w-none announcement-content text-base leading-relaxed text-slate-700 dark:text-gray-300 whitespace-pre-line"
                                            dangerouslySetInnerHTML={{ __html: notice.content.replace(/\n/g, '<br>') }}
                                        />
                                    </div>
                                </div>
                            </article>
                        </section>
                    )}
                </main>

                <Footer />
            </div>
        </div>
    )
}
