import { Button } from '@/components/ui/button';
import { Head, router, usePage } from '@inertiajs/react';
import { useEffect, useState } from 'react';
import { route } from '@/lib/route-helper';
import { motion } from 'framer-motion';
import { Bookmark, Calendar, ChevronLeft, ChevronRight, Tag } from 'lucide-react';
import { Footer } from '../components/footer-section';
import { NavigationBar } from '../components/navigation-bar';
import { NewsBackground } from '../components/news-background';
import { Preload } from '../components/preload';

import { cn } from '@/lib/utils';
import { getCategoryBadge } from '../components/category-badge';
import { formatDate, truncateContent } from '../components/date-utils';
import { HeroSection } from '../components/hero-section';
import { useForceDarkTheme } from '../components/use-force-dark-theme';

interface News {
    id: number;
    title: string;
    slug: string;
    category: 'patch' | 'download' | 'guide' | 'promo' | 'event';
    image: string | null;
    content: string;
    is_active: boolean;
    created_at: string;
    updated_at: string;
}

interface ServerInfo {
    appName: string;
    heroBackgroundUrl?: string | null;
    heroBackgroundWebP?: string | null;
    newsBackgroundUrl?: string | null;
    heroHeight?: number;
    smokeEnabled: boolean;
    newsSmokeEnabled: boolean;
    newsSparksEnabled: boolean;
    appNameColor?: string;
    serverStartTime?: string | null;
    heroUseLogo?: boolean;
    heroLogoUrl?: string | null;
    heroLogoSize?: number;
}

interface DownloadItem {
    id: number;
    name: string;
    description: string;
    size: string;
    url: string;
    icon_name: string;
    mirror_url?: string;
    mirror_icon?: string;
    sort_order: number;
    is_active: boolean;
}

interface Props {
    news: News[];
    appName: string;
    serverInfo: ServerInfo;
    downloadItems?: DownloadItem[];
}

export default function NewsIndex({ news, appName, serverInfo, downloadItems: _downloadItems = [] }: Props) {
    const { appLogoUrl, appFont } = usePage().props as { appLogoUrl?: string | null; appFont?: string };
    // Force dark theme
    useForceDarkTheme();

    const [selectedCategory, setSelectedCategory] = useState<string>('all');
    const [currentPage, setCurrentPage] = useState<number>(1);
    const [navigatingSlug, setNavigatingSlug] = useState<string | null>(null);
    const itemsPerPage = 9;

    const filteredNews = selectedCategory === 'all' ? news : news.filter((item) => item.category === selectedCategory);

    const paginatedNews = filteredNews.slice((currentPage - 1) * itemsPerPage, currentPage * itemsPerPage);
    const totalPages = Math.ceil(filteredNews.length / itemsPerPage);

    useEffect(() => {
        setCurrentPage(1);
    }, [selectedCategory]);

    const containerVariants = {
        hidden: { opacity: 0 },
        visible: {
            opacity: 1,
            transition: {
                staggerChildren: 0.08,
                delayChildren: 0.1,
            },
        },
    };

    const itemVariants = {
        hidden: { opacity: 0, y: 30, scale: 0.97 },
        visible: { opacity: 1, y: 0, scale: 1, transition: { duration: 0.45, ease: 'easeOut' as const } },
    };

    const handleCardClick = (e: React.MouseEvent, newsSlug: string) => {
        e.preventDefault();
        setNavigatingSlug(newsSlug);
        setTimeout(() => {
            router.visit(route('news.show', { slug: newsSlug }), {
                preserveScroll: false,
                preserveState: false,
            });
        }, 400);
    };

    return (
        <>
            <Head title="News" />
            <Preload logoUrl={appLogoUrl} appName={appName} />
            <div className="flex min-h-screen flex-col" style={{ background: '#0a0705' }}>
                <NavigationBar appName={appName} appLogoUrl={appLogoUrl} appFont={appFont} heroUseLogo={serverInfo.heroUseLogo} />

                <main className="content-wrap relative flex-1">
                    {/* Hero Section */}
                    <HeroSection
                        appName={serverInfo.appName}
                        heroBackgroundUrl={serverInfo.heroBackgroundUrl}
                        heroBackgroundWebP={serverInfo.heroBackgroundWebP}
                        heroHeight={serverInfo.heroHeight}
                        smokeEnabled={serverInfo.smokeEnabled}
                        newsSparksEnabled={serverInfo.newsSparksEnabled}
                        appFont={appFont}
                        appNameColor={serverInfo.appNameColor}
                        buttonText="Download Now"
                        serverStartTime={serverInfo.serverStartTime}
                        heroUseLogo={serverInfo.heroUseLogo}
                        heroLogoUrl={serverInfo.heroLogoUrl}
                        heroLogoSize={serverInfo.heroLogoSize}
                    />

                    {/* News Section with unified background */}
                    <NewsBackground newsBackgroundUrl={serverInfo.newsBackgroundUrl}>
                        {/* News Section Header */}
                        <div id="news" className="relative z-10 mx-auto w-full max-w-7xl scroll-mt-20 py-12">
                            {/* Section Header */}
                            <div className="mb-10 px-4 text-center">
                                <div
                                    className="mb-3 text-sm tracking-[0.35em] uppercase"
                                    style={{ color: '#c0392b', fontFamily: 'Rajdhani, sans-serif' }}
                                >
                                    Latest Updates
                                </div>
                                <h2
                                    className="mb-4 text-3xl font-bold md:text-4xl"
                                    style={{
                                        color: '#f0d080',
                                        fontFamily: 'Cinzel Decorative, serif',
                                        textShadow: '0 0 30px rgba(201,168,76,.3)',
                                    }}
                                >
                                    News
                                </h2>
                                <div className="mx-auto flex max-w-xl items-center justify-center gap-3">
                                    <div className="h-px flex-1 bg-gradient-to-r from-transparent to-[#7a5c1e]" />
                                    <span className="text-sm text-[#7a5c1e]">✦</span>
                                    <div className="h-px flex-1 bg-gradient-to-l from-transparent to-[#7a5c1e]" />
                                </div>
                            </div>

                            {/* Filter */}
                            <div className="mb-8 flex flex-wrap justify-center gap-3 px-4">
                                {['all', 'patch', 'download', 'guide', 'promo', 'event'].map((category) => (
                                    <button
                                        key={category}
                                        onClick={() => setSelectedCategory(category)}
                                        className="group relative transition-transform duration-200 hover:scale-105 active:scale-95"
                                        style={{ width: '110px' }}
                                    >
                                        <img
                                            src={selectedCategory === category ? '/img/button/btn_tab.webp' : '/img/button/btn-tab2.webp'}
                                            alt={category}
                                            className="h-auto w-full"
                                            draggable={false}
                                        />
                                        <span
                                            className={cn(
                                                'absolute inset-0 flex items-center justify-center pt-3 text-xs font-semibold tracking-wide uppercase',
                                                selectedCategory === category
                                                    ? 'text-zinc-900 drop-shadow-[0_1px_1px_rgba(255,255,255,0.3)]'
                                                    : 'text-zinc-300 drop-shadow-[0_1px_2px_rgba(0,0,0,0.5)]',
                                            )}
                                        >
                                            {category === 'all' && <Tag className="mr-1 inline-block h-2.5 w-2.5" />}
                                            {category.charAt(0).toUpperCase() + category.slice(1)}
                                        </span>
                                    </button>
                                ))}
                            </div>

                            {/* News Grid */}
                            <div className="mx-auto max-w-6xl px-4">
                                {paginatedNews.length > 0 ? (
                                    <motion.div
                                        className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3"
                                        variants={containerVariants}
                                        initial="hidden"
                                        animate="visible"
                                        key={selectedCategory + '-' + currentPage}
                                    >
                                        {paginatedNews.map((item, index) => (
                                            <motion.div
                                                key={item.id}
                                                variants={itemVariants}
                                                className="group relative flex cursor-pointer flex-col overflow-hidden rounded-xl border bg-[rgba(10,7,5,0.8)] transition-all duration-300 hover:border-[rgba(201,168,76,0.4)] hover:bg-[rgba(20,12,5,0.9)]"
                                                style={{ borderColor: 'rgba(201,168,76,0.2)' }}
                                                whileHover={{ y: -6, transition: { duration: 0.25, ease: 'easeOut' } }}
                                                animate={
                                                    navigatingSlug === item.slug
                                                        ? { opacity: 0, scale: 1.03, y: -10, transition: { duration: 0.35 } }
                                                        : { opacity: 1, scale: 1, y: 0 }
                                                }
                                                onClick={(e) => handleCardClick(e, item.slug)}
                                            >
                                                {/* Featured styling for first item */}
                                                {index === 0 && (
                                                    <div
                                                        className="absolute top-3 right-3 z-30 rounded border px-2 py-0.5 text-[10px] font-bold tracking-wider uppercase"
                                                        style={{
                                                            borderColor: '#7a5c1e',
                                                            color: '#f0d080',
                                                            background: 'rgba(201,168,76,0.15)',
                                                            fontFamily: 'Rajdhani, sans-serif',
                                                        }}
                                                    >
                                                        Featured
                                                    </div>
                                                )}

                                                {item.image ? (
                                                    <div className="relative aspect-[16/9] w-full overflow-hidden bg-zinc-100 dark:bg-zinc-800">
                                                        <motion.div
                                                            className="absolute inset-0 z-10 bg-black/20 transition-colors group-hover:bg-transparent"
                                                            style={{ background: 'linear-gradient(to bottom, transparent 50%, rgba(0,0,0,0.7))' }}
                                                        />
                                                        <motion.img
                                                            src={`/storage/${item.image}`}
                                                            alt={item.title}
                                                            className="h-full w-full object-cover transition-transform duration-500 group-hover:scale-105"
                                                            onError={(e) => {
                                                                e.currentTarget.style.display = 'none';
                                                            }}
                                                            animate={navigatingSlug === item.slug ? { scale: 1.1 } : { scale: 1 }}
                                                            transition={{ duration: 0.5 }}
                                                        />
                                                        <div className="absolute top-4 left-4 z-20">{getCategoryBadge(item.category)}</div>
                                                    </div>
                                                ) : (
                                                    <div className="absolute top-6 left-6 z-20">{getCategoryBadge(item.category)}</div>
                                                )}

                                                <div className={`flex flex-1 flex-col p-5 ${!item.image ? 'pt-16' : ''} relative z-10`}>
                                                    <div
                                                        className="mb-3 flex items-center text-xs font-medium"
                                                        style={{ color: '#7a6a54', fontFamily: 'Rajdhani, sans-serif' }}
                                                    >
                                                        <Calendar className="mr-1.5 h-3.5 w-3.5" />
                                                        {formatDate(item.created_at)}
                                                    </div>

                                                    <h3
                                                        className="mb-3 text-lg leading-tight font-bold tracking-tight transition-colors"
                                                        style={{ color: '#c8b89a', fontFamily: 'Cinzel Decorative, serif' }}
                                                    >
                                                        {item.title}
                                                    </h3>

                                                    <p
                                                        className="mb-4 flex-1 text-sm leading-relaxed"
                                                        style={{ color: '#7a6a54', fontFamily: 'Rajdhani, sans-serif' }}
                                                    >
                                                        {truncateContent(item.content)}
                                                    </p>

                                                    <div className="group/btn relative flex w-fit transition-transform duration-200 hover:scale-105 active:scale-95">
                                                        <img
                                                            src="/img/button/button_read.webp"
                                                            alt="Read full article"
                                                            className="block h-10 w-auto"
                                                            draggable={false}
                                                        />
                                                        <span className="pointer-events-none absolute top-1/2 left-1/2 z-10 -translate-x-1/2 -translate-y-[60%] text-xs font-bold tracking-wide whitespace-nowrap text-white uppercase drop-shadow-[0_1px_2px_rgba(0,0,0,0.5)]">
                                                            Read More
                                                        </span>
                                                    </div>
                                                </div>
                                            </motion.div>
                                        ))}
                                    </motion.div>
                                ) : (
                                    <div className="flex flex-col items-center justify-center py-16 text-center">
                                        <Bookmark className="mb-4 h-16 w-16" style={{ color: 'rgba(122,106,84,0.3)' }} />
                                        <h3 className="mb-2 text-xl font-semibold" style={{ color: '#c8b89a' }}>
                                            No News Available
                                        </h3>
                                        <p style={{ color: '#7a6a54' }}>There are currently no news articles to display.</p>
                                    </div>
                                )}

                                {/* Pagination Controls */}
                                {filteredNews.length > itemsPerPage && (
                                    <div className="mt-12 flex items-center justify-center gap-4">
                                        <Button
                                            variant="outline"
                                            size="sm"
                                            onClick={() => setCurrentPage((prev) => Math.max(1, prev - 1))}
                                            disabled={currentPage <= 1}
                                            className="rounded-full border-[rgba(201,168,76,0.3)] text-[#c9a84c] hover:bg-[rgba(201,168,76,0.1)]"
                                        >
                                            <ChevronLeft className="mr-1 h-4 w-4" />
                                            Previous
                                        </Button>

                                        <div className="flex items-center gap-2">
                                            {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                                                let pageNum;
                                                if (totalPages <= 5) {
                                                    pageNum = i + 1;
                                                } else if (currentPage <= 3) {
                                                    pageNum = i + 1;
                                                } else if (currentPage >= totalPages - 2) {
                                                    pageNum = totalPages - 4 + i;
                                                } else {
                                                    pageNum = currentPage - 2 + i;
                                                }

                                                return (
                                                    <Button
                                                        key={pageNum}
                                                        variant={currentPage === pageNum ? 'default' : 'outline'}
                                                        size="sm"
                                                        onClick={() => setCurrentPage(pageNum)}
                                                        className="min-w-[40px] rounded-full border-[rgba(201,168,76,0.3)] text-[#c9a84c] hover:bg-[rgba(201,168,76,0.1)]"
                                                        style={
                                                            currentPage === pageNum
                                                                ? { background: 'rgba(201,168,76,0.2)', color: '#f0d080', borderColor: '#7a5c1e' }
                                                                : {}
                                                        }
                                                    >
                                                        {pageNum}
                                                    </Button>
                                                );
                                            })}
                                        </div>

                                        <Button
                                            variant="outline"
                                            size="sm"
                                            onClick={() => setCurrentPage((prev) => Math.min(totalPages, prev + 1))}
                                            disabled={currentPage >= totalPages}
                                            className="rounded-full border-[rgba(201,168,76,0.3)] text-[#c9a84c] hover:bg-[rgba(201,168,76,0.1)]"
                                        >
                                            Next
                                            <ChevronRight className="ml-1 h-4 w-4" />
                                        </Button>
                                    </div>
                                )}

                                {/* Page Info */}
                                {filteredNews.length > 0 && (
                                    <div className="mt-4 text-center text-sm" style={{ color: '#7a6a54', fontFamily: 'Rajdhani, sans-serif' }}>
                                        Showing {(currentPage - 1) * itemsPerPage + 1} - {Math.min(currentPage * itemsPerPage, filteredNews.length)}{' '}
                                        of {filteredNews.length} news items
                                    </div>
                                )}
                            </div>
                        </div>
                    </NewsBackground>

                    {/* Spacer */}
                    <div
                        className="relative z-10 w-full"
                        style={{
                            height: '60px',
                            background: 'linear-gradient(to bottom, transparent, #0a0705 70%)',
                        }}
                    />
                </main>

                <Footer appName={appName} logoUrl={appLogoUrl} />
            </div>
        </>
    );
}
