import React, { useState, useEffect, useMemo, useRef } from 'react';
import { Link } from '@inertiajs/react';
import { PublicHeader } from '@/Components/PublicHeader';
import { PublicFooter } from '@/Components/PublicFooter';
import { SEOHead } from '@/Components/SEOHead';
import { BlogCard } from '@/Components/BlogCard';
import { formatCustomDate } from '@/lib/utils';
import {
    ArrowLeft,
    Calendar,
    Clock,
    Eye,
    User,
    Share2,
    Twitter,
    Linkedin,
    Facebook,
    MessageCircle,
    Link2,
    Check,
    ListTree,
    ChevronRight,
    Sparkles,
} from 'lucide-react';

interface BlogShowProps {
    post: any;
    relatedPosts: any[];
}

interface TocItem {
    id: string;
    text: string;
    level: number;
}

export default function Show({ post, relatedPosts }: BlogShowProps) {
    const [scrollProgress, setScrollProgress] = useState(0);
    const [activeSection, setActiveSection] = useState<string>('');
    const [copied, setCopied] = useState(false);
    const contentRef = useRef<HTMLDivElement>(null);

    // Calculate reading progress bar
    useEffect(() => {
        const handleScroll = () => {
            const totalHeight = document.documentElement.scrollHeight - window.innerHeight;
            if (totalHeight > 0) {
                const currentProgress = (window.scrollY / totalHeight) * 100;
                setScrollProgress(Math.min(100, Math.max(0, currentProgress)));
            }

            // Detect active heading for TOC
            const headings = document.querySelectorAll('.article-prose h2, .article-prose h3');
            let currentActive = '';
            headings.forEach((h) => {
                const rect = h.getBoundingClientRect();
                if (rect.top <= 140) {
                    currentActive = h.id;
                }
            });
            if (currentActive) {
                setActiveSection(currentActive);
            }
        };

        window.addEventListener('scroll', handleScroll, { passive: true });
        return () => window.removeEventListener('scroll', handleScroll);
    }, []);

    // Extract Headings from Content for Table of Contents
    const tocItems = useMemo<TocItem[]>(() => {
        if (!post.content) return [];
        const parser = new DOMParser();
        const doc = parser.parseFromString(post.content, 'text/html');
        const headings = doc.querySelectorAll('h2, h3');
        const items: TocItem[] = [];

        headings.forEach((h, idx) => {
            const text = h.textContent?.trim() || '';
            if (text) {
                const id = h.id || `heading-${idx}-${text.toLowerCase().replace(/[^a-z0-9]+/g, '-').slice(0, 40)}`;
                items.push({
                    id,
                    text,
                    level: h.tagName.toLowerCase() === 'h2' ? 2 : 3,
                });
            }
        });

        return items;
    }, [post.content]);

    // Attach generated IDs to rendered DOM headings
    useEffect(() => {
        if (!contentRef.current) return;
        const headings = contentRef.current.querySelectorAll('h2, h3');
        headings.forEach((h, idx) => {
            const text = h.textContent?.trim() || '';
            if (text && !h.id) {
                h.id = `heading-${idx}-${text.toLowerCase().replace(/[^a-z0-9]+/g, '-').slice(0, 40)}`;
            }
        });
    }, [post.content]);

    // Calculated Reading Time
    const calculatedReadingTime = useMemo(() => {
        if (post.reading_time) return post.reading_time;
        const textOnly = post.content ? post.content.replace(/<[^>]*>/g, '') : '';
        const words = textOnly.trim().split(/\s+/).length;
        return Math.max(2, Math.ceil(words / 200));
    }, [post.content, post.reading_time]);

    const postUrl = typeof window !== 'undefined' ? window.location.href : `https://techinsoul.com/blog/${post.slug}`;
    const encodedTitle = encodeURIComponent(post.title || '');
    const encodedUrl = encodeURIComponent(postUrl);

    const handleCopyLink = () => {
        if (typeof navigator !== 'undefined' && navigator.clipboard) {
            navigator.clipboard.writeText(postUrl);
            setCopied(true);
            setTimeout(() => setCopied(false), 2500);
        }
    };

    const scrollToHeading = (id: string) => {
        const el = document.getElementById(id);
        if (el) {
            const offset = 100;
            const bodyRect = document.body.getBoundingClientRect().top;
            const elementRect = el.getBoundingClientRect().top;
            const elementPosition = elementRect - bodyRect;
            const offsetPosition = elementPosition - offset;

            window.scrollTo({
                top: offsetPosition,
                behavior: 'smooth',
            });
        }
    };

    return (
        <div className="min-h-screen bg-[#060B18] text-slate-100 flex flex-col font-sans selection:bg-[#00F2FE]/20 selection:text-[#00F2FE]">
            <SEOHead
                title={`${post.meta_title || post.title} | Tech in Soul Blog`}
                description={post.meta_description || post.excerpt}
                canonical={post.canonical_url}
            />

            {/* Top Glowing Reading Progress Bar */}
            <div
                className="fixed top-0 left-0 right-0 h-[3.5px] bg-gradient-to-r from-[#00F2FE] via-[#4FACFE] to-[#00F2FE] z-50 transition-all duration-150 shadow-sm shadow-[#00F2FE]/40"
                style={{ width: `${scrollProgress}%` }}
            />

            <PublicHeader />

            <main className="flex-grow pt-32 pb-20">
                <article className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 space-y-8">
                    <Link
                        href="/blog"
                        className="inline-flex items-center gap-2 text-xs font-semibold text-slate-400 hover:text-[#00F2FE] transition-colors"
                    >
                        <ArrowLeft className="w-4 h-4" /> Back to Articles
                    </Link>

                    {/* Article Header */}
                    <div className="space-y-4 max-w-4xl">
                        <div className="flex items-center gap-2">
                            <span className="text-xs font-bold text-[#00F2FE] uppercase tracking-widest px-3 py-1 rounded-full bg-[#00F2FE]/10 border border-[#00F2FE]/20">
                                {post.category?.name || 'ENGINEERING'}
                            </span>
                            <span className="text-xs text-slate-400 font-medium">
                                ⏱️ {calculatedReadingTime} min read
                            </span>
                        </div>

                        <h1 className="text-3xl sm:text-5xl font-extrabold text-white tracking-tight leading-tight">
                            {post.title}
                        </h1>

                        <div className="flex flex-wrap items-center gap-4 text-xs text-slate-400 pt-2 border-b border-slate-800 pb-6">
                            <span className="flex items-center gap-1.5 text-slate-300 font-semibold">
                                <User className="w-4 h-4 text-[#00F2FE]" />
                                {post.author?.name || 'Tech in Soul Editorial'}
                            </span>
                            <span>•</span>
                            <span className="flex items-center gap-1">
                                <Calendar className="w-3.5 h-3.5 text-slate-400" />
                                {post.published_at ? formatCustomDate(post.published_at) : 'Recent'}
                            </span>
                            <span>•</span>
                            <span className="flex items-center gap-1">
                                <Clock className="w-3.5 h-3.5 text-slate-400" />
                                {calculatedReadingTime} min read
                            </span>
                            <span>•</span>
                            <span className="flex items-center gap-1">
                                <Eye className="w-3.5 h-3.5 text-slate-400" />
                                {post.views || 0} Views
                            </span>
                        </div>
                    </div>

                    {/* Two-Column Grid: Left Content, Right Sticky TOC & Share */}
                    <div className="grid grid-cols-1 lg:grid-cols-12 gap-10 items-start">
                        {/* Main Article Content */}
                        <div className="lg:col-span-8 space-y-8">
                            <div className="glass-card rounded-3xl p-6 sm:p-10 lg:p-12 space-y-6 text-slate-300 leading-relaxed text-base">
                                {post.excerpt && (
                                    <p className="text-base sm:text-lg font-medium text-white italic border-l-4 border-[#00F2FE] pl-4 py-1 bg-[#00F2FE]/5 rounded-r-xl">
                                        {post.excerpt}
                                    </p>
                                )}

                                <div
                                    ref={contentRef}
                                    className="article-prose prose prose-invert max-w-none text-[#F8FAFC]"
                                    dangerouslySetInnerHTML={{ __html: post.content || '' }}
                                />
                            </div>

                            {/* Tags */}
                            {post.tags && post.tags.length > 0 && (
                                <div className="flex flex-wrap items-center gap-2 pt-2">
                                    <span className="text-xs font-bold text-slate-400">Tags:</span>
                                    {post.tags.map((tag: string, idx: number) => (
                                        <span key={idx} className="text-xs px-3 py-1 rounded-lg bg-[#0B132B] text-[#00F2FE] border border-[#00F2FE]/20 font-medium">
                                            #{tag}
                                        </span>
                                    ))}
                                </div>
                            )}

                            {/* Mobile / Inline Social Share Footer */}
                            <div className="p-6 rounded-2xl bg-[#0B132B] border border-slate-800 flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                                <div>
                                    <h4 className="text-sm font-bold text-white flex items-center gap-2">
                                        <Share2 className="w-4 h-4 text-[#00F2FE]" /> Share this article
                                    </h4>
                                    <p className="text-xs text-slate-400">Enjoyed this technical guide? Share it with fellow developers and engineering teams.</p>
                                </div>

                                <div className="flex items-center gap-2 shrink-0">
                                    <a
                                        href={`https://twitter.com/intent/tweet?text=${encodedTitle}&url=${encodedUrl}`}
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className="p-2.5 rounded-xl bg-[#060B18] text-slate-300 hover:text-[#00F2FE] hover:bg-[#1C2541] border border-slate-800 transition-all"
                                        title="Share on Twitter / X"
                                    >
                                        <Twitter className="w-4 h-4" />
                                    </a>
                                    <a
                                        href={`https://www.linkedin.com/sharing/share-offsite/?url=${encodedUrl}`}
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className="p-2.5 rounded-xl bg-[#060B18] text-slate-300 hover:text-[#00F2FE] hover:bg-[#1C2541] border border-slate-800 transition-all"
                                        title="Share on LinkedIn"
                                    >
                                        <Linkedin className="w-4 h-4" />
                                    </a>
                                    <a
                                        href={`https://www.facebook.com/sharer/sharer.php?u=${encodedUrl}`}
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className="p-2.5 rounded-xl bg-[#060B18] text-slate-300 hover:text-[#00F2FE] hover:bg-[#1C2541] border border-slate-800 transition-all"
                                        title="Share on Facebook"
                                    >
                                        <Facebook className="w-4 h-4" />
                                    </a>
                                    <a
                                        href={`https://api.whatsapp.com/send?text=${encodedTitle}%20${encodedUrl}`}
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className="p-2.5 rounded-xl bg-[#060B18] text-slate-300 hover:text-emerald-400 hover:bg-[#1C2541] border border-slate-800 transition-all"
                                        title="Share on WhatsApp"
                                    >
                                        <MessageCircle className="w-4 h-4" />
                                    </a>
                                    <button
                                        type="button"
                                        onClick={handleCopyLink}
                                        className={`px-3 py-2 rounded-xl text-xs font-semibold border flex items-center gap-1.5 transition-all ${
                                            copied
                                                ? 'bg-emerald-500/10 text-emerald-400 border-emerald-500/30'
                                                : 'bg-[#060B18] text-slate-300 hover:text-[#00F2FE] border-slate-800'
                                        }`}
                                    >
                                        {copied ? <Check className="w-3.5 h-3.5" /> : <Link2 className="w-3.5 h-3.5" />}
                                        {copied ? 'Copied!' : 'Copy Link'}
                                    </button>
                                </div>
                            </div>
                        </div>

                        {/* Right Sticky Sidebar: TOC & Share */}
                        <div className="hidden lg:block lg:col-span-4 sticky top-28 space-y-6">
                            {/* Table of Contents Box */}
                            {tocItems.length > 0 && (
                                <div className="p-6 rounded-3xl bg-[#0B132B] border border-slate-800 space-y-4">
                                    <div className="flex items-center gap-2 pb-3 border-b border-slate-800">
                                        <ListTree className="w-4 h-4 text-[#00F2FE]" />
                                        <h3 className="text-xs font-bold text-white uppercase tracking-wider">
                                            Table of Contents
                                        </h3>
                                    </div>

                                    <nav className="space-y-1.5 max-h-[60vh] overflow-y-auto pr-1">
                                        {tocItems.map((item, idx) => (
                                            <button
                                                key={idx}
                                                type="button"
                                                onClick={() => scrollToHeading(item.id)}
                                                className={`w-full text-left text-xs py-1.5 px-2.5 rounded-lg transition-all flex items-start gap-2 ${
                                                    item.level === 3 ? 'pl-5 text-slate-400' : 'font-semibold text-slate-300'
                                                } ${
                                                    activeSection === item.id
                                                        ? 'bg-[#00F2FE]/10 text-[#00F2FE] font-bold border border-[#00F2FE]/30'
                                                        : 'hover:text-white hover:bg-[#060B18]'
                                                }`}
                                            >
                                                <ChevronRight className={`w-3.5 h-3.5 shrink-0 mt-0.5 ${activeSection === item.id ? 'text-[#00F2FE]' : 'text-slate-600'}`} />
                                                <span className="line-clamp-2">{item.text}</span>
                                            </button>
                                        ))}
                                    </nav>
                                </div>
                            )}

                            {/* Sticky Share Card */}
                            <div className="p-6 rounded-3xl bg-[#0B132B] border border-slate-800 space-y-4">
                                <h4 className="text-xs font-bold text-white uppercase tracking-wider flex items-center gap-2">
                                    <Share2 className="w-3.5 h-3.5 text-[#00F2FE]" /> Quick Share
                                </h4>
                                <div className="grid grid-cols-2 gap-2">
                                    <a
                                        href={`https://twitter.com/intent/tweet?text=${encodedTitle}&url=${encodedUrl}`}
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className="px-3 py-2 rounded-xl bg-[#060B18] text-xs font-semibold text-slate-300 hover:text-[#00F2FE] border border-slate-800 flex items-center gap-2 justify-center"
                                    >
                                        <Twitter className="w-3.5 h-3.5" /> Twitter
                                    </a>
                                    <a
                                        href={`https://www.linkedin.com/sharing/share-offsite/?url=${encodedUrl}`}
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className="px-3 py-2 rounded-xl bg-[#060B18] text-xs font-semibold text-slate-300 hover:text-[#00F2FE] border border-slate-800 flex items-center gap-2 justify-center"
                                    >
                                        <Linkedin className="w-3.5 h-3.5" /> LinkedIn
                                    </a>
                                </div>
                                <button
                                    type="button"
                                    onClick={handleCopyLink}
                                    className={`w-full py-2 rounded-xl text-xs font-bold border flex items-center justify-center gap-1.5 transition-all ${
                                        copied
                                            ? 'bg-emerald-500/10 text-emerald-400 border-emerald-500/30'
                                            : 'bg-gradient-to-r from-[#00F2FE]/10 to-[#4FACFE]/10 text-[#00F2FE] border-[#00F2FE]/30 hover:bg-[#00F2FE]/20'
                                    }`}
                                >
                                    {copied ? <Check className="w-3.5 h-3.5" /> : <Link2 className="w-3.5 h-3.5" />}
                                    {copied ? 'Link Copied to Clipboard!' : 'Copy Article Link'}
                                </button>
                            </div>

                            {/* CTA Box: Estimate Project */}
                            <div className="p-6 rounded-3xl bg-gradient-to-b from-[#00F2FE]/10 via-[#0B132B] to-[#0B132B] border border-[#00F2FE]/30 text-center space-y-3 shadow-lg shadow-cyan-500/5">
                                <Sparkles className="w-6 h-6 text-[#00F2FE] mx-auto" />
                                <h4 className="text-sm font-bold text-white">Have a Project in Mind?</h4>
                                <p className="text-xs text-slate-300">Calculate instant budgets & timelines with our interactive project estimator.</p>
                                <Link
                                    href="/estimate"
                                    className="inline-flex w-full py-2.5 px-4 rounded-xl text-xs font-bold bg-gradient-to-r from-[#00F2FE] to-[#4FACFE] text-[#060B18] hover:opacity-95 items-center justify-center gap-1.5 shadow-md shadow-cyan-500/20"
                                >
                                    Try Project Estimator
                                </Link>
                            </div>
                        </div>
                    </div>

                    {/* Related Articles */}
                    {relatedPosts && relatedPosts.length > 0 && (
                        <div className="pt-12 border-t border-slate-800 space-y-6">
                            <h3 className="text-2xl font-bold text-white">Related Articles</h3>
                            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                                {relatedPosts.map((p) => (
                                    <BlogCard key={p.id} post={p} />
                                ))}
                            </div>
                        </div>
                    )}
                </article>
            </main>

            <PublicFooter />
        </div>
    );
}

