'use client'

import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Header from '@/components/Header'
import Sidebar from '@/components/Sidebar'
import Footer from '@/components/Footer'
import { FiSearch, FiArrowUpRight, FiChevronLeft, FiChevronRight } from 'react-icons/fi'
import { formatDateTime } from '@/utils/formatDate'
import NoticesPageSkeleton from '@/app/notices/_components/NoticesPageSkeleton'

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

type CategoryType = 'all' | 'general' | 'system' | 'event'

export default function NoticesPage() {
    const { t } = useTranslation()
    const [sidebarOpen, setSidebarOpen] = useState(false)
    const [notices, setNotices] = useState<NoticeItem[]>([])
    const [loading, setLoading] = useState(true)
    const [query, setQuery] = useState('')
    const [selectedCategory, setSelectedCategory] = useState<CategoryType>('all')
    const [currentPage, setCurrentPage] = useState(1)
    const pageSize = 5

    useEffect(() => {
        let cancelled = false
        const fetchNotices = async () => {
            try {
                setLoading(true)
                const res = await fetch('/api/notices')
                const data = await res.json().catch(() => null)
                if (!cancelled && data?.ok && Array.isArray(data.notices)) {
                    setNotices(
                        data.notices.map((n: any) => ({
                            id: String(n.id),
                            title: String(n.title ?? ''),
                            content: String(n.content ?? ''),
                            url: String(n.url ?? '#'),
                            category: String(n.category ?? 'general'),
                            date: String(n.date ?? ''),
                        }))
                    )
                }
            } catch (err) {
                console.error('Failed to fetch notices for notices page:', err)
            } finally {
                if (!cancelled) setLoading(false)
            }
        }

        fetchNotices()
        return () => {
            cancelled = true
        }
    }, [])

    const filtered = notices.filter((n) => {
        // Category filter
        if (selectedCategory !== 'all' && n.category !== selectedCategory) {
            return false
        }
        // Search filter
        if (!query.trim()) return true
        const q = query.trim().toLowerCase()
        return n.title.toLowerCase().includes(q) || n.content.toLowerCase().includes(q)
    })

    // Pagination
    const totalPages = Math.ceil(filtered.length / pageSize)
    const startIndex = (currentPage - 1) * pageSize
    const endIndex = startIndex + pageSize
    const paginatedNotices = filtered.slice(startIndex, endIndex)

    // Reset to page 1 when filter changes
    useEffect(() => {
        setCurrentPage(1)
    }, [query, selectedCategory])

    const getCategoryLabel = (cat: string | CategoryType) => {
        const normalizedCat = (cat || 'general').toLowerCase()
        switch (normalizedCat) {
            case 'all':
                return t('notices.category.all')
            case 'general':
                return t('notices.category.general')
            case 'system':
                return t('notices.category.system')
            case 'event':
                return t('notices.category.event')
            default:
                return t('notices.category.general')
        }
    }

    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 ? (
                        <NoticesPageSkeleton />
                    ) : (
                        <div className="w-full h-full px-4 lg:px-6 pt-4 max-w-[960px] mx-auto space-y-6">
                            {/* Page header */}
                            <section className="space-y-2">
                                <h1 className="text-2xl lg:text-3xl font-semibold text-[#17191c] dark:text-gray-50 tracking-tight">
                                    {t('notices.title')}
                                </h1>
                                <p className="text-sm text-[#6b7280] dark:text-gray-300 leading-relaxed">
                                    {t('notices.subtitle')}
                                </p>
                            </section>

                            {/* Category tabs */}
                            <section className="relative max-w-4xl mx-auto mb-6">
                                <div className="mx-auto w-full max-w-[520px]">
                                    <div className="rounded-lg bg-gray-50 dark:bg-[#1a1b1e] p-1 border border-gray-200 dark:border-gray-700">
                                        <div className="relative h-10">
                                            {/* Sliding background indicator */}
                                            <div
                                                className="absolute top-0 h-10 rounded-md bg-gradient-to-tr from-blue-500 to-violet-600 dark:from-blue-600 dark:to-violet-700 shadow-lg shadow-blue-500/30 dark:shadow-blue-600/30 transition-transform duration-300 ease-in-out"
                                                aria-hidden="true"
                                                style={{
                                                    width: '25%',
                                                    transform: `translateX(${(['all', 'general', 'system', 'event'] as CategoryType[]).indexOf(
                                                        selectedCategory
                                                    ) * 100
                                                        }%)`,
                                                }}
                                            />
                                            {/* Tab buttons */}
                                            <div
                                                className="grid h-10 cursor-pointer"
                                                style={{ gridTemplateColumns: 'repeat(4, 1fr)' }}
                                            >
                                                {(['all', 'general', 'system', 'event'] as CategoryType[]).map((cat) => (
                                                    <button
                                                        key={cat}
                                                        type="button"
                                                        onClick={() => setSelectedCategory(cat)}
                                                        className={`relative z-10 h-10 w-full rounded-md text-sm md:text-base font-semibold transition-colors flex items-center justify-center border border-transparent ${selectedCategory === cat
                                                            ? 'text-white'
                                                            : 'text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100'
                                                            }`}
                                                    >
                                                        {getCategoryLabel(cat)}
                                                    </button>
                                                ))}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </section>

                            {/* Search */}
                            <section className="flex flex-col items-center gap-3">
                                <div className="w-full max-w-[320px]">
                                    <div className="relative flex-1 w-full h-10 border rounded-lg px-3.5 flex items-center group border-gray-300 dark:border-gray-600 bg-white dark:bg-[#050608]">
                                        <span className="pointer-events-none mr-2">
                                            <FiSearch className="w-4 h-4 text-[#757b8a] dark:text-gray-400" />
                                        </span>
                                        <input
                                            type="text"
                                            autoComplete="off"
                                            placeholder={t('notices.search.placeholder')}
                                            value={query}
                                            onChange={(e) => setQuery(e.target.value)}
                                            className="flex-1 h-full pr-3.5 border-0 outline-none bg-transparent text-sm text-[#111827] dark:text-gray-50 disabled:text-gray-400 dark:disabled:text-gray-500"
                                        />
                                    </div>
                                </div>
                            </section>

                            {/* Notice list */}
                            <section className="relative max-w-4xl mx-auto space-y-10 min-h-[484px]">
                                {filtered.length === 0 ? (
                                    <div className="px-5 py-10 text-center text-sm text-[#9ca3af] dark:text-gray-500 h-full">
                                        {t('notices.empty')}
                                    </div>
                                ) : (
                                    paginatedNotices.map((notice, index) => {
                                        const category = (notice.category || 'general').toLowerCase()
                                        const isSystem = category === 'system'
                                        const isEvent = category === 'event'

                                        return (
                                            <a
                                                key={notice.id}
                                                href={`/notices/${notice.id}`}
                                                className="block group"
                                                aria-label={notice.title}
                                            >
                                                <article className="relative overflow-hidden rounded-2xl border border-white/60 dark:border-gray-700/60 bg-white/85 dark:bg-[#0c0d0e]/85 backdrop-blur-xl shadow-[0_20px_55px_rgba(15,23,42,0.12)] dark:shadow-[0_20px_55px_rgba(0,0,0,0.3)] transition-all duration-500 group-hover:-translate-y-2 group-hover:shadow-[0_30px_70px_rgba(79,70,229,0.18)] dark:group-hover:shadow-[0_30px_70px_rgba(79,70,229,0.25)]">
                                                    {/* Gradient background on hover */}
                                                    <div className="absolute inset-0 bg-gradient-to-br from-blue-500/5 via-transparent to-violet-500/10 opacity-0 group-hover:opacity-100 transition-opacity duration-500" />

                                                    <div className="relative p-7 space-y-4">
                                                        {/* Date and category */}
                                                        <div className="flex flex-wrap items-center justify-between gap-3 text-sm text-gray-500 dark:text-gray-400">
                                                            <span className="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={`inline-flex items-center gap-1 text-xs md:text-sm font-semibold tracking-wide uppercase px-3 py-1 rounded-full select-none ${isSystem
                                                                    ? 'bg-yellow-50 dark:bg-yellow-900/30 text-yellow-700 dark:text-yellow-400 ring-1 ring-yellow-200 dark:ring-yellow-800'
                                                                    : isEvent
                                                                        ? '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'
                                                                    }`}
                                                            >
                                                                {getCategoryLabel(notice.category || 'general')}
                                                            </span>
                                                        </div>

                                                        {/* Title and content */}
                                                        <div className="space-y-3">
                                                            <h2 className="text-2xl md:text-3xl font-bold leading-snug text-slate-900 dark:text-gray-50">
                                                                {notice.title}
                                                            </h2>
                                                            {notice.content && (
                                                                <p className="text-base text-gray-600 dark:text-gray-300 leading-relaxed line-clamp-3">
                                                                    {notice.content}
                                                                </p>
                                                            )}
                                                        </div>

                                                        {/* More button and ID */}
                                                        <div className="flex items-center justify-between pt-2 text-sm font-semibold text-gray-700 dark:text-gray-300">
                                                            <span className="inline-flex items-center gap-2">
                                                                {t('notices.readMore')}
                                                                <FiArrowUpRight className="h-4 w-4 transition-transform group-hover:translate-x-1 group-hover:-translate-y-1" />
                                                            </span>
                                                            <span className="text-gray-400 dark:text-gray-500 text-xs">
                                                                #{notice.id}
                                                            </span>
                                                        </div>
                                                    </div>
                                                </article>
                                            </a>
                                        )
                                    })
                                )}
                            </section>

                            {/* Pagination */}
                            {!loading && filtered.length > 0 && totalPages > 1 && (
                                <section className="flex justify-center items-center gap-2 mt-8">
                                    <button
                                        onClick={() => setCurrentPage((prev) => Math.max(1, prev - 1))}
                                        disabled={currentPage === 1}
                                        className="px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center gap-1"
                                    >
                                        <FiChevronLeft className="w-4 h-4" />
                                        <span>{t('common.previous')}</span>
                                    </button>
                                    {Array.from({ length: totalPages }, (_, i) => {
                                        const pageNum = i + 1
                                        // Show first page, last page, current page, and pages around current
                                        const showPage =
                                            pageNum === 1 ||
                                            pageNum === totalPages ||
                                            (pageNum >= currentPage - 1 && pageNum <= currentPage + 1)
                                        if (!showPage) {
                                            // Show ellipsis
                                            if (pageNum === currentPage - 2 || pageNum === currentPage + 2) {
                                                return (
                                                    <span key={pageNum} className="px-2 text-gray-400 dark:text-gray-500">
                                                        ...
                                                    </span>
                                                )
                                            }
                                            return null
                                        }
                                        return (
                                            <button
                                                key={pageNum}
                                                onClick={() => setCurrentPage(pageNum)}
                                                className={`px-3 py-2 text-sm border rounded-lg transition-colors ${currentPage === pageNum
                                                    ? 'bg-[#2563eb] dark:bg-[#3b82f6] text-white border-[#2563eb] dark:border-[#3b82f6]'
                                                    : 'border-gray-300 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-800'
                                                    }`}
                                            >
                                                {pageNum}
                                            </button>
                                        )
                                    })}
                                    <button
                                        onClick={() => setCurrentPage((prev) => Math.min(totalPages, prev + 1))}
                                        disabled={currentPage === totalPages}
                                        className="px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center gap-1"
                                    >
                                        <span>{t('common.next')}</span>
                                        <FiChevronRight className="w-4 h-4" />
                                    </button>
                                </section>
                            )}
                        </div>
                    )}
                </main>

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



