# All files / src/components/admin GlobalSearch.tsx

0% Statements 0/105
0% Branches 0/59
0% Functions 0/25
0% Lines 0/101

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280

     'use client';

    import React, { useState, useCallback, useEffect, useRef } from 'react';
    import { useRouter } from 'next/navigation';
    import { Search, X, Users, Film, Package, Loader2 } from 'lucide-react';
    import { Input } from '@/components/ui/input';
    import { cn } from '@/lib/utils';
    import { useTranslation } from 'react-i18next';
    import { apiService } from '@/services/api';

    interface SearchResult {
      type: 'user' | 'reseller' | 'content' | 'music';
      id: number | string;
      title: string;
      subtitle?: string;
      icon: React.ReactNode;
      href: string;
    }

    export function GlobalSearch() {
      const [isOpen, setIsOpen] = useState(false);
      const [query, setQuery] = useState('');
      const [results, setResults] = useState<SearchResult[]>([]);
      const [isLoading, setIsLoading] = useState(false);
      const [selectedIndex, setSelectedIndex] = useState(0);
      const latestRequestIdRef = useRef(0);
      const router = useRouter();
      const { t } = useTranslation();
      const getResultTypeLabel = (type: SearchResult['type']) =>
        t(`admin.search.types.${type}`);

      // Search function
      const performSearch = useCallback(async (searchQuery: string, requestId: number) => {
        if (!searchQuery.trim()) {
          if (requestId === latestRequestIdRef.current) {
            setResults([]);
            setIsLoading(false);
          }
          return;
        }

        setIsLoading(true);

        try {
          // Search in parallel
          const [usersRes, resellersRes, contentRes] = await Promise.allSettled([
            apiService.get(`/api/admin/users?search=${encodeURIComponent(searchQuery)}&limit=5`),
            apiService.get(`/api/admin/resellers?search=${encodeURIComponent(searchQuery)}&limit=5`),
            apiService.get(`/api/admin/content?search=${encodeURIComponent(searchQuery)}&limit=5`),
          ]);

          const searchResults: SearchResult[] = [];

          // Process users
          if (usersRes.status === 'fulfilled' && usersRes.value.success) {
            const data = usersRes.value.data as { users?: any[] };
            const users = data.users || [];
            users.forEach((user: any) => {
              searchResults.push({
                type: 'user',
                id: user.id,
                title: user.username,
                subtitle: user.email,
                icon: <Users className="h-4 w-4 text-blue-500" />,
                href: `/admin?tab=users&userId=${user.id}`
              });
            });
          }

          // Process resellers
          if (resellersRes.status === 'fulfilled' && resellersRes.value.success) {
            const data = resellersRes.value.data as { resellers?: any[] };
            const resellers = data.resellers || [];
            resellers.forEach((reseller: any) => {
              searchResults.push({
                type: 'reseller',
                id: reseller.id,
                title: reseller.username,
                subtitle: reseller.email,
                icon: <Package className="h-4 w-4 text-purple-500" />,
                href: `/admin?tab=resellers&resellerId=${reseller.id}`
              });
            });
          }

          // Process content
          if (contentRes.status === 'fulfilled' && contentRes.value.success) {
            const data = contentRes.value.data as { content?: any[] };
            const content = data.content || [];
            content.forEach((item: any) => {
              searchResults.push({
                type: 'content',
                id: item.id,
                title: item.title,
                subtitle: item.category,
                icon: <Film className="h-4 w-4 text-green-500" />,
                href: `/admin?tab=content&contentId=${item.id}`
              });
            });
          }

          if (requestId === latestRequestIdRef.current) {
            setResults(searchResults);
            setSelectedIndex(0);
          }
        } catch (error) {
          console.error('Search error:', error);
          if (requestId === latestRequestIdRef.current) {
            setResults([]);
          }
        } finally {
          if (requestId === latestRequestIdRef.current) {
            setIsLoading(false);
          }
        }
      }, []);

      // Handle input change
      const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const value = e.target.value;
        setQuery(value);
      };

      useEffect(() => {
        const requestId = latestRequestIdRef.current + 1;
        latestRequestIdRef.current = requestId;

        const timeoutId = setTimeout(() => {
          performSearch(query, requestId);
        }, 300);

        return () => {
          clearTimeout(timeoutId);
        };
      }, [performSearch, query]);

      // Handle keyboard navigation
      const handleKeyDown = (e: React.KeyboardEvent) => {
        if (e.key === 'Escape') {
          setIsOpen(false);
          setQuery('');
          setResults([]);
        } else if (e.key === 'ArrowDown') {
          e.preventDefault();
          setSelectedIndex((prev) => Math.min(prev + 1, results.length - 1));
        } else if (e.key === 'ArrowUp') {
          e.preventDefault();
          setSelectedIndex((prev) => Math.max(prev - 1, 0));
        } else if (e.key === 'Enter' && results[selectedIndex]) {
          e.preventDefault();
          handleResultClick(results[selectedIndex]);
        }
      };

      // Handle result click
      const handleResultClick = (result: SearchResult) => {
        router.push(result.href);
        setIsOpen(false);
        setQuery('');
        setResults([]);
      };

      // Handle click outside
      useEffect(() => {
        const handleClickOutside = (e: MouseEvent) => {
          const target = e.target as HTMLElement;
          if (!target.closest('[data-global-search]')) {
            setIsOpen(false);
          }
        };

        if (isOpen) {
          document.addEventListener('mousedown', handleClickOutside);
          return () => document.removeEventListener('mousedown', handleClickOutside);
        }
      }, [isOpen]);

      // Keyboard shortcut (Ctrl+K or Cmd+K)
      useEffect(() => {
        const handleKeyDown = (e: KeyboardEvent) => {
          if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
            e.preventDefault();
            setIsOpen(true);
          }
        };

        document.addEventListener('keydown', handleKeyDown);
        return () => document.removeEventListener('keydown', handleKeyDown);
      }, []);

      return (
        <div className="relative" data-global-search>
          {/* Search Input */}
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-slate-400 dark:text-slate-400" />
            <Input
              type="text"
              placeholder={t('admin.search.placeholder')}
              value={query}
              onChange={handleInputChange}
              onFocus={() => setIsOpen(true)}
              onKeyDown={handleKeyDown}
              className="pl-10 pr-10 bg-white dark:bg-slate-800/50 border-slate-300 dark:border-slate-600/50 text-slate-900 dark:text-white placeholder:text-slate-500 dark:placeholder:text-slate-400 w-80 focus-ring"
              aria-label={t('common.search')}
            />
            {query && (
              <button
                onClick={() => {
                  setQuery('');
                  setResults([]);
                }}
                className="absolute right-3 top-1/2 transform -translate-y-1/2 text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-white transition-colors"
                aria-label={t('common.close')}
              >
                <X className="h-4 w-4" />
              </button>
            )}
            {isLoading && (
              <div className="absolute right-3 top-1/2 transform -translate-y-1/2">
                <Loader2 className="h-4 w-4 animate-spin text-blue-500" />
              </div>
            )}
          </div>

          {/* Search Results Dropdown */}
          {isOpen && (query || results.length > 0) && (
            <div className="absolute top-full left-0 right-0 mt-2 bg-slate-900/95 backdrop-blur-md border border-slate-700/50 rounded-lg shadow-xl z-50 max-h-[400px] overflow-y-auto">
              {results.length === 0 && !isLoading && query && (
                <div className="p-4 text-center text-slate-400">
                  {t('admin.search.noResults')}
                </div>
              )}

              {results.length > 0 && (
                <div className="py-2">
                  {results.map((result, index) => (
                    <button
                      key={`${result.type}-${result.id}`}
                      onClick={() => handleResultClick(result)}
                      className={cn(
                        'w-full px-4 py-3 flex items-center gap-3 hover:bg-slate-800/50 transition-colors text-left',
                        index === selectedIndex && 'bg-slate-800/50'
                      )}
                      onMouseEnter={() => setSelectedIndex(index)}
                    >
                      <div className="flex-shrink-0">{result.icon}</div>
                      <div className="flex-1 min-w-0">
                        <div className="font-medium text-white truncate">{result.title}</div>
                        {result.subtitle && (
                          <div className="text-sm text-slate-400 truncate">{result.subtitle}</div>
                        )}
                      </div>
                      <div className="flex-shrink-0 text-xs text-slate-500 uppercase">
                        {getResultTypeLabel(result.type)}
                      </div>
                    </button>
                  ))}
                </div>
              )}

              {/* Keyboard hints */}
              <div className="border-t border-slate-700/50 px-4 py-2 flex items-center justify-between text-xs text-slate-500">
                <div className="flex items-center gap-4">
                  <span>
                    <kbd className="px-1.5 py-0.5 bg-slate-800 rounded border border-slate-700">↑↓</kbd> {t('admin.search.shortcuts.navigate')}
                  </span>
                  <span>
                    <kbd className="px-1.5 py-0.5 bg-slate-800 rounded border border-slate-700">{t('admin.search.shortcuts.enterKey')}</kbd> {t('common.select')}
                  </span>
                  <span>
                    <kbd className="px-1.5 py-0.5 bg-slate-800 rounded border border-slate-700">{t('admin.search.shortcuts.escapeKey')}</kbd> {t('common.close')}
                  </span>
                </div>
              </div>
            </div>
          )}
        </div>
      );
    }