import { NewsItemTooltips } from '@/components/game/item-tooltip';
import { Head, router, usePage } from '@inertiajs/react';
import { motion } from 'framer-motion';
import { Calendar, ChevronLeft, ChevronRight } from 'lucide-react';
import { useMemo, useState } from 'react';
import { getCategoryBadge } from '../components/category-badge';
import { Footer } from '../components/footer-section';
import { NavigationBar } from '../components/navigation-bar';
import { NewsBackground } from '../components/news-background';
import { Preload } from '../components/preload';
import { useForceDarkTheme } from '../components/use-force-dark-theme';

interface SocialMediaSettings {
    facebook: { enabled: boolean; url: string };
    discord: { enabled: boolean; url: string };
    instagram: { enabled: boolean; url: string };
    tiktok: { enabled: boolean; url: string };
    youtube: { enabled: boolean; url: string };
}

const DiscordIcon = ({ className }: { className?: string }) => (
    <svg className={className} fill="currentColor" viewBox="0 0 24 24" aria-hidden="true">
        <path d="M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189z" />
    </svg>
);

const YouTubeIcon = ({ className }: { className?: string }) => (
    <svg className={className} fill="currentColor" viewBox="0 0 24 24" aria-hidden="true">
        <path
            fillRule="evenodd"
            d="M19.812 5.418c.861.23 1.538.907 1.768 1.768C21.998 8.746 22 12 22 12s0 3.255-.418 4.814a2.504 2.504 0 0 1-1.768 1.768c-1.56.419-7.814.419-7.814.419s-6.255 0-7.814-.419a2.505 2.505 0 0 1-1.768-1.768C2 15.255 2 12 2 12s0-3.255.417-4.814a2.507 2.507 0 0 1 1.768-1.768C5.744 5 11.998 5 11.998 5s6.255 0 7.814.418ZM15.194 12 10 15V9l5.194 3Z"
            clipRule="evenodd"
        />
    </svg>
);

const InstagramIcon = ({ className }: { className?: string }) => (
    <svg className={className} fill="currentColor" viewBox="0 0 24 24" aria-hidden="true">
        <path
            fillRule="evenodd"
            d="M12.315 2c2.43 0 2.784.013 3.808.06 1.064.049 1.791.218 2.427.465a4.902 4.902 0 011.772 1.153 4.902 4.902 0 011.153 1.772c.247.636.416 1.363.465 2.427.048 1.067.06 1.407.06 4.123v.08c0 2.643-.012 2.987-.06 4.043-.049 1.064-.218 1.791-.465 2.427a4.902 4.902 0 01-1.153 1.772 4.902 4.902 0 01-1.772 1.153c-.636.247-1.363.416-2.427.465-1.067.048-1.407.06-4.123.06h-.08c-2.643 0-2.987-.012-4.043-.06-1.064-.049-1.791-.218-2.427-.465a4.902 4.902 0 01-1.772-1.153 4.902 4.902 0 01-1.153-1.772c-.247-.636-.416-1.363-.465-2.427-.047-1.024-.06-1.379-.06-3.808v-.63c0-2.43.013-2.784.06-3.808.049-1.064.218-1.791.465-2.427a4.902 4.902 0 011.153-1.772A4.902 4.902 0 015.45 2.525c.636-.247 1.363-.416 2.427-.465C8.901 2.013 9.256 2 11.685 2h.63zm-.081 1.802h-.468c-2.456 0-2.784.011-3.807.058-.975.045-1.504.207-1.857.344-.467.182-.8.398-1.15.748-.35.35-.566.683-.748 1.15-.137.353-.3.882-.344 1.857-.047 1.023-.058 1.351-.058 3.807v.468c0 2.456.011 2.784.058 3.807.045.975.207 1.504.344 1.857.182.466.399.8.748 1.15.35.35.683.566 1.15.748.353.137.882.3 1.857.344 1.054.048 1.37.058 4.041.058h.08c2.597 0 2.917-.01 3.96-.058.976-.045 1.505-.207 1.858-.344.466-.182.8-.398 1.15-.748.35-.35.566-.683.748-1.15.137-.353.3-.882.344-1.857.048-1.055.058-1.37.058-4.041v-.08c0-2.597-.01-2.917-.058-3.96-.045-.976-.207-1.505-.344-1.858a3.097 3.097 0 00-.748-1.15 3.098 3.098 0 00-1.15-.748c-.353-.137-.882-.3-1.857-.344-1.023-.047-1.351-.058-3.807-.058zM12 6.865a5.135 5.135 0 110 10.27 5.135 5.135 0 010-10.27zm0 1.802a3.333 3.333 0 100 6.666 3.333 3.333 0 000-6.666zm5.338-3.205a1.2 1.2 0 110 2.4 1.2 1.2 0 010-2.4z"
            clipRule="evenodd"
        />
    </svg>
);

const TikTokIcon = ({ className }: { className?: string }) => (
    <svg className={className} fill="currentColor" viewBox="0 0 24 24" aria-hidden="true">
        <path d="M12.525.02c1.31-.02 2.61-.01 3.91-.02.08 1.53.63 3.09 1.75 4.17 1.12 1.11 2.7 1.62 4.24 1.79v4.03c-1.44-.05-2.89-.35-4.2-.97-.57-.26-1.1-.59-1.62-.93-.01 2.92.01 5.84-.02 8.75-.08 1.4-.54 2.79-1.35 3.94-1.31 1.92-3.58 3.17-5.91 3.21-1.43.08-2.86-.31-4.08-1.03-2.02-1.19-3.44-3.37-3.65-5.71-.02-.5-.03-1-.01-1.49.18-1.9 1.12-3.72 2.58-4.96 1.66-1.44 3.98-2.13 6.15-1.72.02 1.48-.04 2.96-.04 4.44-.99-.32-2.15-.23-3.02.37-.63.41-1.11 1.04-1.36 1.75-.21.51-.15 1.07-.14 1.61.24 1.64 1.82 3.02 3.5 2.87 1.12-.01 2.19-.66 2.77-1.61.19-.33.4-.67.41-1.06.1-1.79.06-3.57.07-5.36.01-4.03-.01-8.05.02-12.07z" />
    </svg>
);

const FacebookIcon = ({ className }: { className?: string }) => (
    <svg className={className} fill="currentColor" viewBox="0 0 24 24" aria-hidden="true">
        <path
            fillRule="evenodd"
            d="M22 12c0-5.523-4.477-10-10-10S2 6.477 2 12c0 4.991 3.657 9.128 8.438 9.878v-6.987h-2.54V12h2.54V9.797c0-2.506 1.492-3.89 3.777-3.89 1.094 0 2.238.195 2.238.195v2.46h-1.26c-1.243 0-1.63.771-1.63 1.562V12h2.773l-.443 2.89h-2.33v6.988C18.343 21.128 22 16.991 22 12z"
            clipRule="evenodd"
        />
    </svg>
);

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 NewsListItem {
    id: number;
    slug: string;
    title: string;
    category: 'patch' | 'download' | 'guide' | 'promo' | 'event';
    image: string | null;
    created_at: string;
}

interface ServerInfo {
    appName: string;
    newsBackgroundUrl?: string | null;
    newsSmokeEnabled: boolean;
    newsSparksEnabled: boolean;
}

interface Props {
    news: News;
    allNews: NewsListItem[];
    appName: string;
    serverInfo: ServerInfo;
}

export default function NewsShow({ news, allNews, appName, serverInfo }: Props) {
    const { appLogoUrl, appFont } = usePage().props as { appLogoUrl?: string | null; appFont?: string };
    const [currentPage, setCurrentPage] = useState(1);
    const perPage = 10;
    const totalPages = Math.ceil(allNews.length / perPage);
    const visibleNews = allNews.slice((currentPage - 1) * perPage, currentPage * perPage);

    useForceDarkTheme();

    const { socialMedia } = usePage().props as { socialMedia?: SocialMediaSettings };

    const _enabledSocials = useMemo(() => {
        const result = [];
        if (socialMedia?.discord?.enabled && socialMedia.discord.url) {
            result.push({ key: 'discord', url: socialMedia.discord.url, Icon: DiscordIcon, label: 'Discord' });
        }
        if (socialMedia?.youtube?.enabled && socialMedia.youtube.url) {
            result.push({ key: 'youtube', url: socialMedia.youtube.url, Icon: YouTubeIcon, label: 'YouTube' });
        }
        if (socialMedia?.instagram?.enabled && socialMedia.instagram.url) {
            result.push({ key: 'instagram', url: socialMedia.instagram.url, Icon: InstagramIcon, label: 'Instagram' });
        }
        if (socialMedia?.tiktok?.enabled && socialMedia.tiktok.url) {
            result.push({ key: 'tiktok', url: socialMedia.tiktok.url, Icon: TikTokIcon, label: 'TikTok' });
        }
        if (socialMedia?.facebook?.enabled && socialMedia.facebook.url) {
            result.push({ key: 'facebook', url: socialMedia.facebook.url, Icon: FacebookIcon, label: 'Facebook' });
        }
        return result;
    }, [socialMedia]);

    const handleNewsClick = async (newsItem: NewsListItem) => {
        if (newsItem.slug === news.slug) return;

        router.visit(`/news/${newsItem.slug}`, {
            preserveScroll: false,
            preserveState: false,
        });
    };

    const formatDate = (dateString: string) => {
        return new Date(dateString).toLocaleDateString('en-US', {
            day: 'numeric',
            month: 'short',
            year: 'numeric',
        });
    };

    const stripFirstHeading = (html: string) => {
        return html.replace(/<h[1-6][^>]*>.*?<\/h[1-6]>/i, '').trim();
    };

    return (
        <>
            <NewsItemTooltips />
            <Head title={news.title} />
            <Preload logoUrl={appLogoUrl} appName={appName} />

            <div className="flex min-h-screen flex-col" style={{ background: '#070012' }}>
                <NavigationBar appName={appName} appLogoUrl={appLogoUrl} appFont={appFont} heroUseLogo={undefined} />

                <main className="content-wrap relative flex-1">
                    <NewsBackground newsBackgroundUrl={serverInfo.newsBackgroundUrl}>
                        <div className="relative z-10 container mx-auto max-w-7xl px-4 py-12">
                            {/* Split Layout: Sidebar + Content */}
                            <div className="grid grid-cols-1 gap-6 lg:grid-cols-12">
                                {/* Sidebar - Left */}
                                <div className="lg:col-span-4">
                                    <div
                                        className="sticky top-24 rounded-xl border p-4"
                                        style={{
                                            background: 'rgba(7,0,18,0.9)',
                                            borderColor: 'rgba(168,85,247,0.24)',
                                        }}
                                    >
                                        <div
                                            className="mb-4 text-xs font-semibold tracking-wider uppercase"
                                            style={{ color: '#d8b4fe', fontFamily: 'Rajdhani, sans-serif' }}
                                        >
                                            All News
                                        </div>

                                        <div className="space-y-2">
                                            {visibleNews.map((item) => (
                                                <button
                                                    key={item.id}
                                                    onClick={() => handleNewsClick(item)}
                                                    className={`group w-full rounded-lg border p-3 text-left transition-all duration-200 ${
                                                        news.slug === item.slug
                                                            ? 'border-[#d8b4fe] bg-[rgba(168,85,247,0.18)]'
                                                            : 'border-transparent bg-[rgba(168,85,247,0.08)] hover:border-[rgba(168,85,247,0.32)] hover:bg-[rgba(168,85,247,0.12)]'
                                                    }`}
                                                >
                                                    <div className="flex items-start gap-3">
                                                        <div className="flex flex-shrink-0 items-center gap-1 pt-0.5">
                                                            {getCategoryBadge(item.category)}
                                                            {allNews[0]?.id === item.id && (
                                                                <span
                                                                    className="inline-flex items-center rounded-full bg-fuchsia-600/90 px-1.5 py-0.5 text-[10px] font-bold tracking-wider text-white uppercase shadow-[0_0_6px_rgba(217,70,239,0.5)]"
                                                                    style={{ fontFamily: 'Rajdhani, sans-serif' }}
                                                                >
                                                                    NEW
                                                                </span>
                                                            )}
                                                        </div>
                                                        <div className="min-w-0 flex-1">
                                                            <div
                                                                className="line-clamp-2 text-sm leading-tight font-semibold transition-colors"
                                                                style={{
                                                                    color: news.slug === item.slug ? '#f5d0fe' : '#ddd6fe',
                                                                    fontFamily: 'Rajdhani, sans-serif',
                                                                }}
                                                            >
                                                                {item.title}
                                                            </div>
                                                            <div
                                                                className="mt-1 flex items-center gap-1 text-xs"
                                                                style={{ color: '#a78bfa', fontFamily: 'Rajdhani, sans-serif' }}
                                                            >
                                                                <Calendar className="h-3 w-3" />
                                                                {formatDate(item.created_at)}
                                                            </div>
                                                        </div>
                                                    </div>
                                                </button>
                                            ))}
                                        </div>

                                        {totalPages > 1 && (
                                            <div className="mt-3 flex items-center justify-between border-t border-[rgba(168,85,247,0.18)] pt-3">
                                                <button
                                                    onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                                                    disabled={currentPage === 1}
                                                    className="flex items-center gap-1 rounded px-2 py-1 text-xs font-semibold transition-all disabled:cursor-not-allowed disabled:opacity-30"
                                                    style={{ color: '#d8b4fe', fontFamily: 'Rajdhani, sans-serif' }}
                                                >
                                                    <ChevronLeft className="h-3 w-3" />
                                                    Prev
                                                </button>
                                                <span className="text-xs" style={{ color: '#a78bfa', fontFamily: 'Rajdhani, sans-serif' }}>
                                                    {currentPage} / {totalPages}
                                                </span>
                                                <button
                                                    onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
                                                    disabled={currentPage === totalPages}
                                                    className="flex items-center gap-1 rounded px-2 py-1 text-xs font-semibold transition-all disabled:cursor-not-allowed disabled:opacity-30"
                                                    style={{ color: '#d8b4fe', fontFamily: 'Rajdhani, sans-serif' }}
                                                >
                                                    Next
                                                    <ChevronRight className="h-3 w-3" />
                                                </button>
                                            </div>
                                        )}
                                    </div>
                                </div>

                                {/* Content - Right */}
                                <div className="lg:col-span-8">
                                    <motion.article
                                        key={news.id}
                                        initial={{ opacity: 0, y: 20, scale: 0.98 }}
                                        animate={{ opacity: 1, y: 0, scale: 1 }}
                                        transition={{ duration: 0.4, ease: 'easeOut' }}
                                        className="overflow-hidden rounded-xl border bg-[rgba(7,0,18,0.9)] shadow-lg"
                                        style={{ borderColor: 'rgba(168,85,247,0.24)' }}
                                    >
                                        {/* News Image */}
                                        {news.image && (
                                            <motion.div
                                                className="w-full overflow-hidden"
                                                initial={{ opacity: 0 }}
                                                animate={{ opacity: 1 }}
                                                transition={{ duration: 0.5, delay: 0.1 }}
                                            >
                                                <div className="relative">
                                                    <motion.img
                                                        src={`/storage/${news.image}`}
                                                        alt={news.title}
                                                        className="h-auto w-full object-cover"
                                                        loading="eager"
                                                        onError={(e) => {
                                                            console.error('News image load failed:', e.currentTarget.src);
                                                            e.currentTarget.style.display = 'none';
                                                        }}
                                                        initial={{ scale: 1.05 }}
                                                        animate={{ scale: 1 }}
                                                        transition={{ duration: 0.7, ease: 'easeOut' }}
                                                    />
                                                    <div
                                                        className="absolute right-0 bottom-0 left-0 flex items-center justify-center px-5 py-4"
                                                        style={{
                                                            background:
                                                                'linear-gradient(to top, rgba(0,0,0,0.85) 0%, rgba(0,0,0,0.4) 70%, transparent 100%)',
                                                        }}
                                                    >
                                                        <div
                                                            style={{
                                                                fontFamily: 'Cinzel Decorative, serif',
                                                                fontSize: '1.6rem',
                                                                fontWeight: 700,
                                                                letterSpacing: '0.1em',
                                                            }}
                                                        >
                                                            {(() => {
                                                                const full = `Perfect World ${appName}`;
                                                                const len = full.length;
                                                                const cut1 = Math.max(1, Math.ceil(len * 0.4));
                                                                const cut2 = Math.min(len - 1, cut1 + Math.max(1, Math.ceil(len * 0.2)));
                                                                return (
                                                                    <>
                                                                        <span style={{ color: '#d8b4fe' }}>{full.slice(0, cut1)}</span>
                                                                        <span
                                                                            style={{ color: '#d946ef', textShadow: '0 0 15px rgba(217,70,239,0.8)' }}
                                                                        >
                                                                            {full.slice(cut1, cut2)}
                                                                        </span>
                                                                        <span style={{ color: '#d8b4fe' }}>{full.slice(cut2)}</span>
                                                                    </>
                                                                );
                                                            })()}
                                                        </div>
                                                    </div>
                                                </div>
                                            </motion.div>
                                        )}

                                        {/* Category & Date */}
                                        <div className="p-6 pb-4 md:p-8">
                                            <motion.div
                                                initial={{ opacity: 0 }}
                                                animate={{ opacity: 1 }}
                                                transition={{ duration: 0.3, delay: 0.2 }}
                                                className="flex flex-wrap items-center gap-3"
                                            >
                                                {getCategoryBadge(news.category)}
                                                <span
                                                    className="flex items-center gap-1 text-sm"
                                                    style={{ color: '#a78bfa', fontFamily: 'Rajdhani, sans-serif' }}
                                                >
                                                    <Calendar className="h-4 w-4" />
                                                    {new Date(news.created_at).toLocaleDateString('en-US', {
                                                        day: 'numeric',
                                                        month: 'long',
                                                        year: 'numeric',
                                                    })}
                                                </span>
                                            </motion.div>
                                        </div>

                                        {/* News Content */}
                                        <motion.div
                                            initial={{ opacity: 0, y: 20 }}
                                            animate={{ opacity: 1, y: 0 }}
                                            transition={{ duration: 0.4, delay: 0.4 }}
                                            className="p-6 pt-0 md:p-8"
                                        >
                                            <div
                                                className="prose prose-zinc dark:prose-invert prose-headings:font-bold prose-headings:tracking-tight prose-a:no-underline hover:prose-a:underline prose-img:rounded-lg prose-ul:list-disc prose-ul:pl-4 prose-ol:list-decimal prose-ol:pl-4 max-w-none [&_li]:pl-2 [&_li>p]:my-0"
                                                style={{
                                                    fontFamily: 'Rajdhani, sans-serif',
                                                    color: '#ddd6fe',
                                                }}
                                                dangerouslySetInnerHTML={{ __html: stripFirstHeading(news.content) }}
                                            />
                                        </motion.div>
                                    </motion.article>
                                </div>
                            </div>
                        </div>
                    </NewsBackground>
                </main>

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