import React, { useState } from 'react';
import { Head, Link } from '@inertiajs/react';
import PortalLayout from '@/layouts/portal-layout';
import {
    Calendar,
    ChevronLeft,
    User,
    ArrowRight,
    Share2,
    Check,
    Clock,
} from 'lucide-react';
import '../../../css/alumni-home.css';
import { toast } from 'sonner';

interface NewsItem {
    id: number;
    title: string;
    slug: string;
    excerpt?: string;
    content?: string;
    thumbnail?: string;
    published_at: string;
    category?: {
        id: number;
        name: string;
        slug: string;
    };
    author?: {
        name: string;
    };
}

interface DetailProps {
    news: NewsItem;
    relatedNews: NewsItem[];
}

export default function NewsDetail({ news, relatedNews }: DetailProps) {
    const [copied, setCopied] = useState(false);

    const formatDate = (dateString?: string) => {
        if (!dateString) return '-';
        try {
            return new Date(dateString).toLocaleDateString('id-ID', {
                day: 'numeric',
                month: 'long',
                year: 'numeric',
            });
        } catch {
            return dateString;
        }
    };

    const handleCopyLink = () => {
        if (typeof window !== 'undefined' && navigator.clipboard) {
            navigator.clipboard
                .writeText(window.location.href)
                .then(() => {
                    setCopied(true);
                    setTimeout(() => setCopied(false), 2500);
                })
                .catch(() => {
                    toast.error(
                        'Tautan gagal disalin. Salin alamat dari bilah browser.',
                    );
                });
        }
    };

    // Estimasi waktu baca (rata-rata 200 kata per menit)
    const wordCount = (news.content || '')
        .trim()
        .split(/\s+/)
        .filter(Boolean).length;
    const readingTime = Math.max(1, Math.ceil(wordCount / 200));

    return (
        <PortalLayout>
            <Head
                title={`${news.title} - Fakultas Teknik Universitas Majalengka`}
            >
                <meta name="description" content={news.excerpt || news.title} />
            </Head>

            <div className="alumni-home min-h-screen bg-[#FAFAF8] pb-24">
                {/* Breadcrumb / Top Bar with staggered entrance */}
                <nav
                    aria-label="Navigasi Halaman"
                    className="stagger-1 sticky top-18 z-30 border-b border-[#E7E3DF] bg-white"
                >
                    <div className="alumni-shell flex items-center justify-between gap-4 py-3">
                        <Link
                            href="/berita"
                            className="inline-flex items-center gap-2 text-xs font-semibold text-[#5F5F64] transition-colors hover:text-[#7A1F2A] focus-visible:outline-2 focus-visible:outline-[#7A1F2A]"
                        >
                            <ChevronLeft className="h-4 w-4 text-[#7A1F2A]" />
                            <span>Kembali ke Berita & Media</span>
                        </Link>

                        <button
                            type="button"
                            onClick={handleCopyLink}
                            className="inline-flex items-center gap-1.5 rounded-md border border-[#E7E3DF] px-2.5 py-1 text-xs font-medium text-[#5F5F64] transition-all duration-200 hover:bg-[#FAF9F7] hover:text-[#17171A] active:scale-95"
                            title="Salin tautan artikel ini"
                        >
                            {copied ? (
                                <>
                                    <Check className="h-3.5 w-3.5 text-[#2F7D4A]" />
                                    <span className="font-semibold text-[#2F7D4A]">
                                        Tautan Disalin
                                    </span>
                                </>
                            ) : (
                                <>
                                    <Share2 className="h-3.5 w-3.5 text-[#87878D]" />
                                    <span>Bagikan</span>
                                </>
                            )}
                        </button>
                    </div>
                </nav>

                {/* Article Header & Main Container with staggered appearance */}
                <main className="alumni-shell pt-8 sm:pt-12">
                    <article className="mx-auto max-w-190">
                        {/* Eyebrow & Category */}
                        <div className="stagger-2 mb-4 flex flex-wrap items-center gap-2.5">
                            <span className="inline-block rounded-md border border-[#F0D5D8] bg-[#F8EEEF] px-2.5 py-1 text-[11px] font-semibold tracking-wide text-[#7A1F2A]">
                                {news.category?.name || 'Kabar Fakultas'}
                            </span>
                            <span className="flex items-center gap-1 text-xs text-[#87878D]">
                                <Clock className="h-3.5 w-3.5" />
                                {readingTime} menit baca
                            </span>
                        </div>

                        {/* Title - Source Serif 4 Display */}
                        <h1 className="stagger-3 alumni-display text-2xl leading-[1.18] font-bold tracking-tight text-[#17171A] sm:text-3xl lg:text-[40px]">
                            {news.title}
                        </h1>

                        {/* Meta: Author, Date */}
                        <div className="stagger-4 mt-5 flex flex-wrap items-center gap-4 border-b border-[#E7E3DF] pb-6 text-xs text-[#5F5F64]">
                            <div className="flex items-center gap-1.5">
                                <User className="h-3.5 w-3.5 text-[#87630E]" />
                                <span>
                                    {news.author?.name ||
                                        'Humas Fakultas Teknik UNMA'}
                                </span>
                            </div>
                            <span className="text-[#D7D1CC]">•</span>
                            <div className="flex items-center gap-1.5">
                                <Calendar className="h-3.5 w-3.5 text-[#87878D]" />
                                <time dateTime={news.published_at}>
                                    {formatDate(news.published_at)}
                                </time>
                            </div>
                        </div>

                        {/* Hero Image with subtle hover zoom */}
                        {news.thumbnail && (
                            <figure className="stagger-5 group my-8">
                                <div className="aspect-16/10 w-full overflow-hidden rounded-xl border border-[#E7E3DF] bg-[#FAF9F7] shadow-xs sm:aspect-video">
                                    <img
                                        src={news.thumbnail}
                                        alt={news.title}
                                        className="hover-zoom-img h-full w-full object-cover"
                                    />
                                </div>
                                <figcaption className="mt-2.5 text-center text-[11px] text-[#87878D] italic">
                                    Dokumentasi resmi: {news.title}
                                </figcaption>
                            </figure>
                        )}

                        {/* Excerpt Lead */}
                        {news.excerpt && (
                            <div className="stagger-5 mb-6 rounded-lg border-l-3 border-[#7A1F2A] bg-[#F7F6F3] p-4 text-sm leading-relaxed font-medium text-[#17171A] italic sm:text-base">
                                {news.excerpt}
                            </div>
                        )}

                        {/* Article Body */}
                        <div className="stagger-6 article-content space-y-5 text-base leading-[1.78] text-[#17171A]">
                            {news.content
                                ?.split('\n\n')
                                .map((paragraph, idx) => {
                                    const cleanPara = paragraph.trim();
                                    if (!cleanPara) return null;
                                    return (
                                        <p
                                            key={idx}
                                            className="text-[15px] leading-relaxed text-[#2C2C30] sm:text-base"
                                        >
                                            {cleanPara}
                                        </p>
                                    );
                                })}
                        </div>

                        {/* Bottom Actions & Share */}
                        <div className="mt-12 flex flex-wrap items-center justify-between gap-4 border-t border-[#E7E3DF] pt-6">
                            <div className="text-xs text-[#5F5F64]">
                                Diterbitkan oleh{' '}
                                <strong className="text-[#17171A]">
                                    Fakultas Teknik Universitas Majalengka
                                </strong>
                            </div>
                            <button
                                type="button"
                                onClick={handleCopyLink}
                                className="inline-flex items-center gap-2 rounded-lg border border-[#D7D1CC] px-3 py-1.5 text-xs font-semibold text-[#17171A] transition-all duration-200 hover:border-[#7A1F2A] hover:bg-white active:scale-95"
                            >
                                <Share2 className="h-3.5 w-3.5 text-[#7A1F2A]" />
                                <span>
                                    {copied
                                        ? 'Tautan Berhasil Disalin'
                                        : 'Bagikan Berita'}
                                </span>
                            </button>
                        </div>
                    </article>

                    {/* Related News Section with hover lift */}
                    {relatedNews.length > 0 && (
                        <section
                            aria-labelledby="related-news-heading"
                            className="mx-auto mt-16 max-w-250 border-t border-[#E7E3DF] pt-10"
                        >
                            <div className="mb-6 flex items-center justify-between">
                                <div>
                                    <p className="text-[11px] font-semibold tracking-wider text-[#87630E] uppercase">
                                        REKOMENDASI ARTIKEL
                                    </p>
                                    <h2
                                        id="related-news-heading"
                                        className="alumni-display text-xl font-bold text-[#17171A] sm:text-2xl"
                                    >
                                        Kabar Fakultas Terkait Lainnya
                                    </h2>
                                </div>
                                <Link
                                    href="/berita"
                                    className="inline-flex items-center gap-1.5 text-xs font-semibold text-[#7A1F2A] hover:underline"
                                >
                                    <span>Lihat Semua Berita</span>
                                    <ArrowRight className="h-3.5 w-3.5" />
                                </Link>
                            </div>

                            <div className="grid grid-cols-1 gap-6 md:grid-cols-3">
                                {relatedNews.map((item, idx) => (
                                    <article
                                        key={item.id}
                                        style={{
                                            animationDelay: `${idx * 100 + 100}ms`,
                                        }}
                                        className="stagger-1 hover-lift group flex flex-col justify-between overflow-hidden rounded-xl border border-[#E7E3DF] bg-white shadow-xs transition-all"
                                    >
                                        <div>
                                            {item.thumbnail && <div className="aspect-16/10 w-full overflow-hidden bg-[#FAF9F7]">
                                                <img
                                                    src={item.thumbnail}
                                                    alt={item.title}
                                                    className="hover-zoom-img h-full w-full object-cover"
                                                    loading="lazy"
                                                />
                                            </div>}
                                            <div className="space-y-2 p-4 sm:p-5">
                                                <div className="flex items-center justify-between text-[11px] text-[#87878D]">
                                                    <span className="rounded bg-[#F8EEEF] px-2 py-0.5 font-semibold text-[#7A1F2A]">
                                                        {item.category?.name ||
                                                            'Berita'}
                                                    </span>
                                                    <span>
                                                        {formatDate(
                                                            item.published_at,
                                                        )}
                                                    </span>
                                                </div>
                                                <h3 className="line-clamp-2 text-sm leading-snug font-bold text-[#17171A] transition-colors group-hover:text-[#7A1F2A]">
                                                    <Link
                                                        href={`/berita/${item.slug}`}
                                                    >
                                                        {item.title}
                                                    </Link>
                                                </h3>
                                                {item.excerpt && (
                                                    <p className="line-clamp-2 text-xs leading-relaxed text-[#5F5F64]">
                                                        {item.excerpt}
                                                    </p>
                                                )}
                                            </div>
                                        </div>

                                        <div className="p-4 pt-0 sm:p-5">
                                            <Link
                                                href={`/berita/${item.slug}`}
                                                className="inline-flex items-center gap-1.5 text-xs font-semibold text-[#7A1F2A] hover:underline"
                                            >
                                                <span>Baca Artikel</span>
                                                <ArrowRight className="hover-slide-arrow h-3 w-3" />
                                            </Link>
                                        </div>
                                    </article>
                                ))}
                            </div>
                        </section>
                    )}
                </main>
            </div>
        </PortalLayout>
    );
}
