"use client";

import React, { useState } from 'react';
import { Link01, Copy01 } from '@untitledui/icons';
import { Badge, BadgeGroup, Button, Form, Input, Avatar, Breadcrumb, MarkdownRenderer, PhotoWithFallback } from '../elements';
import { extractTableOfContents } from '../../utils/markdown-toc';
import { getAvatarUrl } from '../../utils/photo-helpers';
import type { BlogPost } from '../../types/api/blog-post';

interface ExtendedBlogPost extends BlogPost {
    category?: { name: string };
    reading_time_minutes?: number;
    excerpt?: string;
    tags?: Array<{ name: string } | string>;
}

interface TableOfContentsItem {
    id: string;
    title: string;
    level: number;
}

interface BlogPostSectionProps {
    blogPost?: ExtendedBlogPost | null;
}

export const BlogPostSection = ({
    blogPost,
}: BlogPostSectionProps) => {

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

    // Extract table of contents from markdown
    const tableOfContents = blogPost?.content_markdown 
        ? extractTableOfContents(blogPost.content_markdown)
        : [];

    const [copied, setCopied] = useState(false);

    const handleCopyLink = async () => {
        try {
            await navigator.clipboard.writeText(window.location.href);
            setCopied(true);
            setTimeout(() => setCopied(false), 2000);
        } catch (err) {
            console.error('Failed to copy:', err);
        }
    };

    const handleShareLink = () => {
        if (navigator.share) {
            navigator.share({
                title: blogPost?.title,
                url: window.location.href,
            }).catch((err) => {
                console.error('Error sharing:', err);
            });
        } else {
            // Fallback to copy if share is not available
            handleCopyLink();
        }
    };

    if (!blogPost) {
        return (
            <div className="text-center py-12">
                <div className="text-gray-600 text-6xl mb-4">📝</div>
                <h3 className="text-xl font-semibold text-gray-900 mb-2">Blog Post Not Found</h3>
                <p className="text-gray-600 mb-4">The blog post you&apos;re looking for doesn&apos;t exist.</p>
                <Button href="/blog">View All Blog Posts</Button>
            </div>
        );
    }

    return (
        <>
            {/* Breadcrumb - top left aligned */}
            <section className="bg-primary py-2 md:py-2">
                <div className="mx-auto max-w-container px-4 md:px-8">
                    <Breadcrumb 
                        backHref="/blog" 
                        backLabel="Blog" 
                        currentLabel={blogPost.title} 
                    />
                </div>
            </section>

            {/* Blog Post Header with Image */}
            <section className="bg-primary py-4 md:py-6">
                <div className="relative mx-auto max-w-container gap-16 px-4 pb-16 md:gap-8 md:px-8 md:pt-16 md:pb-24 grid grid-cols-1 items-center md:grid-cols-2">
                    <div className="flex max-w-180 flex-col items-start">
                        <BadgeGroup 
                            size="md" 
                            addonText={blogPost.category?.name || "Blog"} 
                            color="brand" 
                            theme="modern" 
                            className="pr-3 mt-4" 
                            iconTrailing={null}
                        >
                            {blogPost.reading_time_minutes 
                                ? `${blogPost.reading_time_minutes} min read` 
                                : (blogPost.published_at ? formatDate(blogPost.published_at) : 'Recent')}
                        </BadgeGroup>
                        
                        <h1 className="mt-4 text-display-md font-semibold text-primary md:text-display-lg">
                            {blogPost.title}
                        </h1>
                        {blogPost.excerpt && (
                            <p className="mt-4 text-lg text-tertiary md:mt-6 md:max-w-120 md:text-xl">
                                {(blogPost.excerpt || blogPost.excerpt_markdown?.replace(/[#*\[\]()]/g, '').trim() || '').replace(/[#*\[\]()]/g, '').trim()}
                            </p>
                        )}
                    </div>

                    {/* Hero Image - Always show with fallback support */}
                    <PhotoWithFallback
                        item={blogPost}
                        fallbackId={blogPost.id}
                        alt={blogPost.title}
                        className="order-first -ml-4 h-36 w-screen max-w-none object-cover md:order-1 md:ml-0 md:h-96 md:w-full md:max-w-full rounded-2xl"
                    />
                </div>

                {/* Content Section with Sidebar */}
                {blogPost.content_markdown && (
                    <div className="mx-auto max-w-container px-4 pb-16 md:px-8 md:pb-24">
                        <div className="mx-auto flex justify-center gap-16">
                            {/* Left sidebar - hidden on mobile */}
                            <div className="hidden w-70 flex-col gap-8 lg:flex">
                                {tableOfContents.length > 0 && (
                                    <>
                                        <div className="w-full border-t border-secondary" />
                                        <div className="flex flex-col gap-4">
                                            <p className="text-md font-semibold text-brand-secondary">Table of contents</p>
                                            <ul className="flex flex-col gap-3">
                                                {tableOfContents.map((item: TableOfContentsItem) => (
                                                    <li key={item.id}>
                                                        <Button 
                                                            size="lg" 
                                                            color="link-gray" 
                                                            href={`#${item.id}`}
                                                            className={`${item.level === 3 ? 'pl-4' : ''} w-full text-left whitespace-normal justify-start`}
                                                        >
                                                            <span className="break-words block w-full">{item.title}</span>
                                                        </Button>
                                                    </li>
                                                ))}
                                            </ul>
                                        </div>
                                        <div className="w-full border-t border-secondary" />
                                    </>
                                )}
                                {blogPost.blog_post_authors && Array.isArray(blogPost.blog_post_authors) && blogPost.blog_post_authors.length > 0 && (
                                    <div className="flex flex-col gap-6">
                                        <p className="text-md font-semibold text-brand-secondary">Author</p>
                                        <div className="flex items-center gap-3">
                                            {(() => {
                                                const author = blogPost.blog_post_authors[0];
                                                const authorName = author?.name || 'Author';
                                                const authorAvatarUrl = getAvatarUrl(author?.photo_attachments, author?.id, authorName);
                                                return (
                                                    <>
                                                        <Avatar
                                                            src={authorAvatarUrl ?? undefined}
                                                            alt={authorName}
                                                            initials={authorName.trim().charAt(0).toUpperCase() || '?'}
                                                            size="md"
                                                        />
                                                        <div>
                                                            <p className="text-md font-semibold text-primary">{authorName}</p>
                                                            {author?.bio_markdown && (
                                                                <p className="text-md text-tertiary">{author.bio_markdown.replace(/[#*\[\]()]/g, '').trim().substring(0, 100)}</p>
                                                            )}
                                                        </div>
                                                    </>
                                                );
                                            })()}
                                        </div>
                                    </div>
                                )}
                                <div className="w-full border-t border-secondary" />
                                <Form
                                    onSubmit={(e: React.FormEvent<HTMLFormElement>) => {
                                        e.preventDefault();
                                        const formData = new FormData(e.currentTarget);
                                        console.log("Form data:", formData);
                                    }}
                                    className="flex flex-col gap-4"
                                >
                                    <label htmlFor="blog-email-input" className="text-md font-semibold text-brand-secondary">
                                        Subscribe to our newsletter
                                    </label>
                                    <Input isRequired id="blog-email-input" name="email" type="email" placeholder="Enter your email" size="md" />
                                    <Button type="submit" size="xl">
                                        Subscribe
                                    </Button>
                                </Form>
                                <div className="w-full border-t border-secondary" />
                                <div className="flex gap-3">
                                    <button
                                        onClick={handleShareLink}
                                        title="Share link"
                                        className="inline-flex h-max cursor-pointer items-center justify-center gap-1.5 rounded-lg px-3.5 py-2.5 text-sm font-semibold outline-brand transition duration-100 ease-linear focus-visible:outline-2 focus-visible:outline-offset-2 bg-secondary text-primary hover:bg-secondary_hover"
                                    >
                                        <Link01 className="size-5 shrink-0" />
                                    </button>
                                    <button
                                        onClick={handleCopyLink}
                                        title={copied ? "Copied!" : "Copy link"}
                                        className="inline-flex h-max cursor-pointer items-center justify-center gap-1.5 rounded-lg px-3.5 py-2.5 text-sm font-semibold outline-brand transition duration-100 ease-linear focus-visible:outline-2 focus-visible:outline-offset-2 bg-secondary text-fg-quaternary hover:bg-secondary_hover"
                                    >
                                        <Copy01 className="size-5 shrink-0" />
                                    </button>
                                </div>
                            </div>

                            {/* Main content */}
                            <div className="max-w-prose lg:max-w-180">
                                <div className="prose-centered-quote mx-auto prose md:prose-lg" id="content">
                                    <MarkdownRenderer content={blogPost.content_markdown || ''} />
                                </div>

                                {/* Mobile-only contributors and social */}
                                <div className="flex flex-col items-start justify-between gap-y-8 lg:hidden lg:flex-row mt-8">
                                    {blogPost.blog_post_authors && Array.isArray(blogPost.blog_post_authors) && blogPost.blog_post_authors.length > 0 && (
                                        <div className="flex flex-col gap-6">
                                            <p className="text-md font-semibold text-brand-secondary">Author</p>
                                            <div className="flex items-center gap-3">
                                                {(() => {
                                                    const author = blogPost.blog_post_authors[0];
                                                    const authorName = author?.name || 'Author';
                                                    const authorAvatarUrl = getAvatarUrl(author?.photo_attachments, author?.id, authorName);
                                                    return (
                                                        <>
                                                            <Avatar
                                                                src={authorAvatarUrl ?? undefined}
                                                                alt={authorName}
                                                                initials={authorName.trim().charAt(0).toUpperCase() || '?'}
                                                                size="md"
                                                            />
                                                            <div>
                                                                <p className="text-md font-semibold text-primary">{authorName}</p>
                                                                {author?.bio_markdown && (
                                                                    <p className="text-md text-tertiary">{author.bio_markdown.replace(/[#*\[\]()]/g, '').trim().substring(0, 100)}</p>
                                                                )}
                                                            </div>
                                                        </>
                                                    );
                                                })()}
                                            </div>
                                        </div>
                                    )}
                                    <div className="flex gap-3">
                                        <button
                                            onClick={handleShareLink}
                                            title="Share link"
                                            className="inline-flex h-max cursor-pointer items-center justify-center gap-1.5 rounded-lg px-3.5 py-2.5 text-sm font-semibold outline-brand transition duration-100 ease-linear focus-visible:outline-2 focus-visible:outline-offset-2 bg-secondary text-primary hover:bg-secondary_hover"
                                        >
                                            <Link01 className="size-5 shrink-0" />
                                        </button>
                                        <button
                                            onClick={handleCopyLink}
                                            title={copied ? "Copied!" : "Copy link"}
                                            className="inline-flex h-max cursor-pointer items-center justify-center gap-1.5 rounded-lg px-3.5 py-2.5 text-sm font-semibold outline-brand transition duration-100 ease-linear focus-visible:outline-2 focus-visible:outline-offset-2 bg-secondary text-fg-quaternary hover:bg-secondary_hover"
                                        >
                                            <Copy01 className="size-5 shrink-0" />
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                )}
            </section>

            {/* Navigation */}
            <section className="bg-primary pb-16 md:pb-24">
                <div className="mx-auto max-w-container px-4 md:px-8">
                    <div className="mx-auto max-w-prose md:max-w-180">
                        <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-end border-t border-secondary pt-8">
                            {blogPost.tags && Array.isArray(blogPost.tags) && blogPost.tags.length > 0 && (
                                <div className="flex flex-wrap gap-2">
                                    {blogPost.tags.map((tag, index: number) => (
                                        <Badge key={index} color="gray" size="md" type="modern">
                                            {typeof tag === 'string' ? tag : tag.name}
                                        </Badge>
                                    ))}
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </section>
        </>
    );
};
