'use client';

import { useEffect, useState, useMemo } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import { Skeleton } from '@/components/ui/skeleton';
import { marked } from 'marked';
import { API_BASE } from '@/lib/config';

interface Content {
  id: number; title: string; summary?: string; content?: string; cover?: string;
  link?: string; contentType: string; tags?: string; authorName?: string;
  viewCount: number; isAiGenerated: boolean; publishedAt: string; createdAt: string;
  category?: { id?: number; name: string };
}

// Calculate estimated reading time
function readingTime(text: string): string {
  const words = text.replace(/<[^>]+>/g, '').replace(/\s+/g, ' ').trim().split(/\s+/).length;
  const minutes = Math.max(1, Math.ceil(words / 200));
  return `${minutes} 分钟`;
}

// Truncate text for preview
function truncate(text: string, max = 150): string {
  return text.length > max ? text.substring(0, max) + '...' : text;
}

export default function ContentDetailClient() {
  const params = useParams();
  const [content, setContent] = useState<Content | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [related, setRelated] = useState<Content[]>([]);

  useEffect(() => {
    if (!params.id) return;
    setLoading(true);
    setError('');
    Promise.all([
      fetch(`${API_BASE}/contents/${params.id}`).then(r => {
        if (!r.ok) throw new Error('内容不存在');
        return r.json();
      }),
      // Fetch related articles from same category
      fetch(`${API_BASE}/contents?pageSize=5`).then(r => r.json()).then(d => d.items || []).catch(() => []),
    ]).then(([data, items]: [Content, Content[]]) => {
      if (!data || !data.id) throw new Error('内容不存在');
      setContent(data);
      // Filter related: same category, exclude current, exclude AI-generated duplicates
      const currentCat = data.category?.id;
      const currentId = data.id;
      const filtered = items
        .filter((i: Content) => i.id !== currentId)
        .filter((i: Content) => !currentCat || (i.category?.id === currentCat))
        .slice(0, 3);
      setRelated(filtered);
    })
    .catch(e => setError(e.message))
    .finally(() => setLoading(false));
  }, [params.id]);

  // Render markdown content with enhanced styling
  const [renderedHtml, setRenderedHtml] = useState<string | null>(null);

  useEffect(() => {
    if (!content?.content) {
      setRenderedHtml(null);
      return;
    }
    const result = marked(content.content, { breaks: true, gfm: true });
    if (typeof result === 'string') {
      setRenderedHtml(result);
    } else {
      result.then(html => setRenderedHtml(html)).catch(() => setRenderedHtml(null));
    }
  }, [content?.content]);

  const readingTimeText = useMemo(() => {
    if (!content?.content) return '';
    return readingTime(content.content);
  }, [content?.content]);

  if (loading) return (
    <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div className="mb-6">
        <Skeleton className="h-4 w-24 mb-4" />
        <Skeleton className="h-10 w-3/4 mb-3" />
        <Skeleton className="h-5 w-1/2 mb-2" />
        <Skeleton className="h-4 w-1/3" />
      </div>
      <Skeleton className="h-64 w-full mb-6" />
      <Skeleton className="h-4 w-full mb-2" />
      <Skeleton className="h-4 w-3/4 mb-2" />
      <Skeleton className="h-4 w-full mb-2" />
      <Skeleton className="h-4 w-1/2" />
    </div>
  );

  if (error || !content) return (
    <div className="max-w-3xl mx-auto px-4 py-20 text-center">
      <div className="w-16 h-16 bg-red-100 dark:bg-red-900/30 rounded-2xl flex items-center justify-center mx-auto mb-4">
        <svg className="w-8 h-8 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.34 16.5c-.77.833.192 2.5 1.732 2.5z" />
        </svg>
      </div>
      <h1 className="text-xl font-bold text-foreground mb-2">{error || '内容不存在'}</h1>
      <Link href="/contents" className="text-brand-600 hover:underline text-sm">返回文章列表</Link>
    </div>
  );

  return (
    <article className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      {/* Header */}
      <header className="mb-8">
        {/* Breadcrumb */}
        <div className="flex items-center gap-2 text-sm text-muted-foreground mb-4">
          <Link href="/contents" className="hover:text-brand-600 transition-colors">文章</Link>
          <span>›</span>
          {content.category && <span>{content.category.name}</span>}
        </div>

        {/* Category badge + meta */}
        <div className="flex items-center gap-2 mb-3 flex-wrap">
          {content.category && (
            <span className="bg-brand-600 text-white text-xs font-medium px-2.5 py-0.5 rounded-full">{content.category.name}</span>
          )}
          <span className="text-xs text-muted-foreground">{content.contentType === 'tutorial' ? '教程' : content.contentType === 'news' ? '资讯' : '文章'}</span>
          <span className="text-xs text-muted-foreground">·</span>
          <span className="text-xs text-muted-foreground">
            {content.publishedAt ? new Date(content.publishedAt).toLocaleDateString('zh-CN') : new Date(content.createdAt).toLocaleDateString('zh-CN')}
          </span>
          <span className="text-xs text-muted-foreground">·</span>
          <span className="text-xs text-muted-foreground">{readingTimeText}</span>
          {content.isAiGenerated && (
            <>
              <span className="text-xs text-muted-foreground">·</span>
              <span className="text-xs text-yellow-600 dark:text-yellow-400 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-700 px-2 py-0.5 rounded-full">AI 生成</span>
            </>
          )}
        </div>

        {/* Title */}
        <h1 className="text-2xl sm:text-3xl lg:text-4xl font-bold text-foreground leading-tight mb-4">
          {content.title}
        </h1>

        {/* Meta row */}
        <div className="flex items-center gap-4 text-sm text-muted-foreground border-t border-border pt-4">
          {content.authorName && <span>作者：{content.authorName}</span>}
          <span className="flex items-center gap-1">
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
            </svg>
            {content.viewCount} 次阅读
          </span>
          {content.tags && (
            <div className="flex items-center gap-2 ml-auto flex-wrap">
              {content.tags.split(',').map(tag => (
                <span key={tag} className="text-xs text-muted-foreground bg-muted/50 px-2 py-0.5 rounded">{tag.trim()}</span>
              ))}
            </div>
          )}
        </div>

        {/* Summary */}
        {content.summary && (
          <div className="mt-4 p-4 bg-muted/30 dark:bg-muted/20 rounded-xl border border-border">
            <p className="text-foreground leading-relaxed">
              <span className="text-brand-600 font-medium mr-2">摘要</span>
              {content.summary}
            </p>
          </div>
        )}
      </header>

      {/* Source card - show if there's a link */}
      {content.link && (
        <div className="mb-8 p-4 bg-gradient-to-r from-brand-50 to-blue-50 dark:from-brand-950/30 dark:to-blue-950/20 rounded-xl border border-brand-100 dark:border-brand-800">
          <div className="flex items-start gap-3">
            <div className="flex-shrink-0 w-10 h-10 rounded-lg bg-brand-100 dark:bg-brand-900 flex items-center justify-center">
              <svg className="w-5 h-5 text-brand-600 dark:text-brand-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
              </svg>
            </div>
            <div className="flex-1 min-w-0">
              <div className="flex items-center justify-between gap-2 mb-1">
                <span className="text-sm font-medium text-foreground">📰 来源</span>
                <a
                  href={content.link}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-sm text-brand-600 dark:text-brand-400 hover:underline font-medium flex items-center gap-1 flex-shrink-0"
                >
                  阅读全文
                  <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6v6M16 4l4 4" />
                  </svg>
                </a>
              </div>
              <p className="text-sm text-muted-foreground break-all">{content.link}</p>
            </div>
          </div>
        </div>
      )}

      {/* Article body - rendered markdown */}
      {renderedHtml ? (
          <div className="article-body text-foreground leading-relaxed" dangerouslySetInnerHTML={{ __html: renderedHtml }} />
        ) : (
        <p className="text-muted-foreground italic py-8 text-center">暂无内容</p>
      )}

      {/* Footer */}
      <footer className="mt-12 pt-8 border-t border-border">
        {/* Tags */}
        {content.tags && (
          <div className="flex items-center gap-2 mb-6 flex-wrap">
            <span className="text-sm font-medium text-muted-foreground">标签：</span>
            {content.tags.split(',').map(tag => (
              <span key={tag} className="text-xs text-muted-foreground bg-muted/50 hover:bg-muted transition-colors px-2.5 py-1 rounded-full cursor-default">
                {tag.trim()}
              </span>
            ))}
          </div>
        )}

        {/* Disclaimer */}
        <div className="text-xs text-muted-foreground bg-muted/20 rounded-lg p-3">
          📝 本文由宇之然AI 每日采集发布，内容整理自原文，仅供参考，版权归原文作者所有。
        </div>

        {/* Related articles */}
        {related.length > 0 && (
          <div className="mt-8">
            <h2 className="text-lg font-semibold text-foreground mb-4 flex items-center gap-2">
              <svg className="w-5 h-5 text-brand-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
              </svg>
              相关文章
            </h2>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
              {related.map((item) => (
                <Link key={item.id} href={`/contents/${item.id}`} className="block group">
                  <div className="p-3 rounded-lg border border-border hover:border-brand-200 hover:shadow-sm transition-all">
                    <h3 className="text-sm font-medium text-foreground group-hover:text-brand-600 transition-colors line-clamp-2">
                      {item.title}
                    </h3>
                    {item.summary && (
                      <p className="text-xs text-muted-foreground mt-1 line-clamp-2">{truncate(item.summary, 80)}</p>
                    )}
                    {item.publishedAt && (
                      <span className="text-xs text-muted-foreground mt-2 block">
                        {new Date(item.publishedAt).toLocaleDateString('zh-CN')}
                      </span>
                    )}
                  </div>
                </Link>
              ))}
            </div>
          </div>
        )}

        {/* Back button */}
        <div className="mt-6 flex gap-3">
          <Link href="/contents" className="inline-flex items-center gap-1 text-sm text-brand-600 hover:text-brand-700 font-medium transition-colors">
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
            </svg>
            返回文章列表
          </Link>
        </div>
      </footer>
    </article>
  );
}