'use client';

import { Skeleton } from '@/components/ui/skeleton';
import { useEffect, useState } from 'react';
import Link from 'next/link';
import { apiFetch } from '../../../lib/auth';
import { toast } from 'sonner';

interface HotItem {
  id: number;
  title: string;
  viewCount?: number;
  likeCount?: number;
  _type: 'course' | 'prompt' | 'post';
}

export default function HotPage() {
  const [items, setItems] = useState<HotItem[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadHot();
  }, []);

  async function loadHot() {
    try {
      const [coursesRes, promptsRes, postsRes] = await Promise.all([
        apiFetch('/courses?pageSize=10'),
        apiFetch('/prompts?pageSize=10'),
        apiFetch('/community/posts?pageSize=10'),
      ]);

      const coursesData = await coursesRes.json();
      const promptsData = await promptsRes.json();
      const postsData = await postsRes.json();

      const items: HotItem[] = [
        ...(coursesData.items || []).map((c: any) => ({ ...c, _type: 'course' as const })),
        ...(promptsData.items || []).map((p: any) => ({ ...p, _type: 'prompt' as const })),
        ...(postsData.items || []).map((p: any) => ({ ...p, _type: 'post' as const })),
      ].sort((a, b) => {
        const aScore = (a.viewCount || 0) + (a.likeCount || 0) * 2;
        const bScore = (b.viewCount || 0) + (b.likeCount || 0) * 2;
        return bScore - aScore;
      }).slice(0, 20);

      setItems(items);
    } catch { /* ignore */ }
    setLoading(false);
  }

  if (loading) return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <Skeleton className="h-8 w-48 mb-6" />
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        <Skeleton className="h-32 rounded-xl" />
        <Skeleton className="h-32 rounded-xl" />
        <Skeleton className="h-32 rounded-xl" />
      </div>
    </div>
  );

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <div className="mb-8">
        <Link href="/discover" className="text-sm text-muted-foreground hover:text-brand-600 mb-2 inline-block">
          &larr; 返回发现
        </Link>
        <h1 className="text-3xl font-bold text-foreground">热门榜单</h1>
        <p className="mt-2 text-muted-foreground">最受关注的内容排行</p>
      </div>

      <div className="bg-card rounded-2xl border border-border overflow-hidden">
        {items.map((item, index) => (
          <Link
            key={`${item._type}-${item.id}`}
            href={
              item._type === 'course' ? `/courses/${item.id}` :
              item._type === 'prompt' ? `/prompts/${item.id}` :
              `/community/${item.id}`
            }
            className={`flex items-center gap-4 p-4 hover:bg-muted/50 transition-colors ${
              index !== items.length - 1 ? 'border-b border-border' : ''
            }`}
          >
            <span className={`text-2xl font-bold w-10 text-center ${
              index === 0 ? 'text-yellow-500' :
              index === 1 ? 'text-muted-foreground' :
              index === 2 ? 'text-amber-600' :
              'text-muted-foreground/40'
            }`}>
              {index + 1}
            </span>
            <div className="flex-1">
              <div className="flex items-center gap-2 mb-1">
                <span className={`text-xs px-2 py-0.5 rounded ${
                  item._type === 'course' ? 'bg-blue-100 text-blue-700' :
                  item._type === 'prompt' ? 'bg-purple-100 text-purple-700' :
                  'bg-green-100 text-green-700'
                }`}>
                  {item._type === 'course' ? '课程' : item._type === 'prompt' ? '提示词' : '讨论'}
                </span>
              </div>
              <h3 className="font-medium text-foreground">{item.title}</h3>
            </div>
            <div className="text-xs text-muted-foreground text-right">
              <div>👁 {item.viewCount || 0}</div>
              <div>❤️ {item.likeCount || 0}</div>
            </div>
          </Link>
        ))}
      </div>
    </div>
  );
}
