'use client';

import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { api } from '@/lib/api';
import { useLanguage } from '@/lib/language-context';
import { sanitizeBlogHtml } from '@/lib/sanitize-blog-html';
import { Newspaper, PenLine } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';

interface BlogPost {
    _id: string;
    title: string;
    excerpt: string;
    content: string;
    authorName: string;
    createdAt: string;
}

export default function BlogPage() {
    const router = useRouter();
    const { t } = useLanguage();
    const [posts, setPosts] = useState<BlogPost[]>([]);
    const [loading, setLoading] = useState(true);
    const [selectedPost, setSelectedPost] = useState<BlogPost | null>(null);

    useEffect(() => {
        api.content.getBlogs().then((res) => {
            if (res.success && Array.isArray(res.data)) {
                setPosts(res.data as BlogPost[]);
            }
        }).finally(() => setLoading(false));
    }, []);

    return (
        <div className="min-h-screen bg-white pt-20">
            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-20">
                <div className="text-center mb-12">
                    <div className="flex justify-center mb-6">
                        <div className="p-4 bg-yellow-100 rounded-full">
                            <Newspaper className="w-12 h-12 text-yellow-600" />
                        </div>
                    </div>
                    <h1 className="text-4xl font-bold text-gray-900 mb-4">{t('blog.title')}</h1>
                    <p className="text-xl text-gray-600 mb-8 max-w-2xl mx-auto">
                        {t('blog.description')}
                    </p>
                </div>

                {loading ? (
                    <p className="text-center text-muted-foreground">{t('blog.loadingPosts')}</p>
                ) : posts.length === 0 ? (
                    <p className="text-center text-muted-foreground">{t('blog.noPostsAvailable')}</p>
                ) : (
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 mb-12">
                        {posts.map((post) => (
                            <div key={post._id} className="bg-gray-50 rounded-xl p-8 text-left border border-gray-100">
                                <div className="inline-flex items-center gap-2 text-xs text-cyan-700 bg-cyan-100 px-2 py-1 rounded-full mb-4">
                                    <PenLine className="w-3.5 h-3.5" />
                                    {new Date(post.createdAt).toLocaleDateString()}
                                </div>
                                <h2 className="text-xl font-semibold text-gray-900 mb-2">{post.title}</h2>
                                <p className="text-gray-600 text-sm mb-4">{post.excerpt}</p>
                                <p className="text-gray-500 text-xs">{t('blog.by')} {post.authorName}</p>
                                <div className="mt-4">
                                    <Button variant="outline" onClick={() => setSelectedPost(post)}>
                                        {t('common.view')}
                                    </Button>
                                </div>
                            </div>
                        ))}
                    </div>
                )}

                <div className="text-center">
                    <Button
                        onClick={() => router.push('/')}
                        className="bg-cyan-600 text-white hover:bg-cyan-500 rounded-full px-8"
                    >
                        {t('blog.backToHome')}
                    </Button>
                </div>
            </div>

            <Dialog open={!!selectedPost} onOpenChange={(open) => !open && setSelectedPost(null)}>
                <DialogContent className="max-h-[85vh] overflow-auto sm:max-w-3xl">
                    <DialogHeader>
                        <DialogTitle>{selectedPost?.title}</DialogTitle>
                    </DialogHeader>
                    <div className="space-y-3">
                        <p className="text-sm text-slate-500">
                            {t('blog.by')} {selectedPost?.authorName} • {selectedPost ? new Date(selectedPost.createdAt).toLocaleDateString() : ''}
                        </p>
                        <p className="text-sm font-medium text-slate-700">{selectedPost?.excerpt}</p>
                        <div
                            className="rounded-lg border border-slate-200 p-4 text-sm leading-relaxed text-slate-700 space-y-3 [&_img]:max-w-full [&_img]:h-auto [&_iframe]:w-full [&_iframe]:aspect-video [&_iframe]:max-w-full [&_a]:text-cyan-700 [&_a]:underline"
                            dangerouslySetInnerHTML={{ __html: sanitizeBlogHtml(selectedPost?.content || '') }}
                        />
                    </div>
                </DialogContent>
            </Dialog>
        </div>
    );
}
