'use client';

import { useEffect, useState } from 'react';
import { Card } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { Wrench, ExternalLink, Star } from 'lucide-react';
import { API_BASE } from '@/lib/config';
import { useT } from '@/i18n';

interface Tool { id: number; name: string; description: string; url: string; icon: string | null; affiliateLink: string | null; isFeatured: boolean; tags: string | null }

function ToolSkeleton() {
  return (
    <Card className="p-5">
      <div className="flex gap-2 mb-2"><Skeleton className="h-5 w-12 rounded-full" /><Skeleton className="h-5 w-12 rounded-full" /></div>
      <Skeleton className="h-5 w-1/2 mb-1" /><Skeleton className="h-4 w-full" />
    </Card>
  );
}

export default function ToolsPage() {
  const t = useT();
  const [tools, setTools] = useState<Tool[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch(`${API_BASE}/tools?categoryId=7`)
      .then(r => r.json()).then(data => setTools(data.items || []))
      .catch(() => {}).finally(() => setLoading(false));
  }, []);

  function parseHighlight(desc: string | null): string {
    if (!desc) return '';
    const match = desc.match(/【推荐理由】\s*(.+?)(?:\n|$)/);
    return match ? match[1].trim() : desc.slice(0, 40) + '...';
  }

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <div className="mb-10">
        <h1 className="text-3xl font-bold text-foreground">{t.tools.title}</h1>
        <p className="mt-2 text-muted-foreground">{t.tools.desc}</p>
      </div>

      {loading ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">{[1,2,3,4,5,6].map(i => <ToolSkeleton key={i} />)}</div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {tools.map((tool) => {
            const highlight = parseHighlight(tool.description);
            return (
            <a key={tool.id} href={tool.url} target="_blank" rel="noopener noreferrer" className="block group">
              <Card className="p-5 hover:shadow-md hover:border-brand-200 dark:hover:border-brand-800 transition-all group">
                <div className="flex items-start gap-3 mb-2">
                  <div className="w-10 h-10 bg-brand-100 dark:bg-brand-900/30 rounded-xl flex items-center justify-center shrink-0 group-hover:scale-110 transition-transform">
                    <Wrench className="w-5 h-5 text-brand-600 dark:text-brand-400" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 flex-wrap">
                      <h3 className="font-semibold group-hover:text-brand-600 transition-colors">{tool.name}</h3>
                      {tool.isFeatured && <Star className="w-3.5 h-3.5 text-amber-500 fill-amber-500" />}
                    </div>
                    <p className="text-sm text-muted-foreground line-clamp-2 mt-0.5">{tool.description?.split('\n\n')[0]}</p>
                  </div>
                  <ExternalLink className="w-4 h-4 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity shrink-0 mt-1" />
                </div>
                {highlight && (
                  <div className="mt-2 px-3 py-1.5 bg-brand-50 dark:bg-brand-950/40 rounded-lg border border-brand-100 dark:border-brand-800">
                    <p className="text-xs text-brand-600 dark:text-brand-400 font-medium">💡 {highlight}</p>
                  </div>
                )}
                <div className="flex gap-2 mt-2">
                  {tool.tags?.split(',').slice(0, 2).map(tag => (
                    <Badge key={tag} variant="secondary">{tag.trim()}</Badge>
                  ))}
                </div>
              </Card>
            </a>
            );
          })}
        </div>
      )}
    </div>
  );
}
