Add Watch Buddies feature

- Created WatchBuddy model
- M:N junctions to EntrySeen/EpisodeSeen
  and Media relation for profile pictures
- Full CRUD + search + profile picture upload
- WatchBuddySelect multi-select with search and inline create, replaced
  all seen_with text inputs
- WatchBuddiesPage (grid) and WatchBuddyProfilePage (edit form,
  icon-based contacts, poster-grid watch history, monthly timeline)
This commit is contained in:
X4Lo committed 2026-06-25 03:11:14 +01:00
1 parent 4313a794ce
commit e82b905886
28 files changed
+6813 -374

No files matched your search

+81 -63
View File
@@ -1,26 +1,26 @@
import { useState, useEffect } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
import { useState, useEffect } from "react";
import { useParams, Link, useNavigate } from "react-router-dom";
import {
useEntry,
useEntrySeasons,
useRefreshEntry,
useEntryCredits,
} from '@/hooks/useEntries';
import { useEntrySeenByEntry, useDeleteEntrySeen } from '@/hooks/useEntrySeen';
import { useCollections } from '@/hooks/useCollections';
import { useLibraryStore } from '@/stores/useLibraryStore';
import { useCommandPaletteStore } from '@/stores/useCommandPaletteStore';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
} from "@/hooks/useEntries";
import { useEntrySeenByEntry, useDeleteEntrySeen } from "@/hooks/useEntrySeen";
import { useCollections } from "@/hooks/useCollections";
import { useLibraryStore } from "@/stores/useLibraryStore";
import { useCommandPaletteStore } from "@/stores/useCommandPaletteStore";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
} from "@/components/ui/dropdown-menu";
import {
Heart,
MoreHorizontal,
@@ -36,31 +36,31 @@ import {
ExternalLink,
Play,
BookmarkCheck,
} from 'lucide-react';
} from "lucide-react";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from '@/components/ui/tooltip';
import { CastList } from '@/components/entries/CastList';
import { SeasonsContainer } from '@/components/entries/SeasonsContainer';
import { StreamingSection } from '@/components/streaming/StreamingSection';
} from "@/components/ui/tooltip";
import { CastList } from "@/components/entries/CastList";
import { SeasonsContainer } from "@/components/entries/SeasonsContainer";
import { StreamingSection } from "@/components/streaming/StreamingSection";
// EpisodeWatchHistory is available for future use
import { EntrySettingsDialog } from '@/components/dialogs/EntrySettingsDialog';
import { EntrySeenDialog } from '@/components/dialogs/EntrySeenDialog';
import { EntryMediaDialog } from '@/components/dialogs/EntryMediaDialog';
import { AddEntryToCollectionDialog } from '@/components/dialogs/AddEntryToCollectionDialog';
import { RatingDialog } from '@/components/dialogs/RatingDialog';
import { MovieWatchHistoryDialog } from '@/components/dialogs/MovieWatchHistoryDialog';
import { ConfirmDialog } from '@/components/dialogs/ConfirmDialog';
import { EntrySettingsDialog } from "@/components/dialogs/EntrySettingsDialog";
import { EntrySeenDialog } from "@/components/dialogs/EntrySeenDialog";
import { EntryMediaDialog } from "@/components/dialogs/EntryMediaDialog";
import { AddEntryToCollectionDialog } from "@/components/dialogs/AddEntryToCollectionDialog";
import { RatingDialog } from "@/components/dialogs/RatingDialog";
import { MovieWatchHistoryDialog } from "@/components/dialogs/MovieWatchHistoryDialog";
import { ConfirmDialog } from "@/components/dialogs/ConfirmDialog";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { EntryDetailsSkeleton } from '@/components/skeletons/PageSkeletons';
} from "@/components/ui/dialog";
import { EntryDetailsSkeleton } from "@/components/skeletons/PageSkeletons";
import {
getPosterUrl,
getBackdropUrl,
@@ -68,38 +68,38 @@ import {
getYear,
formatRuntime,
formatDate,
} from '@/lib/media-utils';
import { useUpdateEntry, useDeleteEntry } from '@/hooks/useEntries';
import type { Collection, Entry } from '@/types';
} from "@/lib/media-utils";
import { useUpdateEntry, useDeleteEntry } from "@/hooks/useEntries";
import type { Collection, Entry, EntrySeen } from "@/types";
const WATCH_STATUSES = [
{
value: 'plan_to_watch',
label: 'Plan to Watch',
value: "plan_to_watch",
label: "Plan to Watch",
color:
'bg-slate-500/15 border-slate-500/30 text-slate-600 dark:text-slate-400',
"bg-slate-500/15 border-slate-500/30 text-slate-600 dark:text-slate-400",
},
{
value: 'watching',
label: 'Watching',
color: 'bg-blue-500/15 border-blue-500/30 text-blue-600 dark:text-blue-400',
value: "watching",
label: "Watching",
color: "bg-blue-500/15 border-blue-500/30 text-blue-600 dark:text-blue-400",
},
{
value: 'completed',
label: 'Completed',
value: "completed",
label: "Completed",
color:
'bg-green-500/15 border-green-500/30 text-green-600 dark:text-green-400',
"bg-green-500/15 border-green-500/30 text-green-600 dark:text-green-400",
},
{
value: 'on_hold',
label: 'On Hold',
value: "on_hold",
label: "On Hold",
color:
'bg-amber-500/15 border-amber-500/30 text-amber-600 dark:text-amber-400',
"bg-amber-500/15 border-amber-500/30 text-amber-600 dark:text-amber-400",
},
{
value: 'dropped',
label: 'Dropped',
color: 'bg-red-500/15 border-red-500/30 text-red-600 dark:text-red-400',
value: "dropped",
label: "Dropped",
color: "bg-red-500/15 border-red-500/30 text-red-600 dark:text-red-400",
},
];
@@ -135,6 +135,7 @@ export function EntryDetailsPage() {
const [showWatchHistoryDialog, setShowWatchHistoryDialog] = useState(false);
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [showStatusDialog, setShowStatusDialog] = useState(false);
const [editSeenRecord, setEditSeenRecord] = useState<EntrySeen | null>(null);
// Track recently viewed for command palette
const addRecentlyViewed = useCommandPaletteStore((s) => s.addRecentlyViewed);
@@ -143,7 +144,7 @@ export function EntryDetailsPage() {
addRecentlyViewed({
id: `lib-${entryId}`,
title: displayEntry.title,
type: displayEntry.is_tvseries ? 'tv' : 'movie',
type: displayEntry.is_tvseries ? "tv" : "movie",
poster_path: displayEntry.poster_path,
libraryId: entryId,
tmdbId: displayEntry.entryIds?.tmdb_id ?? undefined,
@@ -162,7 +163,7 @@ export function EntryDetailsPage() {
const backdrop = getBackdropUrl(e);
const poster = getPosterUrl(e);
const director = credits.find(
(c) => c.cast_type === 'crew' && c.job === 'Director',
(c) => c.cast_type === "crew" && c.job === "Director",
);
const toggleFavorite = () => {
@@ -227,9 +228,9 @@ export function EntryDetailsPage() {
disabled={updateEntry.isPending}
>
<Heart
className={`mr-2 h-4 w-4 ${e.favorit ? 'fill-current' : ''}`}
className={`mr-2 h-4 w-4 ${e.favorit ? "fill-current" : ""}`}
/>
{e.favorit ? 'Unfavorite' : 'Favorite'}
{e.favorit ? "Unfavorite" : "Favorite"}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setShowCollectionDialog(true)}>
<FolderPlus className="mr-2 h-4 w-4" />
@@ -241,7 +242,7 @@ export function EntryDetailsPage() {
}
>
<EyeOff className="mr-2 h-4 w-4" />
{e.hidden ? 'Unhide' : 'Hide'}
{e.hidden ? "Unhide" : "Hide"}
</DropdownMenuItem>
<DropdownMenuSeparator />
{/* Manage */}
@@ -250,9 +251,9 @@ export function EntryDetailsPage() {
disabled={refreshEntry.isPending}
>
<RefreshCw
className={`mr-2 h-4 w-4 ${refreshEntry.isPending ? 'animate-spin' : ''}`}
className={`mr-2 h-4 w-4 ${refreshEntry.isPending ? "animate-spin" : ""}`}
/>
{refreshEntry.isPending ? 'Refreshing...' : 'Refresh details'}
{refreshEntry.isPending ? "Refreshing..." : "Refresh details"}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setShowMediaDialog(true)}>
<ImageIcon className="mr-2 h-4 w-4" />
@@ -291,7 +292,7 @@ export function EntryDetailsPage() {
<div className="flex items-center justify-center gap-3 mt-3">
{e.entryIds.tmdb_id && (
<a
href={`https://www.themoviedb.org/${e.is_tvseries ? 'tv' : 'movie'}/${e.entryIds.tmdb_id}`}
href={`https://www.themoviedb.org/${e.is_tvseries ? "tv" : "movie"}/${e.entryIds.tmdb_id}`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
@@ -322,7 +323,7 @@ export function EntryDetailsPage() {
<h1 className="text-3xl font-bold leading-tight">{e.title}</h1>
{director?.people?.name && (
<p className="text-sm text-muted-foreground">
by{' '}
by{" "}
<Link
to={`/people/${director.people_id}`}
className="font-medium text-foreground hover:underline"
@@ -464,19 +465,19 @@ export function EntryDetailsPage() {
disabled={updateEntry.isPending}
className={`inline-flex items-center gap-1 rounded-full border px-3 py-1 text-sm font-medium transition-colors ${
e.favorit
? 'bg-yellow-500/15 border-yellow-500/30 text-yellow-600 dark:text-yellow-400 hover:bg-yellow-500/25'
: 'border-dashed border-border text-muted-foreground hover:border-yellow-500/40 hover:text-yellow-500'
? "bg-yellow-500/15 border-yellow-500/30 text-yellow-600 dark:text-yellow-400 hover:bg-yellow-500/25"
: "border-dashed border-border text-muted-foreground hover:border-yellow-500/40 hover:text-yellow-500"
}`}
>
<Star
className={`h-3.5 w-3.5 ${e.favorit ? 'fill-yellow-400 text-yellow-400' : ''}`}
className={`h-3.5 w-3.5 ${e.favorit ? "fill-yellow-400 text-yellow-400" : ""}`}
/>
Favorit
</button>
</TooltipTrigger>
<TooltipContent>
<p>
{e.favorit ? 'Remove from favorites' : 'Add to favorites'}
{e.favorit ? "Remove from favorites" : "Add to favorites"}
</p>
</TooltipContent>
</Tooltip>
@@ -490,7 +491,7 @@ export function EntryDetailsPage() {
return (
<button
onClick={() => setShowStatusDialog(true)}
className={`inline-flex items-center gap-1 rounded-full border px-3 py-1 text-sm font-medium transition-colors cursor-pointer ${info?.color ?? ''}`}
className={`inline-flex items-center gap-1 rounded-full border px-3 py-1 text-sm font-medium transition-colors cursor-pointer ${info?.color ?? ""}`}
>
<BookmarkCheck className="h-3.5 w-3.5" />
{info?.label}
@@ -514,7 +515,7 @@ export function EntryDetailsPage() {
<div className="flex flex-wrap items-center justify-center gap-2">
<StreamingSection entry={e} seasons={seasons} />
<a
href={`https://www.youtube.com/results?search_query=${encodeURIComponent(e.title + ' official trailer')}`}
href={`https://www.youtube.com/results?search_query=${encodeURIComponent(e.title + " official trailer")}`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-2 h-11 px-6 text-sm font-medium rounded-md border border-input bg-background hover:bg-accent hover:text-accent-foreground transition-colors"
@@ -607,6 +608,23 @@ export function EntryDetailsPage() {
onDelete={(seenId) =>
deleteEntrySeen.mutate({ id: seenId, entryId: e.id })
}
onEdit={(record) => {
setEditSeenRecord(record);
setShowWatchHistoryDialog(false);
}}
/>
)}
{editSeenRecord && (
<EntrySeenDialog
open={!!editSeenRecord}
onOpenChange={(open) => {
if (!open) setEditSeenRecord(null);
}}
entry={e}
seasons={seasons}
mode="edit"
editRecord={editSeenRecord}
/>
)}
<ConfirmDialog
@@ -618,7 +636,7 @@ export function EntryDetailsPage() {
variant="destructive"
onConfirm={() => {
deleteEntry.mutate(e.id, {
onSuccess: () => navigate('/library'),
onSuccess: () => navigate("/library"),
});
setShowDeleteConfirm(false);
}}
@@ -641,7 +659,7 @@ export function EntryDetailsPage() {
setShowStatusDialog(false);
}}
className={`w-full flex items-center gap-2 rounded-md px-3 py-2 text-sm transition-colors hover:bg-accent ${
e.watch_status === s.value ? 'bg-accent font-medium' : ''
e.watch_status === s.value ? "bg-accent font-medium" : ""
}`}
>
<BookmarkCheck className="h-4 w-4" />
@@ -692,8 +710,8 @@ function EntryCollectionsSection({ entryId }: { entryId: number }) {
</p>
{col.entries && (
<p className="text-xs text-white/70 mt-0.5">
{col.entries.length}{' '}
{col.entries.length === 1 ? 'title' : 'titles'}
{col.entries.length}{" "}
{col.entries.length === 1 ? "title" : "titles"}
</p>
)}
</div>
+30 -30
View File
@@ -1,27 +1,27 @@
import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { settingsApi } from '@/api/settings';
import { maintenanceApi, type OrphanResult } from '@/api/maintenance';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { settingsApi } from "@/api/settings";
import { maintenanceApi, type OrphanResult } from "@/api/maintenance";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import {
Card,
CardContent,
CardHeader,
CardTitle,
CardDescription,
} from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Save, Search, Trash2, Loader2 } from 'lucide-react';
import type { Settings } from '@/types';
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Save, Search, Trash2, Loader2 } from "lucide-react";
import type { Settings } from "@/types";
const settingsSchema = z.object({
tmdbApiKey: z.string().min(1, 'TMDB API key is required'),
tmdbApiKey: z.string().min(1, "TMDB API key is required"),
backPort: z.coerce.number().int().positive(),
authPassword: z.string().optional(),
});
@@ -32,7 +32,7 @@ function formatOrphanResult(result: OrphanResult): string {
if (result.logos) parts.push(`${result.logos} logo(s)`);
if (result.backdrops) parts.push(`${result.backdrops} backdrop(s)`);
if (result.stills) parts.push(`${result.stills} still(s)`);
return parts.length > 0 ? parts.join(', ') : 'None found';
return parts.length > 0 ? parts.join(", ") : "None found";
}
function hasOrphans(result: OrphanResult | null): boolean {
@@ -90,7 +90,7 @@ function MissingDirectorsSection() {
{result && (
<p className="text-xs text-muted-foreground">
{result.count === 0
? 'All entries have directors.'
? "All entries have directors."
: result.fixed > 0
? `Fixed ${result.fixed} of ${result.count} missing directors.`
: `${result.count} entries missing director.`}
@@ -152,7 +152,7 @@ function DuplicateCreditsSection() {
{result && (
<p className="text-xs text-muted-foreground">
{result.duplicates === 0
? 'No duplicate credits found.'
? "No duplicate credits found."
: result.deleted > 0
? `Removed ${result.deleted} duplicates across ${result.groups} groups.`
: `${result.duplicates} duplicates across ${result.groups} groups.`}
@@ -203,7 +203,7 @@ function WatchStatusesSection() {
{fixResult.completed === 0 &&
fixResult.watching === 0 &&
fixResult.planToWatch === 0 &&
'All statuses up to date.'}
"All statuses up to date."}
</p>
)}
</div>
@@ -213,14 +213,14 @@ function WatchStatusesSection() {
export function SettingsPage() {
const queryClient = useQueryClient();
const { data: settings, isLoading } = useQuery({
queryKey: ['settings'],
queryKey: ["settings"],
queryFn: settingsApi.get,
});
const updateSettings = useMutation({
mutationFn: (data: Partial<Settings>) => settingsApi.update(data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['settings'] });
queryClient.invalidateQueries({ queryKey: ["settings"] });
},
});
@@ -262,7 +262,7 @@ export function SettingsPage() {
? {
tmdbApiKey: settings.tmdbApiKey,
backPort: settings.backPort,
authPassword: settings.authPassword || '',
authPassword: settings.authPassword || "",
}
: undefined,
});
@@ -302,7 +302,7 @@ export function SettingsPage() {
<Input
id="tmdbApiKey"
type="password"
{...register('tmdbApiKey')}
{...register("tmdbApiKey")}
/>
{errors.tmdbApiKey && (
<p className="text-xs text-destructive">
@@ -316,7 +316,7 @@ export function SettingsPage() {
<Input
id="backPort"
type="number"
{...register('backPort')}
{...register("backPort")}
/>
{errors.backPort && (
<p className="text-xs text-destructive">
@@ -330,7 +330,7 @@ export function SettingsPage() {
<Input
id="authPassword"
type="password"
{...register('authPassword')}
{...register("authPassword")}
placeholder="Leave empty to disable"
/>
</div>
@@ -340,7 +340,7 @@ export function SettingsPage() {
disabled={!isDirty || updateSettings.isPending}
>
<Save className="mr-2 h-4 w-4" />
{updateSettings.isPending ? 'Saving...' : 'Save Settings'}
{updateSettings.isPending ? "Saving..." : "Save Settings"}
</Button>
</CardContent>
</Card>
@@ -457,11 +457,11 @@ export function SettingsPage() {
<CardContent>
<ul className="text-xs text-muted-foreground list-disc pl-4 mb-3 space-y-0.5">
<li>
Entries with all episodes watched → set to{' '}
Entries with all episodes watched → set to{" "}
<strong>Completed</strong>
</li>
<li>
Entries marked Completed but missing episodes → downgrade to{' '}
Entries marked Completed but missing episodes → downgrade to{" "}
<strong>Watching</strong>
</li>
<li>
@@ -469,7 +469,7 @@ export function SettingsPage() {
set to <strong>Watching</strong>
</li>
<li>
Entries in Watchlist with no status → set to{' '}
Entries in Watchlist with no status → set to{" "}
<strong>Plan to Watch</strong>
</li>
</ul>
@@ -0,0 +1,81 @@
import { useState } from "react";
import { Link } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { watchBuddyApi } from "@/api/watchBuddy";
import { Input } from "@/components/ui/input";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Skeleton } from "@/components/ui/skeleton";
import { Search, Users } from "lucide-react";
import { useDebounce } from "@/hooks/useDebounce";
export function WatchBuddiesPage() {
const [search, setSearch] = useState("");
const debouncedSearch = useDebounce(search, 300);
const { data: buddies = [], isLoading } = useQuery({
queryKey: ["watch-buddies", "all", debouncedSearch],
queryFn: () => watchBuddyApi.search(debouncedSearch || undefined),
});
return (
<div className="animate-page-enter space-y-6">
<div className="flex items-center gap-2">
<Users className="h-6 w-6 text-primary" />
<h1 className="text-2xl font-bold">Watch Buddies</h1>
</div>
<div className="relative w-full max-w-xs">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Search buddies..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-10"
/>
</div>
{isLoading ? (
<div className="grid grid-cols-3 gap-4 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 xl:grid-cols-8">
{Array.from({ length: 16 }).map((_, i) => (
<div key={i} className="flex flex-col items-center gap-2">
<Skeleton className="h-24 w-24 rounded-full" />
<Skeleton className="h-4 w-20" />
</div>
))}
</div>
) : buddies.length === 0 ? (
<div className="flex h-40 items-center justify-center text-muted-foreground">
No buddies found.
</div>
) : (
<div className="grid grid-cols-3 gap-4 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 xl:grid-cols-8">
{buddies.map((buddy) => (
<Link
key={buddy.id}
to={`/watch-buddies/${buddy.id}`}
className="group flex flex-col items-center gap-2 text-center"
>
<Avatar className="h-24 w-24 transition-transform group-hover:scale-105">
{buddy.medias?.some((m: any) => m.type === "profiles") &&
(() => {
const pic = buddy.medias!.find(
(m: any) => m.type === "profiles",
)!;
const url = `${import.meta.env.VITE_API_URL || ""}/api/v1/media/watch-buddies/profiles/preview/${pic.path.replace(/\.[^.]+$/, "_preview.jpg")}`;
return <AvatarImage src={url} alt={buddy.name} />;
})()}
<AvatarFallback className="bg-primary/10 text-primary text-lg">
{buddy.name
.split(" ")
.map((n) => n[0])
.join("")}
</AvatarFallback>
</Avatar>
<p className="text-sm font-medium line-clamp-2">{buddy.name}</p>
</Link>
))}
</div>
)}
</div>
);
}
@@ -0,0 +1,669 @@
import { useState } from "react";
import { useParams, Link, useNavigate } from "react-router-dom";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { watchBuddyApi } from "@/api/watchBuddy";
import { Button } from "@/components/ui/button";
import { ConfirmDialog } from "@/components/dialogs/ConfirmDialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Skeleton } from "@/components/ui/skeleton";
import { Separator } from "@/components/ui/separator";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
Loader2,
ArrowLeft,
Film,
Tv,
Trash2,
ChevronDown,
ChevronUp,
Camera,
Phone,
Mail,
Upload,
} from "lucide-react";
import { format } from "date-fns";
import { getPosterUrl } from "@/lib/media-utils";
import type { WatchBuddy, EntrySeen } from "@/types";
const GENDER_OPTIONS = ["Male", "Female"];
export function WatchBuddyProfilePage() {
const { id } = useParams<{ id: string }>();
const buddyId = parseInt(id!, 10);
const queryClient = useQueryClient();
const { data: buddy, isLoading } = useQuery({
queryKey: ["watch-buddy", buddyId],
queryFn: () => watchBuddyApi.getById(buddyId),
enabled: !!buddyId,
});
const { data: history, isLoading: historyLoading } = useQuery({
queryKey: ["watch-buddy", buddyId, "history"],
queryFn: () => watchBuddyApi.getHistory(buddyId),
enabled: !!buddyId,
});
const [editMode, setEditMode] = useState(false);
const [form, setForm] = useState<Partial<WatchBuddy>>({});
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [showAllHistory, setShowAllHistory] = useState(false);
const [showUploadDialog, setShowUploadDialog] = useState(false);
const [uploadFile, setUploadFile] = useState<File | null>(null);
const [uploadDragOver, setUploadDragOver] = useState(false);
const [uploading, setUploading] = useState(false);
const HISTORY_PREVIEW_COUNT = 16;
const navigate = useNavigate();
const saveMutation = useMutation({
mutationFn: (data: Partial<WatchBuddy>) =>
watchBuddyApi.update(buddyId, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["watch-buddy", buddyId] });
setEditMode(false);
},
});
const deleteMutation = useMutation({
mutationFn: () => watchBuddyApi.remove(buddyId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["watch-buddies"] });
navigate("/watch-buddies", { replace: true });
},
});
const startEdit = () => {
if (buddy) setForm({ ...buddy });
setEditMode(true);
};
const handleSave = () => {
saveMutation.mutate(form);
};
const handleUpload = async () => {
if (!uploadFile) return;
setUploading(true);
try {
await watchBuddyApi.uploadProfilePicture(buddyId, uploadFile);
queryClient.invalidateQueries({ queryKey: ["watch-buddy", buddyId] });
setShowUploadDialog(false);
setUploadFile(null);
} finally {
setUploading(false);
}
};
if (isLoading || !buddy) {
return (
<div className="animate-page-enter space-y-6">
<Skeleton className="h-8 w-48" />
<Skeleton className="h-48 w-full rounded-xl" />
</div>
);
}
// Build combined timeline
const entrySeens: (EntrySeen & { entry?: any })[] = history?.entrySeens || [];
const episodeSeens: any[] = history?.episodeSeens || [];
const timeline = [
...entrySeens.map((r) => ({
id: `e-${r.id}`,
date: r.date_seen,
type: "movie" as const,
title: r.entry?.title ?? "Unknown",
link: `/entry/${r.entry_id}`,
poster: getPosterUrl(r.entry),
subtitle: r.entry?.is_tvseries ? "TV Series" : "Movie",
})),
...episodeSeens.map((r: any) => {
const seasonId = r.episode?.season?.id;
const epId = r.episode_id;
return {
id: `ep-${r.id}`,
date: r.date_seen,
type: "episode" as const,
title: r.episode?.season?.entry?.title ?? "Unknown",
link:
seasonId && epId
? `/entry/${r.entry_id}/season/${seasonId}/episode/${epId}`
: `/entry/${r.entry_id}`,
poster: getPosterUrl(r.episode?.season?.entry),
subtitle: `S${r.episode?.season?.season_number ?? "?"} E${r.episode?.episode_number ?? "?"} — ${r.episode?.name ?? ""}`,
};
}),
].sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
// Group by month for timeline
const grouped = timeline.reduce(
(acc, item) => {
const month = format(new Date(item.date), "MMMM yyyy");
if (!acc[month]) acc[month] = [];
acc[month].push(item);
return acc;
},
{} as Record<string, typeof timeline>,
);
// Count unique entries for watch history section
const entryMap = new Map<
string,
{ title: string; poster: string; link: string; count: number }
>();
for (const item of timeline) {
const existing = entryMap.get(item.title);
if (existing) {
existing.count++;
} else {
entryMap.set(item.title, {
title: item.title,
poster: item.poster,
link: item.link,
count: 1,
});
}
}
const watchedEntries = Array.from(entryMap.values());
const profilePic = buddy.medias?.find(
(m) => (m.type as string) === "profiles",
);
const profilePicUrl = profilePic
? `${import.meta.env.VITE_API_URL || ""}/api/v1/media/watch-buddies/profiles/preview/${profilePic.path.replace(/\.[^.]+$/, "_preview.jpg")}`
: null;
return (
<div className="animate-page-enter space-y-8">
<Link
to="/watch-buddies"
className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
>
<ArrowLeft className="h-4 w-4" />
Back to Buddies
</Link>
{/* Header */}
<div className="flex items-start gap-4">
<button
type="button"
className="group relative shrink-0"
onClick={() => setShowUploadDialog(true)}
title="Change profile picture"
>
<Avatar className="h-20 w-20">
{profilePicUrl && (
<AvatarImage src={profilePicUrl} alt={buddy.name} />
)}
<AvatarFallback className="bg-primary/10 text-primary text-xl">
{buddy.name
.split(" ")
.map((n) => n[0])
.join("")}
</AvatarFallback>
</Avatar>
<div className="absolute inset-0 flex items-center justify-center rounded-full bg-black/40 opacity-0 transition-opacity group-hover:opacity-100">
<Camera className="h-5 w-5 text-white" />
</div>
</button>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<h1 className="text-2xl font-bold">{buddy.name}</h1>
{buddy.buddy_type && buddy.buddy_type !== "person" && (
<Badge variant="secondary" className="capitalize">
{buddy.buddy_type}
</Badge>
)}
</div>
{buddy.gender && (
<p className="text-sm text-muted-foreground">{buddy.gender}</p>
)}
{/* Contact icons */}
{(buddy.instagram || buddy.discord || buddy.phone || buddy.email) && (
<div className="mt-1 flex flex-wrap items-center gap-3 text-sm text-muted-foreground">
{buddy.instagram && (
<a
href={`https://instagram.com/${buddy.instagram.replace(/^@/, "")}`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 transition-colors hover:text-pink-500"
title={`Instagram: ${buddy.instagram}`}
>
<svg
className="h-3.5 w-3.5"
viewBox="0 0 24 24"
fill="currentColor"
>
<path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z" />
</svg>
<span>{buddy.instagram}</span>
</a>
)}
{buddy.discord && (
<span
className="inline-flex items-center gap-1"
title={`Discord: ${buddy.discord}`}
>
<svg
className="h-3.5 w-3.5"
viewBox="0 0 24 24"
fill="currentColor"
>
<path d="M20.317 4.37a19.791 19.791 0 00-4.885-1.515.074.074 0 00-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 00-5.487 0 12.64 12.64 0 00-.617-1.25.077.077 0 00-.079-.037A19.736 19.736 0 003.677 4.37a.07.07 0 00-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 00.031.057 19.9 19.9 0 005.993 3.03.078.078 0 00.084-.028 14.09 14.09 0 001.226-1.994.076.076 0 00-.041-.106 13.107 13.107 0 01-1.872-.892.077.077 0 01-.008-.128 10.2 10.2 0 00.372-.292.074.074 0 01.077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 01.078.01c.12.098.246.198.373.292a.077.077 0 01-.006.127 12.299 12.299 0 01-1.873.892.077.077 0 00-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 00.084.028 19.839 19.839 0 006.002-3.03.077.077 0 00.032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 00-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z" />
</svg>
<span>{buddy.discord}</span>
</span>
)}
{buddy.phone && (
<a
href={`tel:${buddy.phone}`}
className="inline-flex items-center gap-1 transition-colors hover:text-green-500"
title={`Phone: ${buddy.phone}`}
>
<Phone className="h-3.5 w-3.5" />
<span>{buddy.phone}</span>
</a>
)}
{buddy.email && (
<a
href={`mailto:${buddy.email}`}
className="inline-flex items-center gap-1 transition-colors hover:text-blue-500"
title={`Email: ${buddy.email}`}
>
<Mail className="h-3.5 w-3.5" />
<span>{buddy.email}</span>
</a>
)}
</div>
)}
<p className="text-xs text-muted-foreground mt-1">
Watched together: {timeline.length} time
{timeline.length !== 1 ? "s" : ""}
</p>
{buddy.note && (
<p className="mt-2 text-sm text-muted-foreground italic max-w-prose">
{buddy.note}
</p>
)}
</div>
{!editMode && (
<div className="ml-auto flex gap-1 shrink-0">
<Button
variant="outline"
size="sm"
className="text-destructive"
onClick={() => setShowDeleteConfirm(true)}
>
<Trash2 className="h-4 w-4" />
</Button>
<Button variant="outline" size="sm" onClick={startEdit}>
Edit
</Button>
</div>
)}
</div>
{/* Edit mode */}
{editMode ? (
<Card>
<CardHeader>
<CardTitle>Edit Details</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{/* Name + Type + Gender */}
<div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
<div className="space-y-2">
<Label>Name</Label>
<Input
value={form.name ?? ""}
onChange={(e) => setForm({ ...form, name: e.target.value })}
/>
</div>
<div className="space-y-2">
<Label>Type</Label>
<Select
value={form.buddy_type ?? "person"}
onValueChange={(v) => setForm({ ...form, buddy_type: v })}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="person">Person</SelectItem>
<SelectItem value="group">Group</SelectItem>
</SelectContent>
</Select>
</div>
{form.buddy_type !== "group" && (
<div className="space-y-2">
<Label>Gender</Label>
<Select
value={form.gender ?? ""}
onValueChange={(v) =>
setForm({ ...form, gender: v || null })
}
>
<SelectTrigger>
<SelectValue placeholder="Select gender" />
</SelectTrigger>
<SelectContent>
{GENDER_OPTIONS.map((g) => (
<SelectItem key={g} value={g}>
{g || "Not set"}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
</div>
{/* Contact fields */}
<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
<div className="space-y-2">
<Label>Instagram</Label>
<Input
value={form.instagram ?? ""}
onChange={(e) =>
setForm({ ...form, instagram: e.target.value || null })
}
/>
</div>
<div className="space-y-2">
<Label>Discord</Label>
<Input
value={form.discord ?? ""}
onChange={(e) =>
setForm({ ...form, discord: e.target.value || null })
}
/>
</div>
<div className="space-y-2">
<Label>Phone</Label>
<Input
value={form.phone ?? ""}
onChange={(e) =>
setForm({ ...form, phone: e.target.value || null })
}
/>
</div>
<div className="space-y-2">
<Label>Email</Label>
<Input
value={form.email ?? ""}
onChange={(e) =>
setForm({ ...form, email: e.target.value || null })
}
/>
</div>
</div>
<div className="space-y-2">
<Label>Note</Label>
<textarea
value={form.note ?? ""}
onChange={(e) =>
setForm({ ...form, note: e.target.value || null })
}
placeholder="Optional notes about this buddy..."
className="flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-xs placeholder:text-muted-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
<div className="flex gap-2">
<Button onClick={handleSave} disabled={saveMutation.isPending}>
{saveMutation.isPending && (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
)}
Save
</Button>
<Button variant="outline" onClick={() => setEditMode(false)}>
Cancel
</Button>
</div>
</CardContent>
</Card>
) : (
<>{/* Empty — contacts now shown under the name */}</>
)}
<Separator />
{/* Watch History — poster grid */}
<div className="space-y-4">
<h2 className="text-lg font-semibold">Watch History</h2>
{historyLoading ? (
<div className="grid grid-cols-4 gap-3 sm:grid-cols-5 md:grid-cols-6 lg:grid-cols-8">
{Array.from({ length: 6 }).map((_, i) => (
<Skeleton key={i} className="aspect-2/3 w-full rounded-lg" />
))}
</div>
) : watchedEntries.length === 0 ? (
<p className="text-sm text-muted-foreground">No watch history yet.</p>
) : (
<>
<div className="grid grid-cols-4 gap-3 sm:grid-cols-5 md:grid-cols-6 lg:grid-cols-8">
{(showAllHistory
? watchedEntries
: watchedEntries.slice(0, HISTORY_PREVIEW_COUNT)
).map((entry) => (
<Link
key={entry.title}
to={entry.link}
className="group space-y-2"
>
<div className="relative aspect-2/3 overflow-hidden rounded-lg bg-muted">
{entry.poster &&
entry.poster !== "/images/default-poster.png" ? (
<img
src={entry.poster}
alt=""
className="h-full w-full object-cover transition-transform group-hover:scale-105"
/>
) : (
<div className="flex h-full items-center justify-center text-xs text-muted-foreground">
No poster
</div>
)}
{entry.count > 1 && (
<Badge
variant="secondary"
className="absolute top-1.5 right-1.5 text-[10px]"
>
×{entry.count}
</Badge>
)}
</div>
<p className="truncate text-xs font-medium">{entry.title}</p>
</Link>
))}
</div>
{watchedEntries.length > HISTORY_PREVIEW_COUNT && (
<div className="flex justify-center">
<Button
variant="ghost"
size="sm"
onClick={() => setShowAllHistory(!showAllHistory)}
>
{showAllHistory ? (
<>
<ChevronUp className="mr-1 h-4 w-4" />
Show less
</>
) : (
<>
<ChevronDown className="mr-1 h-4 w-4" />
Show all ({watchedEntries.length})
</>
)}
</Button>
</div>
)}
</>
)}
</div>
{/* Timeline */}
<div className="space-y-4">
<h2 className="text-lg font-semibold">Timeline</h2>
{historyLoading ? (
<Skeleton className="h-48 w-full" />
) : timeline.length === 0 ? (
<p className="text-sm text-muted-foreground">No timeline yet.</p>
) : (
<div className="space-y-6">
{Object.entries(grouped).map(([month, items]) => (
<div key={month} className="space-y-2">
<h3 className="sticky top-0 z-10 bg-background py-1 text-sm font-semibold text-muted-foreground">
{month}
</h3>
<div className="space-y-1">
{items.map((item) => (
<Link
key={item.id}
to={item.link}
className="flex items-center gap-3 rounded-lg border border-border p-2 transition-colors hover:bg-accent/50"
>
<Badge variant="outline" className="shrink-0">
{item.type === "movie" ? (
<Film className="h-3 w-3" />
) : (
<Tv className="h-3 w-3" />
)}
</Badge>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">
{item.title}
</p>
<p className="text-xs text-muted-foreground">
{format(new Date(item.date), "MMM d")} —{" "}
{item.subtitle}
</p>
</div>
</Link>
))}
</div>
</div>
))}
</div>
)}
</div>
<ConfirmDialog
open={showDeleteConfirm}
onOpenChange={setShowDeleteConfirm}
title="Delete Buddy"
description={`Are you sure you want to delete "${buddy.name}"? This cannot be undone.`}
confirmLabel="Delete"
variant="destructive"
onConfirm={() => deleteMutation.mutate()}
/>
{/* Profile picture upload dialog */}
<Dialog open={showUploadDialog} onOpenChange={setShowUploadDialog}>
<DialogContent className="sm:max-w-sm">
<DialogHeader>
<DialogTitle>Upload Profile Picture</DialogTitle>
</DialogHeader>
<div
className={`flex flex-col items-center justify-center gap-4 rounded-lg border-2 border-dashed p-8 transition-colors ${
uploadDragOver ? "border-primary bg-primary/5" : "border-border"
}`}
onDragOver={(e) => {
e.preventDefault();
setUploadDragOver(true);
}}
onDragLeave={() => setUploadDragOver(false)}
onDrop={(e) => {
e.preventDefault();
setUploadDragOver(false);
const file = e.dataTransfer.files?.[0];
if (file?.type.startsWith("image/")) setUploadFile(file);
}}
>
{uploadFile ? (
<div className="text-center">
<img
src={URL.createObjectURL(uploadFile)}
alt="Preview"
className="mx-auto mb-3 h-32 w-32 rounded-full object-cover"
/>
<p className="text-sm font-medium">{uploadFile.name}</p>
<Button
variant="ghost"
size="sm"
className="mt-1"
onClick={() => setUploadFile(null)}
>
Remove
</Button>
</div>
) : (
<>
<Upload className="h-8 w-8 text-muted-foreground" />
<p className="text-sm text-muted-foreground text-center">
Drag & drop an image here, or click to browse
</p>
<label className="cursor-pointer">
<input
type="file"
accept="image/*"
className="hidden"
onChange={(e) => {
const file = e.target.files?.[0];
if (file) setUploadFile(file);
}}
/>
<Button
variant="outline"
size="sm"
type="button"
onClick={(e) => {
const input = (e.currentTarget as HTMLElement)
.previousElementSibling as HTMLInputElement;
input?.click();
}}
>
Choose File
</Button>
</label>
</>
)}
</div>
<div className="flex justify-end gap-2">
<Button
variant="outline"
onClick={() => {
setShowUploadDialog(false);
setUploadFile(null);
}}
>
Cancel
</Button>
<Button onClick={handleUpload} disabled={!uploadFile || uploading}>
{uploading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Upload
</Button>
</div>
</DialogContent>
</Dialog>
</div>
);
}