'use client';

import { useEffect, useState, Suspense } from 'react';
import { useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { Input } from '@/components/ui/input';
import { Card } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { SearchIcon, FileText, BookOpen, Wrench, MessageSquare } from 'lucide-react';
import { API_BASE } from '@/lib/config';
import { useT } from '@/i18n';

interface SearchResult { id: number; _type: 'course' | 'prompt' | 'tool' | 'content'; title?: string; name?: string; description?: string; summary?: string; cover?: string; icon?: string; url?: string; model?: string; isFree?: boolean; publishedAt?: string }

export default function SearchPage() {
  return (
    <Suspense fallback={<div className="flex items-center justify-center min-h-[60vh]"><div className="space-y-4 w-full max-w-2xl px-4"><Skeleton className="h-8 w-48 mx-auto" /><Skeleton className="h-4 w-32 mx-auto" /><Skeleton className="h-64 w-full" /></div></div>}>
      <SearchContent />
    </Suspense>
  );
}

function SearchContent() {
  const t = useT();
  const searchParams = useSearchParams();
  const q = searchParams.get('q') || '';
  const type = searchParams.get('type') || 'all';
  const [results, setResults] = useState<SearchResult[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [input, setInput] = useState(q);

  useEffect(() => {
    if (!q) return;
    setLoading(true);
    fetch(`${API_BASE}/search?q=${encodeURIComponent(q)}&type=${type}`)
      .then(r => r.json()).then(data => { setResults(data.results || []); setTotal(data.total || 0); })
      .catch(() => {}).finally(() => setLoading(false));
  }, [q, type]);

  const groups = { course: results.filter(r => r._type === 'course'), prompt: results.filter(r => r._type === 'prompt'), tool: results.filter(r => r._type === 'tool'), content: results.filter(r => r._type === 'content') };
  const groupLabels: Record<string, string> = { course: t.search.groupCourse, prompt: t.search.groupPrompt, tool: t.search.groupTool, content: t.search.groupContent };
  const groupIcons: Record<string, any> = { course: BookOpen, prompt: MessageSquare, tool: Wrench, content: FileText };
  const groupLinks: Record<string, string> = { course: '/courses/', prompt: '/prompts', tool: '/tools', content: '/contents/' };

  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 mb-4">{t.search.title}</h1>
        <form onSubmit={e => { e.preventDefault(); window.location.href = `/search?q=${encodeURIComponent(input)}`; }}>
          <div className="relative">
            <SearchIcon className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-muted-foreground" />
            <Input type="text" value={input} onChange={e => setInput(e.target.value)} placeholder={t.search.placeholder} className="pl-10 h-12 text-base" />
          </div>
        </form>
      </div>

      {!q && (
        <div className="text-center py-20 text-muted-foreground">
          <SearchIcon className="w-12 h-12 mx-auto mb-4 opacity-30" />
          <p>{t.search.emptyHint}</p>
        </div>
      )}

      {q && loading && (
        <div className="space-y-4">{[1,2,3].map(i => <Skeleton key={i} className="h-24 w-full rounded-xl" />)}</div>
      )}

      {q && !loading && total === 0 && (
        <div className="text-center py-20 text-muted-foreground">
          <p>{t.search.noResults.replace('{q}', q)}</p>
        </div>
      )}

      {q && !loading && total > 0 && (
        <div>
          <p className="text-sm text-muted-foreground mb-6">{t.search.resultsCount.replace('{n}', String(total))}</p>
          <div className="space-y-8">
            {Object.entries(groups).map(([key, items]) => {
              if (items.length === 0) return null;
              const Icon = groupIcons[key];
              return (
                <div key={key}>
                  <div className="flex items-center gap-2 mb-3">
                    <Icon className="w-4 h-4 text-muted-foreground" />
                    <span className="text-sm font-medium">{groupLabels[key]}</span>
                    <span className="text-xs text-muted-foreground">{items.length} {t.search.resultsCount.replace('{n}', '')}</span>
                  </div>
                  <div className="grid gap-3">
                    {items.map((item) => (
                      <Link key={`${key}-${item.id}`} href={`${groupLinks[key]}${key === 'course' || key === 'content' ? item.id : ''}`} className="block">
                        <Card className="p-4 hover:border-brand-200 dark:hover:border-brand-800 transition-colors">
                          <h3 className="font-semibold">{item.title || item.name}</h3>
                          <p className="text-sm text-muted-foreground mt-1 line-clamp-2">{item.description || item.summary}</p>
                          <div className="flex gap-2 mt-2">
                            {key === 'course' && <Badge variant={item.isFree ? 'secondary' : 'destructive'}>{item.isFree ? t.courses.free : t.courses.paid}</Badge>}
                            {key === 'prompt' && item.model && <span className="text-xs text-muted-foreground">模型: {item.model}</span>}
                          </div>
                        </Card>
                      </Link>
                    ))}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}
