import React from 'react';
import { useParams, Navigate, Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { PublicLayout } from '../../components/layout';
import { Calendar, Clock, ArrowLeft, User, Tag } from 'lucide-react';
import { blogPosts } from '../../constants/blog';

const BlogPostPage: React.FC = () => {
    const { slug } = useParams<{ slug: string }>();
    const { t, i18n } = useTranslation(['blog', 'common']);

    const post = blogPosts.find((p) => p.slug === slug);

    if (!post) {
        return <Navigate to="/blog" replace />;
    }

    // Helper to render content sections dynamically
    const renderContent = () => {
        // We need to access the structure of the content from the translation file
        // Since i18next t() function returns a string, we need to know the structure beforehand
        // or use returnObjects: true, but that returns an unknown type.
        // For this implementation, we'll assume a standard structure based on the existing blog.json

        // However, since the structure varies per post (e.g. problem_title, solution_1_title),
        // we might need a more flexible approach or standardized content structure.
        // Given the current JSON structure, it's quite specific per post.
        // A robust way is to use `t` with `returnObjects: true` and iterate, but for now,
        // let's try to render specific known sections if they exist, or just use a generic "content" key if we refactor.

        // Actually, looking at blog.json, the content is nested under `content`.
        // We can try to render the `intro` and then specific sections if we can infer them.
        // But since the keys are like `problem_title`, `solution_1_title`, it's hard to iterate without knowing keys.

        // A better approach for this specific codebase without refactoring all JSONs might be
        // to just render the `intro` and `conclusion` and maybe a "read full guide" if it was a real app,
        // but here we want to show the content.

        // Let's use `t` to get the whole content object and iterate over keys?
        // i18next `t` with `returnObjects: true` returns the object.
        const content = t(`blog:${post.titleKey.replace('.title', '.content')}`, { returnObjects: true });

        if (typeof content !== 'object' || content === null) {
            return <p>{t('blog:post.content_not_available')}</p>;
        }

        return (
            <div className="prose prose-lg max-w-none text-[var(--text-secondary)]">
                {Object.entries(content).map(([key, value]) => {
                    if (key === 'intro' || key === 'conclusion') {
                        return <p key={key} className="mb-6">{value as string}</p>;
                    }
                    if (key.endsWith('_title')) {
                        return <h3 key={key} className="text-2xl font-bold text-[var(--text-primary)] mt-8 mb-4">{value as string}</h3>;
                    }
                    if (key.endsWith('_desc')) {
                        // Check if it contains markdown-like bold
                        const text = value as string;
                        const parts = text.split(/(\*\*.*?\*\*)/g);
                        return (
                            <p key={key} className="mb-4">
                                {parts.map((part, i) => {
                                    if (part.startsWith('**') && part.endsWith('**')) {
                                        return <strong key={i} className="text-[var(--text-primary)]">{part.slice(2, -2)}</strong>;
                                    }
                                    return part;
                                })}
                            </p>
                        );
                    }
                    if (Array.isArray(value)) {
                        return (
                            <ul key={key} className="list-disc pl-6 mb-6 space-y-2">
                                {(value as string[]).map((item, index) => {
                                    // Handle bold text in list items
                                    const parts = item.split(/(\*\*.*?\*\*)/g);
                                    return (
                                        <li key={index}>
                                            {parts.map((part, i) => {
                                                if (part.startsWith('**') && part.endsWith('**')) {
                                                    return <strong key={i} className="text-[var(--text-primary)]">{part.slice(2, -2)}</strong>;
                                                }
                                                return part;
                                            })}
                                        </li>
                                    );
                                })}
                            </ul>
                        );
                    }
                    // Fallback for other string keys that might be paragraphs
                    if (typeof value === 'string' && !key.includes('_title') && !key.includes('_desc')) {
                        return <p key={key} className="mb-4">{value}</p>;
                    }
                    return null;
                })}
            </div>
        );
    };

    return (
        <PublicLayout
            variant="default"
            contentPadding="md"
            headerProps={{
                showThemeToggle: true,
                showAuthButtons: true,
                showLanguageSelector: true,
                variant: "default"
            }}
        >
            <article className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-16">
                {/* Back Link */}
                <Link
                    to="/blog"
                    className="inline-flex items-center gap-2 text-[var(--text-tertiary)] hover:text-[var(--color-primary)] mb-8 transition-colors"
                >
                    <ArrowLeft className="w-4 h-4" />
                    <span>{t('common:actions.back')}</span>
                </Link>

                {/* Header */}
                <header className="mb-12">
                    <div className="flex flex-wrap items-center gap-4 mb-6">
                        <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-[var(--color-primary)]/10 text-[var(--color-primary)]">
                            {t(`blog:${post.categoryKey}`)}
                        </span>
                        <div className="flex items-center gap-2 text-[var(--text-tertiary)]">
                            <Calendar className="w-4 h-4" />
                            <span>
                                {new Date(post.date).toLocaleDateString(i18n.language, {
                                    year: 'numeric',
                                    month: 'long',
                                    day: 'numeric',
                                })}
                            </span>
                        </div>
                        <div className="flex items-center gap-2 text-[var(--text-tertiary)]">
                            <Clock className="w-4 h-4" />
                            <span>{t('blog:post.read_time', { time: post.readTime })}</span>
                        </div>
                    </div>

                    <h1 className="text-4xl lg:text-5xl font-extrabold text-[var(--text-primary)] mb-6 leading-tight">
                        {t(`blog:${post.titleKey}`)}
                    </h1>

                    <div className="flex items-center gap-3 pb-8 border-b border-[var(--border-primary)]">
                        <div className="w-12 h-12 rounded-full bg-[var(--bg-tertiary)] flex items-center justify-center text-[var(--text-secondary)]">
                            <User className="w-6 h-6" />
                        </div>
                        <div>
                            <div className="font-medium text-[var(--text-primary)]">
                                {t(`blog:${post.authorKey}`)}
                            </div>
                            <div className="text-sm text-[var(--text-tertiary)]">
                                {t('blog:post.author_role', { defaultValue: 'Contributor' })}
                            </div>
                        </div>
                    </div>
                </header>

                {/* Content */}
                {renderContent()}

                {/* Footer Tags */}
                <div className="mt-12 pt-8 border-t border-[var(--border-primary)]">
                    <div className="flex flex-wrap gap-2">
                        {post.tagsKeys.map((tagKey) => (
                            <span
                                key={tagKey}
                                className="inline-flex items-center gap-1 px-3 py-1 rounded-full bg-[var(--bg-tertiary)] text-[var(--text-secondary)] text-sm"
                            >
                                <Tag className="w-3 h-3" />
                                {t(`blog:${tagKey}`)}
                            </span>
                        ))}
                    </div>
                </div>
            </article>
        </PublicLayout>
    );
};

export default BlogPostPage;
