# All files / src/app/user/history page.tsx

0% Statements 0/62
0% Branches 0/33
0% Functions 0/15
0% Lines 0/55

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

     'use client';

    import React, { useState, useMemo } from 'react';
    import { useTranslation } from 'react-i18next';
    import { useQuery } from '@tanstack/react-query';
    import { History, Film, Tv, Play, ChevronLeft, ChevronRight, Trash2, Calendar } from 'lucide-react';
    import { Button } from '@/components/ui/button';
    import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
    import ModernUserSidebar from '@/components/user/ModernUserSidebar';
    import { UserRoute } from '@/components/auth/ProtectedRoute';
    import { userHistoryService } from '@/services/userHistory';
    import Link from 'next/link';
    import { toast } from 'sonner';
    import { GridSkeleton, ContentCardSkeleton } from '@/components/ui/skeleton-loader';
    import { getGridLayout } from '@/lib/grid-layouts';
    import { formatRelativeTime } from '@/lib/date-format';
    import { WatchHistoryItem } from '@/types/userHistory';

    export default function HistoryPage() {
      const { t } = useTranslation();
      const [currentPage, setCurrentPage] = useState(1);
      const [categoryFilter, setCategoryFilter] = useState<string>('all');
      const itemsPerPage = 24;

      // Load watch history
      const { data: historyData, isLoading, refetch } = useQuery({
        queryKey: ['user-watch-history', currentPage],
        queryFn: async () => {
          const result = await userHistoryService.getWatchHistory({
            page: currentPage,
            limit: itemsPerPage
          });
          if (result.success) {
            return result.data;
          }
          return { history: [], total: 0, page: 1, limit: itemsPerPage, total_pages: 0 };
        }});

      // Filter by category
      const filteredHistory = useMemo(() => {
        if (!historyData?.history) return [];
        if (categoryFilter === 'all') return historyData.history;
        return historyData.history.filter(item => item.content_type === categoryFilter);
      }, [historyData, categoryFilter]);

      // Get unique categories
      const categories = useMemo(() => {
        if (!historyData?.history) return [];
        const types = new Set(historyData.history.map(item => item.content_type));
        return Array.from(types);
      }, [historyData]);

      // Clear history
      const handleClearHistory = async () => {
        if (!confirm(t('history.confirmClear'))) {
          return;
        }

        try {
          const result = await userHistoryService.clearWatchHistory();
          if (result.success) {
            toast.success(t('history.cleared'));
            refetch();
          } else {
            toast.error(t('history.clearFailed'));
          }
        } catch (error) {
          console.error('Error clearing history:', error);
          toast.error(t('history.error'));
        }
      };

      // Get icon for content type
      const getContentIcon = (type: string) => {
        switch (type.toLowerCase()) {
          case 'movie':
            return <Film className="h-4 w-4" />;
          case 'series':
          case 'episode':
            return <Tv className="h-4 w-4" />;
          case 'live':
            return <Play className="h-4 w-4" />;
          default:
            return <Film className="h-4 w-4" />;
        }
      };

      // Get category label
      const getCategoryLabel = (type: string) => {
        switch (type.toLowerCase()) {
          case 'movie':
            return t('history.categories.movie');
          case 'series':
          case 'episode':
            return t('history.categories.series');
          case 'live':
            return t('history.categories.live');
          default:
            return type;
        }
      };

      return (
        <UserRoute>
          <div className="flex h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900">
            <ModernUserSidebar />

            <main className="flex-1 overflow-y-auto">
              <div className="container mx-auto px-6 py-8">
                {/* Header */}
                <div className="mb-8">
                  <div className="flex items-center gap-3 mb-2">
                    <History className="h-8 w-8 text-blue-500" />
                    <h1 className="text-4xl font-bold text-white">
                      {t('history.title')}
                    </h1>
                  </div>
                  <p className="text-slate-400">
                    {t('history.description')}
                  </p>
                </div>

                {/* Filters and Actions */}
                <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-4 mb-6">
                  <div className="flex items-center gap-4">
                    {/* Category Filter */}
                    <Select value={categoryFilter} onValueChange={setCategoryFilter}>
                      <SelectTrigger className="w-[200px] bg-slate-800/50 border-slate-700/50">
                        <SelectValue placeholder={t('history.filterByCategory')} />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="all">{t('history.allCategories')}</SelectItem>
                        {categories.map(cat => (
                          <SelectItem key={cat} value={cat}>
                            {getCategoryLabel(cat)}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>

                    {/* Stats */}
                    <div className="text-sm text-slate-400">
                      {filteredHistory.length} {t('history.items')}
                    </div>
                  </div>

                  {/* Clear History Button */}
                  <Button
                    onClick={handleClearHistory}
                    variant="outline"
                    className="border-red-600/50 text-red-400 hover:bg-red-600/20 hover:text-red-300"
                  >
                    <Trash2 className="h-4 w-4 mr-2" />
                    {t('history.clearHistory')}
                  </Button>
                </div>

                {/* History Grid */}
                {isLoading ? (
                  <GridSkeleton items={24} CardComponent={ContentCardSkeleton} />
                ) : filteredHistory.length === 0 ? (
                  <div className="text-center py-20">
                    <History className="h-16 w-16 text-slate-600 mx-auto mb-4" />
                    <h3 className="text-xl font-semibold text-white mb-2">
                      {t('history.noHistory')}
                    </h3>
                    <p className="text-slate-400 mb-6">
                      {t('history.noHistoryDescription')}
                    </p>
                    <Link href="/user">
                      <Button className="bg-blue-600 hover:bg-blue-700">
                        <Play className="h-4 w-4 mr-2" />
                        {t('history.browseContent')}
                      </Button>
                    </Link>
                  </div>
                ) : (
                  <>
                    <div className={getGridLayout('content')}>
                      {filteredHistory.map((item: WatchHistoryItem) => (
                        <Link
                          key={item.id}
                          href={item.content_id ? `/user/content/${item.content_id}/watch` : '#'}
                          className="group relative bg-slate-800/30 rounded-lg overflow-hidden hover:bg-slate-700/50 transition-all duration-200 hover:scale-105"
                        >
                          {/* Placeholder Image */}
                          <div className="aspect-[2/3] bg-gradient-to-br from-blue-600/20 to-purple-600/20 flex items-center justify-center relative">
                            {getContentIcon(item.content_type)}
                            <div className="absolute inset-0 bg-black/0 group-hover:bg-black/40 transition-all duration-200 flex items-center justify-center">
                              <Play className="h-12 w-12 text-white opacity-0 group-hover:opacity-100 transition-opacity" />
                            </div>
                          </div>

                          {/* Content Info */}
                          <div className="p-3 space-y-2">
                            <h3 className="font-medium text-white truncate text-sm">
                              {item.content_title}
                            </h3>

                            {item.episode_title && (
                              <p className="text-xs text-slate-400 truncate">
                                {item.series_title && `${item.series_title} - `}
                                {item.season_number && `T${item.season_number}`}
                                {item.episode_number && `E${item.episode_number}`}
                                {item.episode_title && `: ${item.episode_title}`}
                              </p>
                            )}

                            <div className="flex items-center justify-between">
                              <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-blue-600/20 text-blue-400 text-xs">
                                {getContentIcon(item.content_type)}
                                {getCategoryLabel(item.content_type)}
                              </span>

                              <div className="flex items-center gap-1 text-xs text-slate-500">
                                <Calendar className="h-3 w-3" />
                                {formatRelativeTime(item.start_timestamp)}
                              </div>
                            </div>
                          </div>
                        </Link>
                      ))}
                    </div>

                    {/* Pagination */}
                    {historyData && historyData.total_pages > 1 && (
                      <div className="flex items-center justify-between mt-8">
                        <div className="text-sm text-slate-400">
                          {t('history.page')} {currentPage} {t('history.of')} {historyData.total_pages}
                        </div>

                        <div className="flex items-center gap-2">
                          <Button
                            onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                            disabled={currentPage === 1}
                            variant="outline"
                            size="sm"
                            className="border-slate-700/50"
                          >
                            <ChevronLeft className="h-4 w-4 mr-1" />
                            {t('common.previous')}
                          </Button>

                          <Button
                            onClick={() => setCurrentPage(p => Math.min(historyData.total_pages, p + 1))}
                            disabled={currentPage === historyData.total_pages}
                            variant="outline"
                            size="sm"
                            className="border-slate-700/50"
                          >
                            {t('common.next')}
                            <ChevronRight className="h-4 w-4 ml-1" />
                          </Button>
                        </div>
                      </div>
                    )}
                  </>
                )}
              </div>
            </main>
          </div>
        </UserRoute>
      );
    }