import { useState, useEffect } from 'react';
import { useRouter } from 'next/router';
import Image from 'next/image';
import Link from 'next/link';
import { useAuth } from '@/hooks/useAuth';
import MainLayout from '@/components/layouts/MainLayout';
import CommentSection from '@/components/article/CommentSection';
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Loader2, Lock, Download, Calendar, User as UserIcon, Tag as TagIcon, Share2, Crown, FileText, Eye, ShoppingCart, Copy, Check, Box, HardDrive } from 'lucide-react';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { toast } from 'sonner';

interface Article {
    _id: string;
    文章标题: string;
    封面图: string;
    摘要: string;
    正文内容: string;
    作者ID: {
        用户名: string;
        头像: string;
    };
    分类ID: {
        _id: string;
        分类名称: string;
    };
    标签ID列表: {
        标签名称: string;
    }[];
    价格: number;
    支付方式: 'points' | 'cash' | 'membership_free';
    资源属性?: {
        下载链接: string;
        提取码: string;
        解压密码: string;
        隐藏内容: string;
        版本号?: string;
        文件大小?: string;
        扩展属性?: { 属性名: string; 属性值: string }[];
    };
    createdAt: string;
    统计数据: {
        阅读数: number;
        销量: number;
    };
}

export default function ArticleDetail() {
    const router = useRouter();
    const { id } = router.query;
    const { user } = useAuth();
    const [article, setArticle] = useState<Article | null>(null);
    const [recentArticles, setRecentArticles] = useState<Article[]>([]);
    const [loading, setLoading] = useState(true);
    const [hasAccess, setHasAccess] = useState(false);
    const [purchasing, setPurchasing] = useState(false);
    const [copiedField, setCopiedField] = useState<string | null>(null);

    useEffect(() => {
        if (id) {
            fetchArticle();
            fetchRecentArticles();
        }
    }, [id]);

    const fetchArticle = async () => {
        try {
            const res = await fetch(`/api/articles/${id}`);
            if (res.ok) {
                const data = await res.json();
                setArticle(data.article);
                setHasAccess(data.hasAccess);
            } else {
                toast.error('文章不存在或已被删除');
                router.push('/');
            }
        } catch (error) {
            console.error('Failed to fetch article', error);
        } finally {
            setLoading(false);
        }
    };

    const fetchRecentArticles = async () => {
        try {
            const res = await fetch('/api/articles?limit=5');
            if (res.ok) {
                const data = await res.json();
                // Filter out current article if present
                const filtered = data.articles.filter((a: Article) => a._id !== id);
                setRecentArticles(filtered.slice(0, 5));
            }
        } catch (error) {
            console.error('Failed to fetch recent articles', error);
        }
    };

    const handlePurchase = async () => {
        if (!user) {
            router.push(`/auth/login?redirect=${encodeURIComponent(router.asPath)}`);
            return;
        }

        if (!article) return;

        // If price is 0, it should be accessible, but just in case
        if (article.价格 === 0) return;

        setPurchasing(true);
        try {
            const res = await fetch('/api/orders/create', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    type: 'buy_resource',
                    itemId: article._id,
                    paymentMethod: 'alipay', // Default to alipay for now
                    returnUrl: window.location.href // Pass current page URL for redirect after payment
                }),
            });

            if (res.ok) {
                const data = await res.json();
                // Redirect to Alipay
                window.location.href = data.payUrl;
            } else {
                const data = await res.json();
                toast.error(data.message || '创建订单失败');
            }
        } catch (error) {
            toast.error('网络错误，请稍后重试');
        } finally {
            setPurchasing(false);
        }
    };

    const handleShare = () => {
        const url = window.location.href;
        navigator.clipboard.writeText(url).then(() => {
            toast.success('链接已复制到剪贴板');
        }).catch(() => {
            toast.error('复制失败');
        });
    };

    const copyToClipboard = (text: string, field: string) => {
        navigator.clipboard.writeText(text).then(() => {
            setCopiedField(field);
            toast.success('复制成功');
            setTimeout(() => setCopiedField(null), 2000);
        }).catch(() => {
            toast.error('复制失败');
        });
    };

    if (loading) {
        return (
            <MainLayout>
                <div className="container mx-auto px-4 py-8 max-w-6xl">
                    <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
                        <div className="lg:col-span-3 space-y-8">
                            <Skeleton className="h-12 w-3/4" />
                            <Skeleton className="h-[400px] w-full rounded-xl" />
                            <div className="space-y-4">
                                <Skeleton className="h-4 w-full" />
                                <Skeleton className="h-4 w-full" />
                                <Skeleton className="h-4 w-5/6" />
                            </div>
                        </div>
                        <div className="lg:col-span-1 space-y-6">
                            <Skeleton className="h-[300px] w-full rounded-xl" />
                            <Skeleton className="h-[200px] w-full rounded-xl" />
                        </div>
                    </div>
                </div>
            </MainLayout>
        );
    }

    if (!article) return null;

    return (
        <MainLayout
            seo={{
                title: article.文章标题,
                description: article.摘要 || article.正文内容.substring(0, 100),
                keywords: article.标签ID列表?.map(t => t.标签名称).join(',')
            }}
        >
            <div className="max-w-7xl mx-auto px-4 py-8">
                <div className="grid grid-cols-1 lg:grid-cols-10 gap-8">
                    {/* Main Content - Left Column (70%) */}
                    <div className="lg:col-span-7">
                        {/* Article Header */}
                        <div className="mb-8">
                            <div className="flex items-center gap-2 mb-4">
                                <Badge variant="secondary" className="text-primary bg-primary/10 hover:bg-primary/20">
                                    {article.分类ID?.分类名称 || '未分类'}
                                </Badge>
                                {article.标签ID列表?.map((tag, index) => (
                                    <Badge key={index} variant="outline" className="text-muted-foreground">
                                        {tag.标签名称}
                                    </Badge>
                                ))}
                            </div>

                            <h1 className="text-3xl md:text-4xl font-bold text-foreground mb-6 leading-tight">
                                {article.文章标题}
                            </h1>

                            <div className="flex flex-wrap items-center justify-between gap-4 border-b border-border pb-8">
                                <div className="flex items-center gap-6 text-sm text-muted-foreground">
                                    <div className="flex items-center gap-2">
                                        <UserIcon className="w-4 h-4" />
                                        <span>{article.作者ID?.用户名 || '匿名'}</span>
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <Calendar className="w-4 h-4" />
                                        <span>{format(new Date(article.createdAt), 'yyyy-MM-dd', { locale: zhCN })}</span>
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <Eye className="w-4 h-4" />
                                        <span>{article.统计数据?.阅读数 || 0} 阅读</span>
                                    </div>
                                </div>

                                <Button variant="ghost" size="sm" onClick={handleShare} className="text-muted-foreground hover:text-primary">
                                    <Share2 className="w-4 h-4 mr-2" />
                                    分享
                                </Button>
                            </div>
                        </div>

                        {/* Cover Image */}
                        {article.封面图 && (
                            <div className="mb-10 rounded-xl overflow-hidden shadow-lg relative aspect-video bg-muted">
                                <Image
                                    src={article.封面图}
                                    alt={article.文章标题}
                                    fill
                                    className="object-cover"
                                    priority
                                    sizes="(max-width: 768px) 100vw, (max-width: 1200px) 80vw, 800px"
                                />
                            </div>
                        )}

                        {/* Article Content */}
                        <article className="prose prose-lg max-w-none mb-12 prose-headings:text-foreground prose-p:text-foreground prose-a:text-primary hover:prose-a:text-primary/80 prose-img:rounded-xl dark:prose-invert">
                            <div dangerouslySetInnerHTML={{ __html: article.正文内容 }} />
                        </article>

                        {/* Comments Section */}
                        <CommentSection articleId={article._id} isLoggedIn={!!user} />
                    </div>

                    {/* Sidebar - Right Column (30%) */}
                    <div className="lg:col-span-3 space-y-6">
                        {/* Resource Card */}
                        <Card className="border-primary/20 shadow-md overflow-hidden">
                            <div className="bg-linear-to-r from-primary/10 to-primary/5 p-4 border-b border-primary/10">
                                <h3 className="font-bold text-lg flex items-center gap-2 text-foreground">
                                    <Download className="w-5 h-5 text-primary" />
                                    资源下载
                                </h3>
                            </div>
                            <CardContent className="p-6 space-y-6">
                                <div className="flex items-baseline justify-between">
                                    <span className="text-sm text-muted-foreground">资源价格</span>
                                    <div className="flex items-baseline gap-1">
                                        <span className="text-2xl font-bold text-primary">
                                            {article.价格 > 0 ? `¥${article.价格}` : '免费'}
                                        </span>
                                        {article.价格 > 0 && <span className="text-xs text-muted-foreground">/ 永久</span>}
                                    </div>
                                </div>

                                {/* Resource Attributes (Version, Size, etc.) */}
                                {article.资源属性 && (
                                    <div className="grid grid-cols-2 gap-2 text-xs text-muted-foreground bg-muted/50 p-3 rounded-lg border border-border">
                                        {article.资源属性.版本号 && (
                                            <div className="flex items-center gap-1.5">
                                                <Box className="w-3.5 h-3.5 text-muted-foreground" />
                                                <span>版本: {article.资源属性.版本号}</span>
                                            </div>
                                        )}
                                        {article.资源属性.文件大小 && (
                                            <div className="flex items-center gap-1.5">
                                                <HardDrive className="w-3.5 h-3.5 text-muted-foreground" />
                                                <span>大小: {article.资源属性.文件大小}</span>
                                            </div>
                                        )}
                                        {article.资源属性.扩展属性?.map((attr, idx) => (
                                            <div key={idx} className="flex items-center gap-1.5 col-span-2">
                                                <TagIcon className="w-3.5 h-3.5 text-muted-foreground" />
                                                <span>{attr.属性名}: {attr.属性值}</span>
                                            </div>
                                        ))}
                                    </div>
                                )}

                                {hasAccess ? (
                                    <div className="space-y-4 animate-in fade-in duration-500">
                                        <div className="bg-green-50 text-green-700 px-4 py-3 rounded-lg text-sm flex items-center gap-2 border border-green-100">
                                            <Check className="w-4 h-4" />
                                            您已拥有此资源权限
                                        </div>

                                        {article.资源属性 && (
                                            <div className="space-y-3">
                                                <Button className="w-full" asChild>
                                                    <a href={article.资源属性.下载链接} target="_blank" rel="noopener noreferrer">
                                                        <Download className="w-4 h-4 mr-2" />
                                                        立即下载
                                                    </a>
                                                </Button>

                                                {article.资源属性.提取码 && (
                                                    <div className="flex items-center justify-between bg-muted/50 p-2 rounded text-sm border border-border">
                                                        <span className="text-muted-foreground pl-1">提取码: {article.资源属性.提取码}</span>
                                                        <Button
                                                            variant="ghost"
                                                            size="icon"
                                                            className="h-6 w-6"
                                                            onClick={() => copyToClipboard(article.资源属性!.提取码, 'code')}
                                                        >
                                                            {copiedField === 'code' ? <Check className="w-3 h-3 text-green-600" /> : <Copy className="w-3 h-3" />}
                                                        </Button>
                                                    </div>
                                                )}

                                                {article.资源属性.解压密码 && (
                                                    <div className="flex items-center justify-between bg-muted/50 p-2 rounded text-sm border border-border">
                                                        <span className="text-muted-foreground pl-1">解压密码: {article.资源属性.解压密码}</span>
                                                        <Button
                                                            variant="ghost"
                                                            size="icon"
                                                            className="h-6 w-6"
                                                            onClick={() => copyToClipboard(article.资源属性!.解压密码, 'pwd')}
                                                        >
                                                            {copiedField === 'pwd' ? <Check className="w-3 h-3 text-green-600" /> : <Copy className="w-3 h-3" />}
                                                        </Button>
                                                    </div>
                                                )}

                                                {article.资源属性.隐藏内容 && (
                                                    <div className="bg-amber-50 p-3 rounded text-sm border border-amber-100 text-amber-800">
                                                        <div className="font-medium mb-1 flex items-center gap-1">
                                                            <Lock className="w-3 h-3" /> 付费内容
                                                        </div>
                                                        <div className="whitespace-pre-wrap text-xs opacity-90">{article.资源属性.隐藏内容}</div>
                                                    </div>
                                                )}
                                            </div>
                                        )}
                                    </div>
                                ) : (
                                    <div className="space-y-4">
                                        <Button
                                            className="w-full bg-linear-to-r from-primary to-purple-600 hover:from-primary/90 hover:to-purple-600/90 text-white shadow-lg shadow-primary/20"
                                            onClick={handlePurchase}
                                            disabled={purchasing}
                                        >
                                            {purchasing ? (
                                                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                                            ) : (
                                                <ShoppingCart className="w-4 h-4 mr-2" />
                                            )}
                                            立即购买
                                        </Button>

                                        {article.支付方式 === 'membership_free' ? (
                                            <div className="text-center">
                                                <Link href="/membership" className="text-xs text-primary font-medium hover:underline flex items-center justify-center gap-1">
                                                    <Crown className="w-3 h-3 text-yellow-500" />
                                                    会员免费下载 (点击开通)
                                                </Link>
                                            </div>
                                        ) : (
                                            <div className="text-center">
                                                <Link href="/membership" className="text-xs text-muted-foreground hover:text-primary flex items-center justify-center gap-1">
                                                    <Crown className="w-3 h-3 text-yellow-500" />
                                                    开通会员享受折扣
                                                </Link>
                                            </div>
                                        )}
                                    </div>
                                )}

                                <div className="pt-4 border-t border-border grid grid-cols-2 gap-4 text-center text-sm text-muted-foreground">
                                    <div>
                                        <div className="text-foreground font-medium">{article.统计数据?.阅读数 || 0}</div>
                                        <div className="text-xs mt-1">浏览次数</div>
                                    </div>
                                    <div>
                                        <div className="text-foreground font-medium">{article.统计数据?.销量 || 0}</div>
                                        <div className="text-xs mt-1">最近售出</div>
                                    </div>
                                </div>
                            </CardContent>
                        </Card>

                        {/* Recent Posts Card */}
                        <Card>
                            <CardHeader className="pb-3">
                                <CardTitle className="text-base flex items-center gap-2">
                                    <FileText className="w-4 h-4 text-primary" />
                                    近期推荐
                                </CardTitle>
                            </CardHeader>
                            <CardContent className="px-0 pb-2">
                                <div className="flex flex-col">
                                    {recentArticles.length > 0 ? (
                                        recentArticles.map((item, _index) => (
                                            <Link
                                                key={item._id}
                                                href={`/article/${item._id}`}
                                                className="group flex items-start gap-3 px-6 py-3 hover:bg-accent transition-colors border-b border-border/50 last:border-0"
                                            >
                                                <div className="relative w-16 h-12 shrink-0 rounded overflow-hidden bg-muted">
                                                    {item.封面图 ? (
                                                        <Image
                                                            src={item.封面图}
                                                            alt={item.文章标题}
                                                            fill
                                                            className="object-cover group-hover:scale-105 transition-transform duration-300"
                                                            sizes="64px"
                                                        />
                                                    ) : (
                                                        <div className="w-full h-full flex items-center justify-center text-muted-foreground">
                                                            <FileText className="w-6 h-6" />
                                                        </div>
                                                    )}
                                                </div>
                                                <div className="flex-1 min-w-0">
                                                    <h4 className="text-sm font-medium text-foreground line-clamp-2 group-hover:text-primary transition-colors">
                                                        {item.文章标题}
                                                    </h4>
                                                    <div className="flex items-center gap-2 mt-1 text-xs text-muted-foreground">
                                                        <span>{format(new Date(item.createdAt), 'MM-dd')}</span>
                                                    </div>
                                                </div>
                                            </Link>
                                        ))
                                    ) : (
                                        <div className="px-6 py-4 text-sm text-muted-foreground text-center">
                                            暂无推荐
                                        </div>
                                    )}
                                </div>
                            </CardContent>
                        </Card>
                    </div>
                </div>
            </div>
        </MainLayout>
    );
}
