'use client';

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

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

export default function DiscoverPage() {
  const t = useT();
  const [hotCourses, setHotCourses] = useState<HotItem[]>([]);
  const [hotPrompts, setHotPrompts] = useState<HotItem[]>([]);
  const [hotPosts, setHotPosts] = useState<HotItem[]>([]);
  const [loading, setLoading] = useState(true);

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

  async function loadData() {
    try {
      const [coursesRes, promptsRes, postsRes] = await Promise.all([
        apiFetch('/courses?pageSize=5'), apiFetch('/prompts?pageSize=5'), apiFetch('/community/posts?pageSize=5'),
      ]);
      setHotCourses((await coursesRes.json()).items?.map((c: any) => ({ ...c, _type: 'course' as const })) || []);
      setHotPrompts((await promptsRes.json()).items?.map((p: any) => ({ ...p, _type: 'prompt' as const })) || []);
      setHotPosts((await postsRes.json()).items?.map((p: any) => ({ ...p, _type: 'post' as const })) || []);
    } 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-24 mb-2" /><Skeleton className="h-5 w-64 mb-8" />
      {[1,2,3].map(i => <Skeleton key={i} className="h-32 rounded-xl mb-4" />)}
    </div>
  );

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-foreground">{t.discover.desc}</h1>
      </div>
      <div className="space-y-8">
        <section>
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-xl font-semibold text-foreground">🔥 {t.discover.hotCourses}</h2>
            <Link href="/courses" className="text-sm text-brand-600 hover:underline">{t.common.viewAll}</Link>
          </div>
          <div className="grid gap-3">
            {hotCourses.map((item, index) => (
              <Link key={item.id} href={`/courses/${item.id}`}
                className="bg-card rounded-xl border border-border p-4 hover:shadow-md transition-shadow flex items-center gap-4">
                <span className="text-2xl font-bold text-muted-foreground/20 w-8">{index + 1}</span>
                <div className="flex-1">
                  <h3 className="font-medium text-foreground">{item.title}</h3>
                  <p className="text-xs text-muted-foreground mt-1">👁 {t.discover.viewCount?.replace('{n}', String(item.viewCount)) || `${item.viewCount} 浏览`}</p>
                </div>
              </Link>
            ))}
          </div>
        </section>

        <section>
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-xl font-semibold text-foreground">✨ {t.discover.hotPrompts}</h2>
            <Link href="/prompts" className="text-sm text-brand-600 hover:underline">{t.common.viewAll}</Link>
          </div>
          <div className="grid gap-3">
            {hotPrompts.map((item, index) => (
              <Link key={item.id} href={`/prompts`}
                className="bg-card rounded-xl border border-border p-4 hover:shadow-md transition-shadow flex items-center gap-4">
                <span className="text-2xl font-bold text-muted-foreground/20 w-8">{index + 1}</span>
                <div className="flex-1">
                  <h3 className="font-medium text-foreground">{item.title}</h3>
                  <p className="text-xs text-muted-foreground mt-1">❤️ {t.discover.likeCount?.replace('{n}', String(item.likeCount)) || `${item.likeCount} 点赞`}</p>
                </div>
              </Link>
            ))}
          </div>
        </section>

        <section>
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-xl font-semibold text-foreground">💬 {t.discover.hotPosts}</h2>
            <Link href="/community" className="text-sm text-brand-600 hover:underline">{t.common.viewAll}</Link>
          </div>
          <div className="grid gap-3">
            {hotPosts.map((item, index) => (
              <Link key={item.id} href={`/community/${item.id}`}
                className="bg-card rounded-xl border border-border p-4 hover:shadow-md transition-shadow flex items-center gap-4">
                <span className="text-2xl font-bold text-muted-foreground/20 w-8">{index + 1}</span>
                <div className="flex-1">
                  <h3 className="font-medium text-foreground">{item.title}</h3>
                  <p className="text-xs text-muted-foreground mt-1">{t.discover.postStats?.replace('{likes}', String(item.likeCount)).replace('{views}', String(item.viewCount)) || `❤️ ${item.likeCount} · 👁 ${item.viewCount}`}</p>
                </div>
              </Link>
            ))}
          </div>
        </section>
      </div>
    </div>
  );
}
