'use client';

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

interface Circle {
  id: number;
  name: string;
  description?: string;
  tags?: string;
  _count: { members: number; posts: number };
  creator?: { id: number; nickname: string };
}

export default function CirclesPage() {
  const t = useT();
  const [circles, setCircles] = useState<Circle[]>([]);
  const [loading, setLoading] = useState(true);

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

  async function loadCircles() {
    try {
      const res = await fetch(`${API_BASE}/circles`);
      if (res.ok) {
        const data = await res.json();
        setCircles(data || []);
      }
    } catch { toast.error("加载圈子失败") }
    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-32 mb-8" />
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {[1,2,3,4].map(i => <Skeleton key={i} 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; {t.circles.back}</Link>
        <h1 className="text-3xl font-bold text-foreground">{t.circles.title}</h1>
        <p className="mt-2 text-muted-foreground">{t.circles.desc}</p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {circles.map(circle => (
          <Link key={circle.id} href={`/circles/${circle.id}`}
            className="bg-card rounded-xl border border-border p-6 hover:shadow-md transition-shadow block">
            <h3 className="font-semibold text-foreground mb-2">{circle.name}</h3>
            <p className="text-sm text-muted-foreground mb-4">{circle.description}</p>
            <div className="flex items-center justify-between">
              <div className="flex gap-2">
                {circle.tags?.split(',').map(tag => (
                  <span key={tag} className="text-xs px-2 py-0.5 bg-muted rounded">{tag.trim()}</span>
                ))}
              </div>
              <span className="text-xs text-muted-foreground">{circle._count?.members || 0} {t.circles.members} · {circle._count?.posts || 0} {t.circles.posts}</span>
            </div>
          </Link>
        ))}
      </div>

      {circles.length === 0 && !loading && (
        <div className="text-center py-20 text-muted-foreground"><p>{t.circles.empty}</p></div>
      )}
    </div>
  );
}
