import React, { useMemo, useState } from 'react';
import { Link, router } from '@inertiajs/react';
import { toast } from 'sonner';
import { MessageSquare, Hash, ExternalLink } from 'lucide-react';
import axios from 'axios';

import { Badge } from '@/Components/ui/badge';
import { Button } from '@/Components/ui/button';
import AdSlot from '@/Components/AdSlot';
import ConfirmModal from '@/Components/ConfirmModal';
import useTranslation from '@/hooks/useTranslation';
import { cn } from '@/lib/utils';

import ArticleHeader from './ArticleHeader';
import ArticleMedia from './ArticleMedia';
import ArticleBody from './ArticleBody';

export default function FullArticle({ post, onOpenComments, ads, inlineRelated, auth }) {
    const { t } = useTranslation();
    
    const isAuthor = auth?.user?.id === post.user_id;
    const isAdmin = auth?.user?.role === 'admin';
    const canEdit = isAuthor || isAdmin; 
    const canDelete = isAuthor || isAdmin;

    const [isDeleteOpen, setIsDeleteOpen] = useState(false);
    const [isDeleting, setIsDeleting] = useState(false);

    const sortedImages = useMemo(() => {
        if (!post.images || post.images.length === 0) return [];
        return [...post.images].sort((a, b) => (b.is_primary === 1) - (a.is_primary === 1));
    }, [post.images]);

    const gallerySlides = useMemo(() => {
        if (sortedImages.length > 0) {
            return sortedImages.map(img => ({ src: img.image_path, title: img.caption || null }));
        } else if (post.image_path) {
            return [{ src: post.image_path, title: post.title }];
        }
        return [];
    }, [sortedImages, post]);

    const handleDeletePost = async () => {
        setIsDeleting(true);
        try {
            const endpoint = isAdmin ? `/api/admin/posts/${post.id}` : `/api/user/my-posts/${post.id}`;
            await axios.delete(endpoint);
            toast.success(t('_deleted_success', 'Post deleted successfully'));
            router.visit('/'); 
        } catch (error) {
            console.error(error);
            toast.error(t('_delete_failed', 'Failed to delete post'));
            setIsDeleteOpen(false);
        } finally {
            setIsDeleting(false);
        }
    };

    const adHeader = ads?.['article_header'];
    const adMobileTop = ads?.['article_mobile_top']; 
    const adAfterCover = ads?.['article_after_cover'];
    const shouldShowAd = (ad) => ad && ad.is_active;

    return (
        <article className="mb-20 animate-in fade-in duration-700 bg-background">
            
            <ConfirmModal 
                open={isDeleteOpen}
                onOpenChange={setIsDeleteOpen}
                onConfirm={handleDeletePost}
                title={t('_delete_post', 'Delete Article?')}
                description={t('_delete_warning', 'Are you sure? This action cannot be undone.')}
                confirmText={isDeleting ? t('_deleting', 'Deleting...') : t('_yes_delete', 'Yes, Delete')}
                variant="destructive"
            />

            <div className="mb-8 flex flex-col items-center w-full">
                {shouldShowAd(adMobileTop) && (
                    <div className="md:hidden w-full">
                        <AdSlot ad={adMobileTop} className="mx-auto" />
                    </div>
                )}

                {shouldShowAd(adHeader) && (
                    <div className={cn("w-full", adMobileTop ? "hidden md:block" : "block")}>
                        <AdSlot ad={adHeader} className="max-w-[728px] mx-auto" />
                    </div>
                )}
            </div>

            <ArticleHeader 
                post={post} 
                auth={auth} 
                canEdit={canEdit} 
                canDelete={canDelete} 
                onOpenComments={onOpenComments} 
                setIsDeleteOpen={setIsDeleteOpen} 
            />

            <ArticleMedia 
                post={post} 
                sortedImages={sortedImages} 
                gallerySlides={gallerySlides} 
            />

            {shouldShowAd(adAfterCover) && (
                <div className="mb-8 flex justify-center my-8">
                    <div className="text-center">
                        <p className="text-[10px] text-muted-foreground uppercase tracking-widest mb-2">{t('_advertisement', 'Advertisement')}</p>
                        <AdSlot ad={adAfterCover} className="mx-auto" />
                    </div>
                </div>
            )}

            <ArticleBody 
                post={post} 
                inlineRelated={inlineRelated} 
            />

            {post.tags && post.tags.length > 0 && (
                <div className="flex flex-wrap gap-2 mb-8">
                    {post.tags.map((tag, index) => (
                        <Link key={index} href={route('tag.show', tag)}>
                            <Badge variant="secondary" className="px-3 py-1 flex items-center gap-1 hover:bg-primary/10 hover:text-primary transition-colors">
                                <Hash className="w-3 h-3 opacity-50" /> {tag}
                            </Badge>
                        </Link>
                    ))}
                </div>
            )}

            {post.source_url && (
                <div className="mb-10">
                    <a 
                        href={post.source_url} 
                        target="_blank" 
                        rel="noopener noreferrer" 
                        className="inline-flex items-center gap-2 text-sm font-semibold text-primary hover:text-primary/80 bg-primary/10 hover:bg-primary/20 px-4 py-2 rounded-full transition-colors"
                    >
                        <ExternalLink className="w-4 h-4" />
                        {t('_view_original_source', 'View original source')}
                    </a>
                </div>
            )}

            <div className="bg-muted/30 border rounded-lg p-6 flex flex-col sm:flex-row items-center justify-between gap-4">
                <div>
                    <h4 className="font-bold flex items-center gap-2">
                        <MessageSquare className="w-5 h-5 text-primary" /> {t('_join_conversation', 'Join the conversation')}
                    </h4>
                    <p className="text-sm text-muted-foreground mt-1">{t('_what_do_you_think', 'What do you think about this story?')}</p>
                </div>
                <Button variant="outline" onClick={() => onOpenComments(post.id)} className="hover:bg-primary hover:text-primary-foreground">
                    {t('_view_comments', 'View Comments')} ({post.comments_count || 0})
                </Button>
            </div>
            
        </article>
    );
}