import React, { useMemo, useState, useEffect } from 'react';
import { Link, usePage } from '@inertiajs/react';
import { Avatar, AvatarFallback, AvatarImage } from '@/Components/ui/avatar';
import { Button } from '@/Components/ui/button';
import { Badge } from '@/Components/ui/badge';
import { Switch } from '@/Components/ui/switch';
import { Label } from '@/Components/ui/label';
import { 
    Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, DialogDescription 
} from '@/Components/ui/dialog';
import { 
    Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger, SheetDescription 
} from '@/Components/ui/sheet';
import { 
    Breadcrumb,
    BreadcrumbItem,
    BreadcrumbLink,
    BreadcrumbList,
    BreadcrumbPage,
    BreadcrumbSeparator,
} from "@/components/ui/breadcrumb";
import { 
    Edit, Trash2, MessageCircle, ExternalLink, Rss, Star, Flame, PenTool, Sparkles 
} from 'lucide-react';
import VoteButtons from '@/Components/VoteButtons';
import ArticleShareMenu from './ArticleShareMenu';
import useTranslation from '@/hooks/useTranslation';
import axios from 'axios';
import { toast } from 'sonner';

function useMediaQuery(query) {
    const [matches, setMatches] = useState(false);
    useEffect(() => {
        const media = window.matchMedia(query);
        if (media.matches !== matches) setMatches(media.matches);
        const listener = () => setMatches(media.matches);
        window.addEventListener("resize", listener);
        return () => window.removeEventListener("resize", listener);
    },[matches, query]);
    return matches;
}

export default function ArticleHeader({ post, auth, canEdit, canDelete, onOpenComments, setIsDeleteOpen }) {
    const { t } = useTranslation();
    const { locale } = usePage().props;
    const isDesktop = useMediaQuery("(min-width: 768px)");
    const isAdmin = auth?.user?.role === 'admin';

    const [flags, setFlags] = useState({
        is_featured: post.is_featured || false,
        is_editor_pick: post.is_editor_pick || false,
        is_hot: post.is_hot || false,
    });

    const handleToggleFlag = async (key, value) => {
        const newFlags = { ...flags, [key]: value };
        setFlags(newFlags);
        try {
            await axios.patch(`/api/admin/posts/${post.id}/flags`, newFlags);
            toast.success(t('_highlights_updated', 'Highlights updated successfully'));
        } catch (error) {
            setFlags(flags);
            toast.error(t('_highlights_failed', 'Failed to update highlights'));
        }
    };

    const formatDate = (dateString) => {
        if (!dateString) return '';
        try {
            const safeLocale = locale ? locale.replace('_', '-') : 'en-US';
            return new Intl.DateTimeFormat(safeLocale, { 
                year: 'numeric', month: 'long', day: 'numeric' 
            }).format(new Date(dateString));
        } catch (e) {
            return new Date(dateString).toLocaleDateString();
        }
    };

    const authorDetails = useMemo(() => {
        if (post.rss_feed && post.rss_feed.show_author === false) {
            return {
                name: post.rss_feed.name,
                avatar: post.rss_feed.feed_logo,
                isFeed: true,
                link: route('source.show', post.rss_feed.id), 
                fallbackIcon: <Rss className="w-4 h-4" />
            };
        }
        return {
            name: post.user?.name || 'Unknown',
            avatar: post.user?.avatar,
            isFeed: false,
            link: route('author.show', post.user?.username || '#'),
            fallbackIcon: <span>{post.user?.name?.charAt(0) || 'U'}</span>
        };
    }, [post]);

    const AuthorWrapper = ({ children, className }) => (
        <Link href={authorDetails.link} className={className}>{children}</Link>
    );

    const HighlightsForm = () => (
        <div className="py-4 space-y-4">
            <div className="flex items-center justify-between border p-4 rounded-[var(--radius)] bg-card">
                <div className="space-y-0.5">
                    <Label className="flex items-center gap-2 text-base">
                        <Star className="w-4 h-4 text-amber-500 fill-amber-500" /> {t('_featured', 'Featured')}
                    </Label>
                    <p className="text-xs text-muted-foreground">{t('_featured_desc', 'Show in hero slider on homepage')}</p>
                </div>
                <Switch checked={flags.is_featured} onCheckedChange={(c) => handleToggleFlag('is_featured', c)} />
            </div>
            <div className="flex items-center justify-between border p-4 rounded-[var(--radius)] bg-card">
                <div className="space-y-0.5">
                    <Label className="flex items-center gap-2 text-base">
                        <PenTool className="w-4 h-4 text-indigo-500" /> {t('_editors_pick', "Editor's Pick")}
                    </Label>
                    <p className="text-xs text-muted-foreground">{t('_editors_pick_desc', 'Highlight as recommended reading')}</p>
                </div>
                <Switch checked={flags.is_editor_pick} onCheckedChange={(c) => handleToggleFlag('is_editor_pick', c)} />
            </div>
            <div className="flex items-center justify-between border p-4 rounded-[var(--radius)] bg-card">
                <div className="space-y-0.5">
                    <Label className="flex items-center gap-2 text-base">
                        <Flame className="w-4 h-4 text-red-500 fill-red-500" /> {t('_hot_news', 'Hot News')}
                    </Label>
                    <p className="text-xs text-muted-foreground">{t('_hot_news_desc', 'Mark as trending or urgent')}</p>
                </div>
                <Switch checked={flags.is_hot} onCheckedChange={(c) => handleToggleFlag('is_hot', c)} />
            </div>
        </div>
    );

    return (
        <header className="mb-8 mt-2">
            <Breadcrumb className="mb-5 text-sm sm:text-base">
                <BreadcrumbList>
                    <BreadcrumbItem>
                        <BreadcrumbLink asChild>
                            <Link href="/">{t('_home', 'Home')}</Link>
                        </BreadcrumbLink>
                    </BreadcrumbItem>
                    {post.category && (
                        <>
                            <BreadcrumbSeparator className="rtl:-scale-x-100" />
                            <BreadcrumbItem>
                                <BreadcrumbLink asChild>
                                    <Link href={route('category.show', post.category.slug)} className="text-primary font-medium">
                                        {post.category.name}
                                    </Link>
                                </BreadcrumbLink>
                            </BreadcrumbItem>
                        </>
                    )}
                    <BreadcrumbSeparator className="rtl:-scale-x-100" />
                    <BreadcrumbItem>
                        <BreadcrumbPage className="line-clamp-1 max-w-[150px] sm:max-w-[300px] md:max-w-[500px]">
                            {post.title}
                        </BreadcrumbPage>
                    </BreadcrumbItem>
                </BreadcrumbList>
            </Breadcrumb>

            {(flags.is_featured || flags.is_editor_pick || flags.is_hot) && (
                <div className="flex flex-wrap gap-2 mb-4">
                    {flags.is_featured && (
                        <Badge className="bg-amber-500 hover:bg-amber-600 text-white border-0 gap-1.5 px-2.5 rounded-[var(--radius)]">
                            <Star className="w-3.5 h-3.5 fill-current" /> {t('_featured', 'Featured')}
                        </Badge>
                    )}
                    {flags.is_editor_pick && (
                        <Badge className="bg-indigo-500 hover:bg-indigo-600 text-white border-0 gap-1.5 px-2.5 rounded-[var(--radius)]">
                            <PenTool className="w-3.5 h-3.5" /> {t('_editors_pick', "Editor's Pick")}
                        </Badge>
                    )}
                    {flags.is_hot && (
                        <Badge className="bg-red-500 hover:bg-red-600 text-white border-0 gap-1.5 px-2.5 rounded-[var(--radius)]">
                            <Flame className="w-3.5 h-3.5 fill-current" /> {t('_hot', 'Hot')}
                        </Badge>
                    )}
                </div>
            )}

            <h1 className="text-3xl md:text-5xl font-extrabold leading-tight font-serif tracking-tight mb-4 text-foreground">
                {post.title}
            </h1>
            
            {post.meta_description && (
                <p className="text-lg md:text-xl text-muted-foreground leading-relaxed mb-6">
                    {post.meta_description}
                </p>
            )}

            <div className="flex flex-col sm:flex-row sm:items-center justify-between border-y border-border py-4 gap-4">
                <div className="flex items-center gap-3">
                    <AuthorWrapper className="shrink-0">
                        <Avatar className="h-10 w-10 border border-border">
                            <AvatarImage src={authorDetails.avatar} className="object-cover" />
                            <AvatarFallback>{authorDetails.fallbackIcon}</AvatarFallback>
                        </Avatar>
                    </AuthorWrapper>
                    <div className="flex flex-col">
                        <AuthorWrapper className="text-sm font-bold hover:underline hover:text-primary transition-colors">
                            {authorDetails.isFeed ? `${t('_via', 'via')} ${authorDetails.name}` : authorDetails.name}
                        </AuthorWrapper>
                        <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
                            <span>{formatDate(post.created_at)}</span>
                            {post.source_url && (
                                <>
                                    <span className="opacity-50 hidden sm:inline">•</span>
                                    <a href={post.source_url} target="_blank" rel="noopener noreferrer" className="flex items-center gap-1 text-primary hover:underline transition-colors">
                                        <ExternalLink className="w-3 h-3" /> {t('_source', 'Source')}
                                    </a>
                                </>
                            )}
                        </div>
                    </div>
                </div>

                <div className="flex flex-wrap items-center gap-2 sm:gap-3 w-full sm:w-auto mt-2 sm:mt-0">
                    <VoteButtons post={post} auth={auth} />

                    <Button variant="secondary" size="sm" className="h-9 text-xs sm:text-sm gap-2 rounded-[var(--radius)]" onClick={() => onOpenComments(post.id)}>
                        <MessageCircle className="w-4 h-4" /> {post.comments_count || 0}
                    </Button>

                    {isAdmin && (
                        isDesktop ? (
                            <Dialog>
                                <DialogTrigger asChild>
                                    <Button variant="outline" size="sm" className="h-9 gap-2 text-primary border-primary/20 hover:bg-primary/5 rounded-[var(--radius)]">
                                        <Sparkles className="w-4 h-4" />
                                        <span className="hidden sm:inline">{t('_highlights', 'Highlights')}</span>
                                    </Button>
                                </DialogTrigger>
                                <DialogContent className="sm:max-w-md z-[200] rounded-[var(--radius)]">
                                    <DialogHeader>
                                        <DialogTitle>{t('_manage_highlights', 'Manage Article Highlights')}</DialogTitle>
                                        <DialogDescription>{t('_toggle_tags_desc', 'Toggle tags dynamically.')}</DialogDescription>
                                    </DialogHeader>
                                    <HighlightsForm />
                                </DialogContent>
                            </Dialog>
                        ) : (
                            <Sheet>
                                <SheetTrigger asChild>
                                    <Button variant="outline" size="sm" className="h-9 gap-2 text-primary border-primary/20 hover:bg-primary/5 rounded-[var(--radius)]">
                                        <Sparkles className="w-4 h-4" />
                                        <span className="hidden sm:inline">{t('_highlights', 'Highlights')}</span>
                                    </Button>
                                </SheetTrigger>
                                <SheetContent side="bottom" className="rounded-t-2xl z-[200]">
                                    <SheetHeader className="text-start">
                                        <SheetTitle>{t('_manage_highlights', 'Manage Article Highlights')}</SheetTitle>
                                        <SheetDescription>{t('_toggle_tags_desc', 'Toggle tags dynamically.')}</SheetDescription>
                                    </SheetHeader>
                                    <HighlightsForm />
                                </SheetContent>
                            </Sheet>
                        )
                    )}

                    {canEdit && (
                        <Button variant="outline" size="icon" className="h-9 w-9 shrink-0 rounded-[var(--radius)]" asChild>
                            <Link href={route('my-posts.edit', post.id)}>
                                <Edit className="w-4 h-4" />
                            </Link>
                        </Button>
                    )}

                    {canDelete && (
                        <Button variant="ghost" size="icon" className="h-9 w-9 shrink-0 text-red-500 hover:text-red-700 hover:bg-red-50 rounded-[var(--radius)]" onClick={() => setIsDeleteOpen(true)}>
                            <Trash2 className="w-4 h-4" />
                        </Button>
                    )}

                    <ArticleShareMenu postSlug={post.slug} postTitle={post.title} />
                </div>
            </div>
        </header>
    );
}