xonecas.io
556
Bn

bees-nest / files

bees-nest / src / components / search-interface.tsx

4.1 KB
1"use client";
2
3import * as React from "react";
4import { ResultCard, type SearchResult } from "@/components/result-card";
5import { SearchForm } from "@/components/search-form";
6import { cn } from "@/lib/utils";
7
8interface ApiSearchResult {
9  id: number;
10  title: string | null;
11  description: string | null;
12  url: string;
13  image: string | null;
14  siteName: string | null;
15  rank: number;
16}
17
18export function SearchInterface() {
19  const [hasSearched, setHasSearched] = React.useState(false);
20  const [results, setResults] = React.useState<SearchResult[]>([]);
21  const [isSearching, setIsSearching] = React.useState(false);
22  const [error, setError] = React.useState<string | null>(null);
23
24  const getHostnameSafely = (url: string) => {
25    try {
26      return new URL(url).hostname;
27    } catch {
28      return url;
29    }
30  };
31
32  const handleSearch = async (query: string) => {
33    setIsSearching(true);
34    setError(null);
35    setHasSearched(true); // Move to top immediately for better UX
36
37    try {
38      const response = await fetch(
39        `/api/search?q=${encodeURIComponent(query)}`,
40      );
41
42      if (!response.ok) {
43        throw new Error("Failed to fetch search results");
44      }
45
46      const data = await response.json();
47
48      const mappedResults: SearchResult[] = (data.results || []).map(
49        (item: ApiSearchResult) => ({
50          id: item.id.toString(),
51          title: item.title || "Untitled",
52          description: item.description || "No description available",
53          source: item.siteName || getHostnameSafely(item.url),
54          url: item.url,
55          imageUrl: item.image || undefined,
56          date: undefined, // API doesn't return date yet
57        }),
58      );
59
60      setResults(mappedResults);
61    } catch (err) {
62      console.error(err);
63      setError("An error occurred while searching. Please try again.");
64      setResults([]);
65    } finally {
66      setIsSearching(false);
67    }
68  };
69
70  return (
71    <div
72      className={cn(
73        "flex flex-col transition-all duration-500 ease-in-out w-full max-w-4xl mx-auto px-4",
74        hasSearched
75          ? "pt-8 gap-8"
76          : "min-h-[80vh] justify-center items-center gap-6",
77      )}
78    >
79      <div
80        className={cn(
81          "flex flex-col items-center gap-6 w-full transition-all duration-500",
82          hasSearched ? "items-start" : "items-center text-center",
83        )}
84      >
85        <SearchForm
86          onSearch={handleSearch}
87          className={cn(
88            "transition-all duration-500",
89            hasSearched ? "max-w-full" : "max-w-2xl",
90          )}
91        />
92      </div>
93
94      {hasSearched && (
95        <div className="w-full space-y-4 animate-in slide-in-from-bottom-4 duration-500 fade-in">
96          {isSearching ? (
97            <div className="space-y-4">
98              <div className="text-sm text-muted-foreground">Searching...</div>
99              {/* Skeleton Loading */}
100              {[1, 2, 3].map((i) => (
101                <div
102                  key={i}
103                  className="h-32 w-full animate-pulse rounded-2xl bg-muted/40"
104                />
105              ))}
106            </div>
107          ) : error ? (
108            <div className="rounded-xl border border-destructive/20 bg-destructive/10 p-4 text-sm text-destructive">
109              {error}
110            </div>
111          ) : results.length > 0 ? (
112            <>
113              <div className="text-sm text-muted-foreground">
114                Found {results.length} results
115              </div>
116              <div className="grid gap-4">
117                {results.map((result) => (
118                  <ResultCard key={result.id} result={result} />
119                ))}
120              </div>
121            </>
122          ) : (
123            <div className="flex flex-col items-center justify-center gap-2 py-12 text-center text-muted-foreground">
124              <p className="text-lg font-medium text-foreground">
125                No results found
126              </p>
127              <p>
128                We couldn't find anything matching your search. Try different
129                keywords.
130              </p>
131            </div>
132          )}
133        </div>
134      )}
135    </div>
136  );
137}