'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 DailyItem {
  id: number;
  title: string;
  summary?: string;
  cover?: string;
  _type: 'course' | 'prompt' | 'content';
}

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

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

  async function loadDaily() {
    try {
      const [coursesRes, promptsRes, contentsRes] = await Promise.all([
        apiFetch('/courses?pageSize=3'),
        apiFetch('/prompts?pageSize=3'),
        apiFetch('/contents?pageSize=3'),
      ]);

      const coursesData = await coursesRes.json();
      const promptsData = await promptsRes.json();
      const contentsData = await contentsRes.json();

      const items: DailyItem[] = [
        ...(coursesData.items || []).map((c: any) => ({ ...c, _type: 'course' as const })),
        ...(promptsData.items || []).map((p: any) => ({ ...p, _type: 'prompt' as const })),
        ...(contentsData.items || []).map((c: any) => ({ ...c, _type: 'content' as const })),
      ];

      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="space-y-4">
        {items.map((item, index) => (
          <Link
            key={`${item._type}-${item.id}`}
            href={
              item._type === 'course' ? `/courses/${item.id}` :
              item._type === 'prompt' ? `/prompts/${item.id}` :
              `/contents/${item.id}`
            }
            className="bg-card rounded-xl border border-border p-4 hover:shadow-md transition-shadow flex gap-4"
          >
            {item.cover && (
              <img src={item.cover} alt={item.title} className="w-20 h-20 object-cover rounded-lg shrink-0" />
            )}
            <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>
                <span className="text-xs text-muted-foreground">#{index + 1}</span>
              </div>
              <h3 className="font-semibold text-foreground mb-1">{item.title}</h3>
              <p className="text-sm text-muted-foreground line-clamp-2">{item.summary || '暂无描述'}</p>
            </div>
          </Link>
        ))}
      </div>
    </div>
  );
}
